Unity3D 与 安卓交互

安卓部分

创建安卓lib(jar) 供Unity使用

 gradel:

plugins {
    id 'com.android.library'
}

AndrodiManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iffy.unitytest">

</manifest>

类方法:

public class Model {
    //获取当前型号
    public String getPhoneModel() {
        Log.e("iffy", "I received the getPhoneModel message from unity");
        Log.e("iffy", "my model is" + android.os.Build.MODEL);
        return android.os.Build.MODEL;
    }
    //发送消息
    public void sendMessage(String s) {
        Log.e("iffy", "I received the message from unity" + s);
    }
}

使用make project 命令编译jar

拷出class.jar在Unity 使用


Unity3D部分

 jar包放入Unity 路径 Assets/Plugins/Android/classes.jar

添加脚本调用jar包接口 Assets/Scripts/Test.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
   AndroidJavaClass javaClass = null; //静态方法
   AndroidJavaObject aobj = null;//创建对象使用
   public Text titleB;
   public void StartGame(){
    titleB.text ="开始游戏";
	   
   }
   
   public void ExitGame(){
	   Application.Quit();
   }

   public void getModel(){
      titleB.text ="开始游戏????";
      //javaClass = new AndroidJavaClass("com.iffy.unitytest.Model");
      aobj = new AndroidJavaObject("com.iffy.unitytest.Model");
      titleB.text = aobj.Call<string>("getPhoneModel");
   }

}

绑定文本框和脚本

绑定按钮点击事件和脚本

项目代码:

GitHub - iffy1/Unitytest: interaction between Unity and Android

猜你喜欢

转载自blog.csdn.net/iffy1/article/details/127705097