Android对接Unity3D,原生View与Unity3D视图的层级关系
场景
- 1.很多人在对接unity的时候,难免产品会让你添加一些原生的view到unity视图上,但是你会发现所添加的原生view并不能被看见,你甚至开始怀疑自己的代码,但是确实代码没有错,只是原生的view被unity的UnityPlayer遮挡了,至于这个UnityPlayer后面会说到。
- 2.假如原生的activity只是单纯(有些产品可能要求其他骚操作)的加载一个unity场景,但是这个场景的模型又非常大,并且unity端没有给你一个加载场景的动画,那么很残忍的结果就是这个加载unity场景的过程中会出现界面黑屏、白屏甚至花屏(华为出现过)。这个时候产品发现不对,认为应该叫unity端加一个动画,但是,很残忍的是就算加了动画,仍然会出现短暂的界面黑屏、白屏甚至花屏。那么聪明的原生就说,我加一个原生的加载动画不就ojbk了?并且通过unity端的回调来取消这个动画不就非常优雅了。然而,然而发现新加的原生动画看不到,看到的是黑屏、白屏甚至花屏。好气!
分析
1、按照官方的文档集成,在原生中显现Unity3D场景首先是创建一个Activity,然后在这个Activity中实例化一个UnityPlayer对象就可以了(详细查看官方文档),注意这里有一个细节就是在Activity中放置UnityPlayer这个对象最好是帧布局,相对布局会卡顿,因为我们都知道,在原生中渲染速度:FrameLayout>LinearLayout>RelativeLayout,亲测,当模型过大的时候,RelativeLayout的容器基本上用不了。以下是放置unity的界面代码(不是小白直接跳过):
open abstract class UnityPlayerActivity : AppCompatActivity() {
protected lateinit var mUnityPlayer: BaseUnityPlayer // don't change the name of this variable; referenced from native code
//提示框
private var loading: LoadingDialog? = null
//白屏菊花
private var progress: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFormat(PixelFormat.RGBX_8888) // <--- This makes xperia play happy
mUnityPlayer = BaseUnityPlayer(this)
mUnityPlayer.requestFocus()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// To support deep linking, we need to make sure that the client can get access to
// the last sent intent. The clients access this through a JNI api that allows them
// to get the intent set on launch. To update that after launch we have to manually
// replace the intent with the one caught here.
setIntent(intent)
}
override fun onResume() {
super.onResume()
mUnityPlayer.resume()
mUnityPlayer.windowFocusChanged(true)//unity主动聚焦
}
override fun onPause() {
super.onPause()
mUnityPlayer.pause()
}
override fun onDestroy() {
mUnityPlayer.quit()
super.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mUnityPlayer.lowMemory()
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
if (level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {
mUnityPlayer.lowMemory()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
mUnityPlayer.configurationChanged(newConfig)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
mUnityPlayer.windowFocusChanged(hasFocus)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
return if (event.action == KeyEvent.ACTION_MULTIPLE) mUnityPlayer.injectEvent(event) else super.dispatchKeyEvent(event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return mUnityPlayer.injectEvent(event)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return mUnityPlayer.injectEvent(event)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
return mUnityPlayer.injectEvent(event)
}
/*API12*/
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
return mUnityPlayer.injectEvent(event)
}
/**
* 用于网络加载提示的弹窗
*/
protected fun showLoading() {
loading = loading ?: LoadingDialog()
loading?.setCallBack(object : LoadingDialog.OnDisMissCallBack {
override fun disMiss() {
cancelCurrent()
}
})
if (loading?.isAdded == false) {
loading?.show(supportFragmentManager, "Loading")
} else {
loading?.dialog?.show()
}
}
protected fun disMisLoading() {
loading?.dismiss()
}
/**
* U3D白屏界面上的静态菊花
*/
protected fun showProgress() {
progress = progress ?: ProgressDialog.show(this, false, null)
if (!progress!!.isShowing) {
progress!!.show()
}
}
protected fun disMissProgress() {
progress!!.dismiss()
}
abstract fun cancelCurrent()
}
xml中(笔者放置UnityPlayer的界面布局):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:InnerView="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:CircleProgressBar="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.cninct.rmm.mvp.view.activity.MainUnityActivity">
<!--unity的宿主控件,顶层和该层都是用帧布局,提高绘制效率-->
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!--底部菜单栏-->
<include
android:id="@+id/layout_tab"
layout="@layout/view_main_tab"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"/>
......
Activity中:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_unity_main)
initView()
......
}
//首页相关控件的初始化
private fun initView() {
fl_content.addView(mUnityPlayer)
......
}
2、在正常显示之后就可以发现,其实真正显示Unity的就是一个布局容器fl_content,而fl_content是通过addView的方式将UnityPlayer添加进容器中,所以UnityPlayer也是一个View,继续查看UnityPlayer,一下是部分代码:
public class UnityPlayer extends FrameLayout implements d {
public static Activity currentActivity = null;
private static boolean n;
c a = new c(this, (byte) 0);
i b = null;
private boolean c = false;
private boolean d = true;
private l e = new l();
private final ConcurrentLinkedQueue f = new ConcurrentLinkedQueue();
private BroadcastReceiver g = null;
private boolean h = false;
private a i = new a(this, (byte) 0);
private TelephonyManager j;
private j k;
private ContextWrapper l;
private SurfaceView m;
private boolean o;
private Bundle p = new Bundle();
private n q;
private boolean r = false;
private ProgressBar s = null;
private Runnable t = new Runnable() {
public final void run() {
int p = UnityPlayer.this.nativeActivityIndicatorStyle();
if (p >= 0) {
if (UnityPlayer.this.s == null) {
UnityPlayer.this.s = new ProgressBar(UnityPlayer.this.l, null, new int[]{16842874, 16843401, 16842873, 16843400}[p]);
UnityPlayer.this.s.setIndeterminate(true);
UnityPlayer.this.s.setLayoutParams(new LayoutParams(-2, -2, 51));
UnityPlayer.this.addView(UnityPlayer.this.s);
}
UnityPlayer.this.s.setVisibility(0);
UnityPlayer.this.bringChildToFront(UnityPlayer.this.s);
}
}
};
...
以上可以发现,其实UnityPlayer就是继承的FrameLayout,并且可以猜测这个FrameLayout中有至少一个SurfaceView显示真正的模型场景等,因为普通View是没有这个能力去渲染的,只有通过SurfaceView开启线程去渲染(证据:在与Unity通信的时候,通过Unity的消息回调去更新UI会提示不能在非主线程中更新界面的提示)。所以原生View和Unity3D场景问题其实就是在这个UnityPlayer中的SurfaceView与我们的原生View发生了Z-Index上的冲突,或者说是遮挡。那么怎样把我们的原生View放在UnityPlayer上面呢?其实我们首先需要把SurfaceView的Z-Index降低。就像开发地图和多媒体播放一样,存在地图、多媒体、普通View的显示层级,我们需要将这些层级处理一下,通过SurfaceView的setZOrderOnTop方法和setZOrderMediaOverlay方法。当然如果没有多媒体不需要设置setZOrderMediaOverlay方法。
解决问题
直接贴代码了:
class BaseUnityPlayer(contextWrapper: ContextWrapper) : UnityPlayer(contextWrapper) {
override fun addView(child: View) {
if (child is SurfaceView) {
child.setZOrderOnTop(false)
}
super.addView(child)
}
}