Unity与Android交互问题整理

在做Untiy调用Android工程时,总是出现这样或那样的问题,为了避免遗忘,整理记录如下:

1. Unity3D中Android插件findviewbyid返回null

 用findViewById获取布局文件中的指定View时,在Android工程中是好使的,但是,放到Unity中,获取的为空指针。

异常log如下:

Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.unity.test4unity/org.doubango.imsdroid.Screens.ScreenHome}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2341)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:2165)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
at org.doubango.imsdroid.Services.Impl.ScreenService.show(ScreenService.java:132)
at org.doubango.imsdroid.Services.Impl.ScreenService.show(ScreenService.java:150)
at org.doubango.imsdroid.Screens.ScreenSplash$1.onReceive(ScreenSplash.java:63)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:868)
... 8 more
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at org.doubango.imsdroid.Screens.ScreenHome.onCreate(ScreenHome.java:94)
at android.app.Activity.performCreate(Activity.java:6049)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2294)
... 15 more

分析原因是下面代码在获取GridView时,返回null导致:

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.screen_home);
	mContext = this;
	ScreenHomeAdapter adapter = new ScreenHomeAdapter(ScreenHome.this);
	mGridView = (GridView) findViewById(R.id.screen_home_gridview);
     ......

网上查说问题的原因主要在于,在我们将自己的android工程打成jar插件时,原来的R.id.xxxxx已经被转换成相应的数字id编译进了jar包,而Unity3D在导出工程或是apk的时候,会对所有资源进行重新的id编译,这就导致我们jar中的旧id是无法获取到相应对象。

但有的View,例如Button,TextView都可以拿到,这块儿还有点搞不太清楚:(

解决方法:

修改GridView的获取方法,具体如下:

int viewID = getResources().getIdentifier("screen_home_gridview", "id", getPackageName());  
mGridView = (GridView)findViewById(viewID); 


2. Unity打包apk的时候报错 An asset is marked withHideFlags.DontSave but is included in the build

原因分析:

打包的时候报错 An asset is marked with HideFlags.DontSave but is included in thebuild,找来找去发现是由于UILabel 引用了Library/unityeditor resources中的字体引发的。

解决办法:

将Label之类的控件用到的字体改为 NGUI字体或自己定义的字体。

未完待续。。。

参考资料:

http://johncookie.iteye.com/blog/1997636

你可能感兴趣的:(Unity与android交互,unity,android,交互)