Unity3D Native Plugin
The native plugin should provide a simple C interface which the C# script then exposes to other user scripts.
iOS
Call iOS code from Unity
// .cs
using System.Runtime.InteropServices;
[DllImport ("__Internal")]
private static extern void _Foo();
public static void Foo()
{
if (Application.platform != RuntimePlatform.OSXEditor) {
_Foo();
}
}
// .mm / .cpp
extern "C"
{
void _Foo()
{
return;
}
}
- [Tag]
- The iOS framework must be put in the Xcode generated project, not in Unity.
And the framework’s functions must be wrapped in anextern "C"
block.
Then you will be able to use it in C# withDllImport
.
- All files with extensions
.a, .m, .mm, .cpp
under in theAssets/Plugins/iOS
folder will be merged into the generated Xcode project automatically. However, merging is done by symlinking files fromAssets/Plugins/iOS
to the final destination, which might affect some workflows. The.h
files are not included in the Xcode project tree, but they appears on the destination file system, thus alllow compilation of.m/.mm/.c/.cpp
files.
(Peng) After build to iOS project, the iOS source code would be under Unity-iPhone/Libraries/Plugins/iOS/.cpp (/Peng)
- Sub folder are currently not supported.
Call Unity code from iOS
// .cpp
UnitySendMessage("GameObjectName", "MethodName", "Message2Send");
(Peng)
“GameObjectName” shows in Project Hierarchy View is the name of game object appears on scene.
“MethodName” is a public function name of the “GameObjectName”.
“Message2Send” is the “MethodName“‘s parameter.
(/Peng)
- [Tag]
- Managed-to-unmanaged calls are quite processer intensive on iOS. Try to avoid call multiple native methods per frame.
- Xcode’s “Classes” folder is a good place to store your native code because it is not overwritten when project updated. (Peng) Check any source file has configured “Target Membership”. (/Peng)
- (Peng) It seems
UnitySendMessage
only check the first “GameObjectName” from render tree (?) and its first “MethodName”. (/Peng)