位置: 编程技术 - 正文

Building Unity3D Plugins for Android

编辑:rootadmin
Building Plugins for Android

推荐整理分享Building Unity3D Plugins for Android,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

This page describes Native Code Plugins for Android.

Building a Plugin for Android

To build a plugin for Android, you should first obtain the Android NDK and familiarize yourself with the steps involved in building a shared library.

If you are using C&#;&#; (.cpp) to implement the plugin you must ensure the functions are declared with C linkage to avoid name mangling issues.

Using Your Plugin from C#

Once built, the shared library should be copied to the Assets->Plugins->Android folder. Unity will then find it by name when you define a function like the following in the C# script:-

Please note that PluginName should not include the prefix (‘lib’) nor the extension (‘.so’) of the filename. You should wrap all native code methods with an additional C# code layer. This code should check Application.platform and call native methods only when the app is running on the actual device; dummy values can be returned from the C# code when running in the Editor. You can also use platform defines to control platform dependent code compilation.

Android Library Projects

You can drop pre-compiled Android library projects into the Assets->Plugins->Android folder. Pre-compiled means all .javafiles must have been compiled into jar files located in either the bin/ or the libs/ folder of the project. AndroidManifest.xml from these folders will get automatically merged with the main manifest file when the project is built.

See Android Library Projects for more details.

Deployment

For cross platform deployment, your project should include plugins for each supported platform (ie, libPlugin.so for Android, Plugin.bundle for Mac and Plugin.dll for Windows). Unity automatically picks the right plugin for the target platform and includes it with the player.

For specific Android platform (armv7, x), the libraries (lib*.so) should be placed in the following:

Assets/Plugins/Android/libs/x/

Assets/Plugins/Android/libs/armeabi-v7a/

Using Java Plugins

The Android plugin mechanism also allows Java to be used to enable interaction with the Android OS.

Building a Java Plugin for Android

There are several ways to create a Java plugin but the result in each case is that you end up with a .jar file containing the .class files for your plugin. One approach is to download the JDK, then compile your .java files from the command line with javac. This will create .class files which you can then package into a .jar with the jar command line tool. Another option is to use the EclipseIDE together with the ADT.

Note: Unity expects Java plugins to be built using JDK v1.6. If you are using v1.7, you should include “-source 1.6 -target 1.6” in the command line options to the compiler.

Using Your Java Plugin from Native Code

Once you have built your Java plugin (.jar) you should copy it to the Assets->Plugins->Android folder in the Unity project. Unity will package your .class files together with the rest of the Java code and then access the code using the Java Native Interface (JNI). JNI is used both when calling native code from Java and when interacting with Java (or the JavaVM) from native code.

To find your Java code from the native side you need access to the Java VM. Fortunately, that access can be obtained easily by adding a function like this to your C/C&#;&#; code:

This is all that is needed to start using Java from C/C&#;&#;. It is beyond the scope of this document to explain JNI completely. However, using it usually involves finding the class definition, resolving the constructor (<init>) method and creating a new object instance, as shown in this example:-

Using Your Java Plugin with helper classes

AndroidJNIHelper and AndroidJNI can be used to ease some of the pain with raw JNI.

AndroidJavaObject and AndroidJavaClass automate a lot of tasks and also use cacheing to make calls to Java faster. The combination of AndroidJavaObject and AndroidJavaClass builds on top of AndroidJNI and AndroidJNIHelper, but also has a lot of logic in its own right (to handle the automation). These classes also come in a ‘static’ version to access static members of Java classes.

You can choose whichever approach you prefer, be it raw JNI through AndroidJNI class methods, or AndroidJNIHelper together with AndroidJNI and eventually AndroidJavaObject/AndroidJavaClass for maximum automation and convenience.

UnityEngine.AndroidJNI is a wrapper for the JNI calls available in C (as described above). All methods in this class are static and have a 1:1 mapping to the Java Native Interface. UnityEngine.AndroidJNIHelper provides helper functionality used by the next level, but is exposed as public methods because they may be useful for some special cases.

Instances of UnityEngine.AndroidJavaObject and UnityEngine.AndroidJavaClass have a one-to-one mapping to an instance of java.lang.Object and java.lang.Class (or subclasses thereof) on the Java side, respectively. They essentially provide 3 types of interaction with the Java side:-

Call a methodGet the value of a fieldSet the value of a field

The Call is separated into two categories: Call to a ‘void’ method, and Call to a method with non-void return type. A generic type is used to represent the return type of those methods which return a non-void type. The Get and Set always take a generic type representing the field type.

Example 1

Here, we’re creating an instance of java.lang.String, initialized with a string of our choice and retrieving the hash value for that string.

The AndroidJavaObject constructor takes at least one parameter, the name of class for which we want to construct an instance. Any parameters after the class name are for the constructor call on the object, in this case the string “some_string”. The subsequent Call to hashCode() returns an ‘int’ which is why we use that as the generic type parameter to the Call method.

Building Unity3D Plugins for Android

Note: You cannot instantiate a nested Java class using dotted notation. Inner classes must use the $ separator, and it should work in both dotted and slashed format. So [android.view.ViewGroup$LayoutParams orandroid/view/ViewGroup$LayoutParams can be used, where a LayoutParams class is nested in a ViewGroup] class.

Example 2

One of the plugin samples above shows how to get the cache directory for the current application. This is how you would do the same thing from C# without any plugins:-

In this case, we start with AndroidJavaClass instead of AndroidJavaObject because we want to access a static member ofcom.unity3d.player.UnityPlayer rather than create a new object (an instance is created automatically by the Android UnityPlayer). Then we access the static field “currentActivity” but this time we use AndroidJavaObject as the generic parameter. This is because the actual field type (android.app.Activity) is a subclass of java.lang.Object, and any non-primitive typemust be accessed as AndroidJavaObject. The exceptions to this rule are strings, which can be accessed directly even though they don’t represent a primitive type in Java.

After that it is just a matter of traversing the Activity through getCacheDir() to get the File object representing the cache directory, and then calling getCanonicalPath() to get a string representation.

Of course, nowadays you don’t need to do that to get the cache directory since Unity provides access to the application’s cache and file directory with Application.temporaryCachePath and Application.persistentDataPath.

Example 3

Finally, here is a trick for passing data from Java to script code using UnitySendMessage.

The Java class com.unity3d.player.UnityPlayer now has a static method UnitySendMessage, equivalent to the iOSUnitySendMessage function on the native side. It can be used in Java to pass data to script code.

Here though, we call it directly from script code, which essentially relays the message on the Java side. This then calls back to the native/Unity code to deliver the message to the object named “Main Camera”. This object has a script attached which contains a method called “JavaMessage”.

Best practice when using Java plugins with Unity

As this section is mainly aimed at people who don’t have comprehensive JNI, Java and Android experience, we assume that theAndroidJavaObject/AndroidJavaClass approach has been used for interacting with Java code from Unity.

The first thing to note is that any operation you perform on an AndroidJavaObject or AndroidJavaClass is computationally expensive (as is the raw JNI approach). It is highly advisable to keep the number of transitions between managed and native/Java code to a minimum, for the sake of performance and also code clarity.

You could have a Java method to do all the actual work and then use AndroidJavaObject / AndroidJavaClass to communicate with that method and get the result. However, it is worth bearing in mind that the JNI helper classes try to cache as much data as possible to improve performance.

The Mono garbage collector should release all created instances of AndroidJavaObject and AndroidJavaClass after use, but it is advisable to keep them in a using(){} statement to ensure they are deleted as soon as possible. Without this, you cannot be sure when they will be destroyed. If you set AndroidJNIHelper.debug to true, you will see a record of the garbage collector’s activity in the debug output.

You can also call the .Dispose() method directly to ensure there are no Java objects lingering. The actual C# object might live a bit longer, but will be garbage collected by mono eventually.

Extending the UnityPlayerActivity Java Code

With Unity Android it is possible to extend the standard UnityPlayerActivity class (the primary Java class for the Unity Player on Android, similar to AppController.mm on Unity iOS).

An application can override any and all of the basic interaction between Android OS and Unity Android. You can enable this by creating a new Activity which derives from UnityPlayerActivity (UnityPlayerActivity.java can be found at/Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidPlayer/src/com/unity3d/player on Mac and usually at C:Program FilesUnityEditorDataPlaybackEnginesAndroidPlayersrccomunity3dplayer on Windows).

To do this, first locate the classes.jar shipped with Unity Android. It is found in the installation folder (usually C:Program FilesUnityEditorData (on Windows) or /Applications/Unity (on Mac)) in a sub-folder calledPlaybackEngines/AndroidPlayer/bin. Then add classes.jar to the classpath used to compile the new Activity. The resulting .class file(s) should be compressed into a .jar file and placed in the Assets->Plugins->Android folder. Since the manifest dictates which activity to launch it is also necessary to create a new AndroidManifest.xml. The AndroidManifest.xml file should also be placed in the Assets->Plugins->Android folder (placing a custom manifest completely overrides the default Unity Android manifest).

The new activity could look like the following example, OverrideExample.java:

And this is what the corresponding AndroidManifest.xml would look like:

UnityPlayerNativeActivity

It is also possible to create your own subclass of UnityPlayerNativeActivity. This will have much the same effect as subclassing UnityPlayerActivity but with improved input latency. Be aware, though, that NativeActivity was introduced in Gingerbread and does not work with older devices. Since touch/motion events are processed in native code, Java views would normally not see those events. There is, however, a forwarding mechanism in Unity which allows events to be propagated to the DalvikVM. To access this mechanism, you need to modify the manifest file as follows:-

Note the “.OverrideExampleNative” attribute in the activity element and the two additional meta-data elements. The first meta-data is an instruction to use the Unity library libunity.so. The second enables events to be passed on to your custom subclass of UnityPlayerNativeActivity.

ExamplesNative Plugin Sample

A simple example of the use of a native code plugin can be found here

This sample demonstrates how C code can be invoked from a Unity Android application. The package includes a scene which displays the sum of two values as calculated by the native plugin. Please note that you will need the Android NDK to compile the plugin.

Java Plugin Sample

An example of the use of Java code can be found here

This sample demonstrates how Java code can be used to interact with the Android OS and how C&#;&#; creates a bridge between C# and Java. The scene in the package displays a button which when clicked fetches the application cache directory, as defined by the Android OS. Please note that you will need both the JDK and the Android NDK to compile the plugins.

Here is a similar example but based on a prebuilt JNI library to wrap the native code into C#.

From:

【猫猫的Unity Shader之旅】之双面材质和多Pass渲染 默认情况下,我们编写的Shader都只对模型的正面进行渲染,因为大多数模型都是封闭的,我们看不到反面。在实际的开发过程中,也经常会遇到需要正

【边玩边学Unity3d】实现可编辑网格 转载:

Unity3D开发之Unity5版本自写Shader没有雾的效果问题 原本项目是Unity4.6版本的,升级到Unity5之后发现原本的雾不再看见了,然后查了一下相关资料,发现官方是改变了雾的渲染。这里有相关的官方方式:htt

标签: Building Unity3D Plugins for Android

本文链接地址:https://www.jiuchutong.com/biancheng/372800.html 转载请保留说明!

上一篇:添加随机的游戏元素(随机游戏插件怎么使用)

下一篇:【猫猫的Unity Shader之旅】之双面材质和多Pass渲染(猫的猫的视频)

  • 个体户开公账户需要什么资料
  • 短期借款明细账应采用三栏式账页格式
  • 小规模印花税是季报还是月报
  • 外包和离岸外包一样吗
  • 成本收入不配比的风险有哪些
  • 冲减以前年度多计的管理费用分录
  • 个人所得税可以退几年前的?
  • 股权变更印花税申报表怎么填写
  • 职工薪酬会计准则
  • 收到预付款项发票如何入账?
  • 营改增对建筑业的影响
  • 纳税人涉税信息查询
  • 企业如何处理劳方与资方的关系
  • 超市预付卡开票内容
  • 一般纳税人如何纳税申报
  • 快递公司税收优惠
  • 机构股东入股资金流向
  • 公司投资理财产品收益怎么算
  • 17%和6%的票能直接抵扣吗?
  • 怎么更正以前年度企业所得税
  • 行业协会会费收缴标准
  • 运费从货款中扣除后付款分录怎么做
  • 背书转让银行承兑汇票会计分录
  • 应交所得税的计算公式excel
  • 不计入开办费可以吗
  • 其他收入工会经费计税依据
  • 建筑业产值填哪个数据
  • php获取ftp文件目录
  • PHP:imagettftext()的用法_GD库图像处理函数
  • 酒店加盟管理费多少
  • 提存计划怎么算
  • 优化in
  • 金银首饰以旧换新增值税处理
  • sybaris插件包
  • php eval绕过
  • 企业年度汇算清缴申报表填写
  • 企业所得税那些是免税的收入
  • 织梦官方网站
  • 收入和成本的原则是什么
  • 自来水厂的供水井
  • 延期付款利息收入要交增值税吗
  • Win7 32/64位系统下安装SQL2005和SP3补丁安装教程[图文]
  • 可以抵扣的进项发票有哪些
  • 增值税纳税申报实训报告
  • 固定资产清理的借贷方向表示什么
  • 短期借款的核算
  • 车辆保险发票一般在哪开
  • 酒店客房收入如何分配
  • 非居民企业所得税
  • 商品促销赠品如何分类
  • 汽车高速公路收费卡
  • 股东在注册资本金范围内承担责任
  • 暂估入库后发票来不了会计分录
  • 现金流量表和利润表的勾稽关系
  • 购买天然气进项税额
  • 固定资产盘点表excel
  • win7开机提示由于启动计算机时出现页面文件
  • win8系统笔记本怎么恢复出厂设置
  • 微软停止更新win7
  • win10右键菜单自定义
  • Office 2007在Windows Vista中出现的反常字体问题的解决办法
  • linux存在的意义
  • winsvc是什么进程
  • ubuntu虚拟机怎么联网
  • centos权限不够怎么办
  • NDSTray.exe - NDSTray是什么进程 有什么用
  • windows8怎么设置
  • popupwindow底部弹出
  • Quick cocos2dx-Lua(V3.3R1)学习笔记(7) ---计时器,我是个定时吃饭睡觉的好孩子
  • 置顶朋友圈怎么设置
  • 炉石传说用什么开发的
  • perl and
  • 原生js import
  • iframe的替代方案
  • js鼠标滑动特效
  • javascript获取html元素的方法
  • 编写javascript代码
  • python的了解
  • 企业不做审计会有什么后果?
  • 广东省电子税务局登录方式
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设