Create callbacks from native code
Understand how to use native-to-managed callback functionality.
Read time 2 minutesLast updated 14 days ago
Understand how to use native-to-managed callback functionality.
There are two ways to send data from native code to C# scripts. You can either send a message directly to a GameObject, or you can invoke a C# delegate that was previously passed from managed-to-native code.
Use messages
From Objective-C, use the following call to send a message to a C# script:
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");From Swift (Swift Xcode project type), use the following method:
UnityPlayer.shared.sendMessage(toGameObject: "ObjectName", method: "MyMethod", argument: "Message to send")The following is an example of a C# method that receives messages from native code.
using UnityEngine;public class MessageReceiver : MonoBehaviour{ // This method name must match the one used in UnitySendMessage / sendMessage public void MyMethod(string message) { Debug.Log("Received message from native plug-in: " + message); }}
Both functions have the following limitations:
- From native code, you can only call script methods that correspond to the following signature: .
void MethodName(string message); - Calls to are asynchronous and have a delay of one frame.
UnitySendMessage - Two or more GameObjects that have the same name can cause conflicts.
For more information, refer to Send messages to C# scripts.
Use delegates
When you use delegates, the C# method must be static and marked with the attribute.
MonoPInvokeCallbackTo use delegates:
- Pass the method as a delegate into your native method.
extern - In native code, implement a function that accepts a function pointer with the matching signature.
The native function pointer then points back to your static C# method.
The C# code for this method looks like this:
delegate void MyFuncType();[AOT.MonoPInvokeCallback(typeof(MyFuncType))]static void MyFunction() { }[DllImport ("__Internal")]static extern void RegisterCallback(MyFuncType func);
The C code that accepts the callback looks like this:
typedef void (*MyFuncType)();void RegisterCallback(MyFuncType func) {}