Understand how to use native-to-managed callback functionality.
There are two ways to send data from native code to C# scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary. You can either send a message directly to a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary, or you can invoke a C# delegate that was previously passed from managed-to-native code.
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);
}
}
Note: The method must be public and have a single string parameter. The method name must also match the one used in the UnitySendMessage or sendMessage call.
Both functions have the following limitations:
void MethodName(string message);.UnitySendMessage are asynchronous and have a delay of one frame.For more information, refer to Send messages to C# scripts.
When you use delegates, the C# method must be static and marked with the MonoPInvokeCallback attribute.
To use delegates:
extern native method.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:
Note: This example uses C. The C# code that calls RegisterCallback requires the method to be defined in C for symbol matching.
lang-c
typedef void (*MyFuncType)();
void RegisterCallback(MyFuncType func) {}
Note: Ensure string values returned from a native method are UTF–8 encoded and allocated on the heap.