Unity和AndroidStudio 混合开发
这几天做项目,要求Unity开发的工程嵌套到AndroidStudio开发的应用里,记录下Unity和AndroidStudio开发遇到的问题
Unity
package com.unity3d.player;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public abstract class UnityReaderActivity extends UnityPlayerActivity {
public static UnityReaderActivity instance = null;
abstract protected void showMainActivity(String setToColor);
@Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
instance = this;
}
@Override
protected void onDestroy()
{
super.onDestroy();
instance = null;
}
}
通过AndroidStudio创建UnityRenderAvtivity.java,并放入Unity工程中,因为Android启动Unity工程是通过UnityPlayerActivity.java来启动的,所以UnityRenderAvtivity继承UnityPlayerActivity,这里可以重写父类的方法,实现我们自定义的功能
选择Android平台,勾选上Export Project 然后点击Export,导出完的目录结构如下
AndroidStudio
使用AndroidStudio创建Emprty Activity,包名要和Unity工程的包名一致,然后将unity导出文件目录下的unityLibrary文件夹以module形式导入Android Studio
修改build.gradle(module:app)
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.mskj.kongwan"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
//Add Code
ndk{
abiFilters 'armeabi-v7a'
}
//End
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation project(path: ':unityLibrary')
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//Add Code
implementation project(':unityLibrary')
implementation fileTree(
dir: project(':unityLibrary').getProjectDir().toString() + ('\\libs'),include: ['*.jar']
)
//End
}
修改build.gradle(Module:NativeAndroidApp)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
//Add Code
flatDir{
dirs "${project(':unityLibrary').projectDir}/libs"
}
//End
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
修改strings.xml(Module:app)
<resources>
<string name="app_name">unity_android</string>
//Add Code
<string name = "game_view_content_description">Game view</string>>
//End
<string name = "gounity_btn">Go Unity</string>
</resources>
删除AndroidManifest中部分代码(module:unityLibrary)
如果不屏蔽的话,会生成两个图标
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools">
<!-- <application>-->
<!-- <activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" android:screenOrientation="sensorPortrait" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false">-->
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
<!-- <meta-data android:name="unityplayer.UnityActivity" android:value="true" />-->
<!-- <meta-data android:name="android.notch_support" android:value="true" />-->
<!-- </activity>-->
<!-- <meta-data android:name="unity.splash-mode" android:value="2" />-->
<!-- <meta-data android:name="unity.splash-enable" android:value="True" />-->
<!-- <meta-data android:name="notch.config" android:value="portrait|landscape" />-->
<!-- <meta-data android:name="unity.build-id" android:value="3b539f22-f56f-4f2a-b331-0b94ec5e77ad" />-->
<!-- </application>-->
<uses-feature android:glEsVersion="0x00020000" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>
创建MainUnityActivity类(Module:app)
该类继承自UnityReaderActivity
package com.mystudio.testandroid;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import com.unity3d.player.UnityReaderActivity;
public class MainUnityActivity extends UnityReaderActivity {
//这个类调起Unity的场景
@Override
public boolean onKeyDown(int i, KeyEvent keyEvent)
{
//点击返回键跳转到主界面
if (i == KeyEvent.KEYCODE_BACK)
{
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();
}
return super.onKeyDown(i,keyEvent);
}
}
修改AndroidManifest(Module:app)
<?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.mskj.kongwan">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Unity_android"
tools:replace="android:icon, android:theme,android:allowBackup"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//Add Code
<activity android:name=".MainUnityActivity"
android:screenOrientation="portrait"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density"
android:hardwareAccelerated="false"
android:process=":Unity"
android:label="UnityProject">
</activity>
//End
</application>
</manifest>
修改MainActivity(Module:app)
package com.mystudio.testandroid;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.gounity);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GoUnity(v);
}
});
}
public void GoUnity(View view)
{
Intent intent = new Intent(this,MainUnityActivity.class);
startActivity(intent);
}
}
修改activity_main.xml(Module:app)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<Button
android:id="@+id/gounity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击事件"
tools:layout_editor_absoluteX="159dp"
tools:layout_editor_absoluteY="290dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
参考链接
https://blog.csdn.net/qq_40028144/article/details/108058407?utm_medium=distribute.pc_relevant.none-task-blog-searchFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-searchFromBaidu-1.control