目录

1.工具

2.流程 见下图

3.具体过程

3.1 unity程序编写

3.1.1 创建Unity项目

3.1.2 制作相关控件

3.1.3 编写脚本

3.2 unity 项目导出

3.2.1 External Tools 的设置

3.2.2 Player Settings的设置

3.2.3 导出

3.3 Android项目集成

3.3.1 创建项目

3.3.2 集成unity

3.4 Android项目调用


1.工具

AndroidStudio:

Android Gradle Plugin Version 3.5.2

Gradle Version 5.4.1

Unity 3D:

2018.4.30f1

2.流程 见下图

2.1 android 加载unity包

2.2 android 点击原生按钮调用unity方法,更新UnityUI

/*** // objectName: Unity 对象的名称* // methodName: Unity 对象绑定的脚本方法名* // message: 自定义消息**/
UnityPlayer.UnitySendMessage("Canvas/Button_Show", "ShowText", "Android 数据");

2.3 Unity 点击unity内部按钮调用android方法更新AndroidUI,Android响应被调回应数据,unity回去数据更新UnityUi

AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
//传入方法名 参数
string v = jo.Call<string>("CallAndroidShow","Unity 数据");//如果没有返回
jo.Call("CallAndroidShow");

3.具体过程

3.1 unity程序编写

3.1.1 创建Unity项目

创建一个3D项目 版本是2018.4.30f1

3.1.2 制作相关控件

添加两个控件:

1.text name:Text1

2.button name:Button_Show

3.1.3 编写脚本

编写一个脚本:ShowButton.cs。并挂载在Button_Show控件上

脚本内容:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class ShowButton : MonoBehaviour
{public Text textShow;public Button show;//Start is called before the first frame update//点击unity按钮后调用android方法public void CallAndroidShowAa(){// 不知道为啥不行//AndroidJavaClass jo =  new AndroidJavaClass("com.unity2android.unityplugin.AndroidActivity");//jo.Call("CallAndroidShow");show.transform.Find("Text").GetComponent<Text>().text = "调取Android数据";AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");//传入方法名 参数string v = jo.Call<string>("CallAndroidShow","Unity 数据");textShow.text = v;}//提供一个android调用的方法 android调用传入数据unity更新UIpublic void ShowText(string message){textShow.text = "" + message;}// Start is called before the first frame updatevoid Start(){//点击事件show.onClick.AddListener(CallAndroidShowAa);}// Update is called once per framevoid Update(){}
}

挂在后将控件传入脚本:

3.2 unity 项目导出

3.2.1 External Tools 的设置

路径:Edit->Preferences->External Tools

SDK、JDK、NDK 都需要勾选如果本地有用本地的比较快,

3.2.2 Player Settings的设置

路径:File->BuildSettings->Player Settings

1.修改Company name和Product Name 涉及后面的包名

2.版本修改

package name 是和  Company name、Product Name关联的

version和bundle version Code我猜一个是真正的版本号一个是显示的版本号,这个可以不改,但是继承的时候如果有更改unity不改再集成会报错,不知道为啥。

3.cpu架构的选择

如果不选择X86就不用Scriptiong Backend选择IL2CPP。

3.2.3 导出

漫长的等待。

3.3 Android项目集成

3.3.1 创建项目

这个包名要和unity导出的一致

3.3.2 集成unity

3.3.2.1 查看unity 导出的结构

3.3.2.2 集成jar

将unity 3D导出的jar复制到android项目下,

Project->unityplugin->app->libs

右键 add As Library

3.3.2.3 集成assets

将unity包中的assets复制到APP->src->main下

3.3.2.4 集成jniLibs

将unity 导出包中的jinLibs全部复制到APP->src->main下

3.3.2.5 修改清单文件

将unity包中的清单文件打开,把android项目中清单文件不包含的全部粘贴过去其中

<activity android:name="com.unity2android.unityplugin.UnityPlayerActivity">修改为自己项目路径,里面的

<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LEANBACK_LAUNCHER" /> </intent-filter>

需要屏蔽掉

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"package="com.unity2android.unityplugin"android:installLocation="preferExternal"><supports-screensandroid:anyDensity="true"android:largeScreens="true"android:normalScreens="true"android:smallScreens="true"android:xlargeScreens="true" /><applicationandroid:banner="@drawable/app_banner"android:icon="@mipmap/app_icon"android:isGame="true"android:label="@string/app_name"android:theme="@style/UnityThemeSelector">
<!--  修改为       android:name="com.unity3d.player.UnityPlayerActivity">--><activityandroid:name="com.unity2android.unityplugin.UnityPlayerActivity">android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density"android:hardwareAccelerated="false"android:label="@string/app_name"android:launchMode="singleTask"android:screenOrientation="fullSensor">
<!--            屏蔽掉--><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /></intent-filter><meta-dataandroid:name="unityplayer.UnityActivity"android:value="true" /></activity><meta-dataandroid:name="unity.build-id"android:value="487dc281-c378-4b43-9120-9f3bb7741898" /><meta-dataandroid:name="unity.splash-mode"android:value="0" /><meta-dataandroid:name="unity.splash-enable"android:value="True" /><meta-dataandroid:name="unity.builder"android:value="\12369984484064" /></application><uses-feature android:glEsVersion="0x00020000" /><uses-permission android:name="android.permission.INTERNET" /><uses-featureandroid:name="android.hardware.touchscreen"android:required="false" /><uses-featureandroid:name="android.hardware.touchscreen.multitouch"android:required="false" /><uses-featureandroid:name="android.hardware.touchscreen.multitouch.distinct"android:required="false" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

3.3.2.6修改相关配置文件

将unity 中build.gradle文件下的补全到android项目中的build.gradle中

Android项目的Project

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {mavenCentral()google()jcenter()}dependencies {classpath 'com.android.tools.build:gradle:3.5.2'// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files}
}allprojects {repositories {mavenCentral()google()jcenter()flatDir {dirs 'libs'}}
}task clean(type: Delete) {delete rootProject.buildDir
}

Andorid 项目的mode

apply plugin: 'com.android.application'android {compileSdkVersion 30buildToolsVersion "30.0.0"defaultConfig {applicationId "com.unity2android.unityplugin"minSdkVersion 19targetSdkVersion 30versionCode 1versionName "1.0"ndk {abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86'}testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"}lintOptions {abortOnError false}aaptOptions {noCompress = ['.unity3d', '.ress', '.resource', '.obb']}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}buildTypes {debug {minifyEnabled falseuseProguard falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'jniDebuggable true}release {minifyEnabled falseuseProguard falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'signingConfig signingConfigs.debug}}packagingOptions {doNotStrip '*/armeabi-v7a/*.so'doNotStrip '*/arm64-v8a/*.so'doNotStrip '*/x86/*.so'}bundle {language {enableSplit = false}density {enableSplit = false}abi {enableSplit = true}}}dependencies {implementation fileTree(include: ['*.jar'], dir: 'libs')implementation 'androidx.appcompat:appcompat:1.0.2'implementation 'androidx.constraintlayout:constraintlayout:1.1.3'testImplementation 'junit:junit:4.12'androidTestImplementation 'androidx.test.ext:junit:1.1.0'androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'implementation files('libs/unity-classes.jar')
}

没有啥补啥

3.4 Android项目调用

新建一个AndroidActivity

package com.unity2android.unityplugin;import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;import com.unity2android.unityplugin.R;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;import static android.content.ContentValues.TAG;public class AndroidActivity extends UnityPlayerActivity {private TextView tv;private LinearLayout ll;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_android);ll = findViewById(R.id.ll);ll.addView(mUnityPlayer);Button switch_ = findViewById(R.id.switch_);Button clear = findViewById(R.id.clear);tv = findViewById(R.id.tv);switch_.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {CallUnityShow("Canvas/Button_Show", "ShowText", "Android 数据");}});clear.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {CallUnityShow("Canvas/Button_Show", "ShowText", "");tv.setText("");}});ll.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.d(TAG, "onClick: lll");}});}/*** // objectName: Unity 对象的名称* // methodName: Unity 对象绑定的脚本方法名* // message: 自定义消息** @param s1* @param s2* @param s3*/public void CallUnityShow(String s1, String s2, String s3) {UnityPlayer.UnitySendMessage(s1, s2, s3);Log.d(TAG, "CallUnityShow: 456");}public String CallAndroidShow(final String s) {Log.d(TAG, "CallAndroidShow: 123");runOnUiThread(new Runnable() {@Overridepublic void run() {tv.setText(s);}});return "Android 返回";}@Overrideprotected void onDestroy() {super.onDestroy();// UnityPlayer.UnitySendMessage("Manager", "Unload", "");mUnityPlayer.quit();}// Pause Unity@Overrideprotected void onPause() {super.onPause();mUnityPlayer.pause();}// Resume Unity@Overrideprotected void onResume() {super.onResume();mUnityPlayer.resume();}/*** 按键点击事件*/@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {onDestroy();}return true;}
}

对应的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:id="@+id/ll"android:layout_width="match_parent"android:layout_height="400dp"android:orientation="vertical"></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:orientation="horizontal"android:layout_height="wrap_content"><Buttonandroid:id="@+id/switch_"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="text"/><Buttonandroid:id="@+id/clear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="clear"/></LinearLayout><TextViewandroid:id="@+id/tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="unity"/></LinearLayout>

Android项目源码:https://download.csdn.net/download/qq_35698774/19990943

Unity 导出的jar:https://download.csdn.net/download/qq_35698774/19990999

Unity 项目:https://download.csdn.net/download/qq_35698774/19991018

转发表明出处

Android和Unity互调相关推荐

  1. Android开发之android与JS互调 | Android与H5互调(附源码)

    我们先看下JS代码: <!DOCTYPE html> <html lang="en"> <head><meta charset=" ...

  2. WebView详解与简单实现Android与H5互调

    为什么要学习Android与H5互调? 微信,QQ空间等大量软件都内嵌了H5,不得不说是一种趋势.Android与H5互调可以让我们的实现混合开发,至于混合开发就是在一个App中内嵌一个轻量级的浏览器 ...

  3. Android与Unity的交互

    Android与Unity的交互方式 Unity做好功能之后提供classes.jar文件,导入到Android Studio中进行之后的功能开发.最后由Android Studio打包APK. An ...

  4. Android 与 Unity(随笔录)

    前言 最近换了工作,公司是做康复领域的,由于项目需求需要,Android产品中必须加入VR元素,将虚拟场景与Android融合,打造一个用户满意的产品. 本人是做Android开发的,思考的是把Uni ...

  5. Android与Unity交互及手机震动控制

    背景 Unity开发过程中,自身提供的API或方案无法满足需求时,就需要Android工程交互通信.网络上交互方案很多,通常为jar包和aar包,经过对比本人采用aar包来实现,过程相对简单. Uni ...

  6. Unity Android 之 Unity Android 交互(aar形式)动态申请权限功能实现(权限可人为怎加删减,并含代码工程)

    Unity Android 之 Unity Android 交互(aar形式)动态申请权限功能实现(权限可人为怎加删减,并含代码工程) 目录

  7. 【Unity3D学习记录#2】Android调用Unity界面 与 信息交互

    [Unity3D学习记录#2]Android调用Unity界面 与 信息交互 Android 调用 Unity Unity项目构建 Android项目构建 Android 与 Unity 的信息交互 ...

  8. Android引用RN第三方控件,Android和RN互调方式,最近开发心得

    "有人住高楼,有人在深沟,有人光万丈,有人一身锈,世人万千种,浮云莫去求,斯人若彩虹,遇上方知有." 时隔四季,我重新开始了我的文章更新,so do you miss me? 前言 ...

  9. unity android 启动,Android启动Unity

    例如在一个android项目中,点击一个按钮,启动unity for android. 1.首先在Unity 引擎中将Unity3D项目build一下,需要在build settings--> ...

最新文章

  1. 【ES6】正则表达式的拓展
  2. 为什么一些机器学习模型需要对数据进行归一化?——1)归一化后加快了梯度下降求最优解的速度;2)归一化有可能提高精度...
  3. 给定地址段为0001H,仅通过变化偏移地址寻址,CPU的寻址范围为____到____
  4. 直方图应用:直方图均衡化,直方图匹配,对比直方图
  5. 英雄联盟手游主播否认部分英雄后期的作用,难道阿卡丽没未来?
  6. 【Linux系统编程】同步和互斥的概念
  7. One order search dynamic SQL build logic
  8. C语言中,全局变量滥用的后果竟如此严重?
  9. 《C++ Primer》7.3.4节练习
  10. 【TensorFlow】TensorFlow函数精讲之tf.nn.softmax_cross_entropy_with_logits
  11. react 开源项目_2020年2月Github上最热门的JavaScript开源项目
  12. [Vue] Computed property XXX was assigned to but it has no setter.
  13. 孙鑫-MFC笔记九--菜单编程
  14. 什么是“5个9”(99.999%)的可靠性?
  15. python threadPool 与 multiprocessing.Pool
  16. EOJ-1708//POJ3334
  17. 3D数学基础:图形与游戏开发 【第一章 简介】
  18. 左耳听风——笔记二:程序员练级攻略
  19. UrlRewrite重写url
  20. 关于flash跨域问题

热门文章

  1. 前端页面的pdf导出(h2c,jsPDF)
  2. 在线辅导平台,兼职赚钱,分享知识变现
  3. 复制粘贴代码时要注意空白字符的问题
  4. 使用阿里云短信服务测试功能发送短信到手机验证
  5. 华为Linux送的u盘,微软无奈,断供系统没用,华为和荣耀给用户赠送带Windows的U盘...
  6. 使用mpaas的iOS客户端如何一包支持任意环境切换(理论篇)
  7. 琶音和分解和弦的区别
  8. Java设计模式之 简单工厂模式和工厂方法实验报告书
  9. 游戏服务器后台的快速开发
  10. 在 build.gradle.kts 添加 maven 仓库