Version: Unity 6.6 Beta (6000.6)
Language : English
Call native plug-ins for iOS
Configure a plug-in for iOS with the Inspector window

Create callbacks from native code

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);
    }
}

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:

  • From native code, you can only call script methods that correspond to the following signature: void MethodName(string message);.
  • Calls to UnitySendMessage are asynchronous and have a delay of one frame.
  • 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 MonoPInvokeCallback attribute.

To use delegates:

  1. Pass the method as a delegate into your extern native method.
  2. 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:

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.

Additional resources

Call native plug-ins for iOS
Configure a plug-in for iOS with the Inspector window