Unity call c# code from c/objective-c part
- Method 1: use
UnitySendMessage("[gameobject_name]", "[method_name]", "[string_param]");
The above code equal the following code:
GameObject.Find("[gameobject_name]").SendMessage("[method_name]", "[string_param]");
1
To receive message, this gameObject must have a Monobehavior script that must implement a method like this:
public void method_name(string str) {
// some logici here
}
1
2
3
2
3
If several scripts implement such method, all of them will be called.
- Method 2: use delegate to register a callback function in C# side, this need to write some code both for c# and c/objective-c sides.
Here is the work for C# side:
private delegate void OnViewClosed(int result, string msg);
[MonoPInvokeCallback(OnViewClosed)]
static void CalledByNativeC(int result, string msg)
{
// some logic here
}
// ...
#if UNITY_IOS
[DllImport("__Internal")]
private static extern void SetOnViewClosed(OnViewClosed);
#endif
// register the callback function
SetOnViewClosed(CalledByNativeC);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
The following is the code for c/objective-c side:
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
// define as a function pointer type
typedef void (*OnViewClosed)(int result, const char* msg);
// keep the function pointer
static OnViewClosed s_calledFromCSharp = NULL;
// called from c# code
void SetOnViewClosed(OnViewClosed viewClosed)
{
s_calledFromCSharp = viewClosed;
}
// ......
// some where in C/Objecive-C, trigger the callback function
if (s_calledFromCSharp != NULL)
s_calledFromCSharp(result, msg);
//......
#ifdef __cplusplus
}
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
评论
发表评论