This repository is an iOS project that includes iOS and Unity communication.
Explore the project »
Report Bug
Communicate with a Unity game embedded in a SwiftUI iOS App »
- Unity
- UnityFramework
- NativeCallProxy
- Create an Unity project.
- Export the Unity project.
- Drag and drop the Unity-iPhone.xcodeproj file to the iOS workspace.
- Add a new framework to the iOS workspace:
General >
Frameworks, Libraries and Embedded Content >
Click the + button >
Select the UnityFramework.framework from the list.
NOTE |
You must connect and run on a real device to successful build. |
- Create a struct called UnityMessage.
struct UnityMessage {
let objectName: String?
let methodName: String?
let messageBody: String?
}
- Create a cache array for cases where Unity is not initialized.
var cachedMessages = [UnityMessage]()
- Create a sendMessage function to sending message to Unity.
- Object Name: Name of Unity object.
- Method Name: Name of Unity method.
- Message: Message to Unity.
func sendMessage(_ objectName: String, methodName: String, message: String) {
let msg: UnityMessage = UnityMessage(
objectName: objectName,
methodName: methodName,
messageBody: message)
// Send the message right away if Unity is initialized, else cache it
if isInitialized {
unityFramework?.sendMessageToGO(
withName: msg.objectName,
functionName: msg.methodName,
message: msg.messageBody)
} else {
cachedMessages.append(msg)
}
}
- Send message to Unity.
UnityManager.shared.sendMessage(
"Ball",
methodName: "SetBallColor",
message: "red")
- Create a NativeCallProxy.h file.
#import <Foundation/Foundation.h>
@protocol NativeCallsProtocol
@required
- (void) sendMessageToMobileApp:(NSString*)message;
// other methods
@end
__attribute__ ((visibility("default")))
@interface FrameworkLibAPI : NSObject
+(void) registerAPIforNativeCalls:(id<NativeCallsProtocol>) aApi;
@end
- Create a NativeCallProxy.mm file.
#import <Foundation/Foundation.h>
#import "NativeCallProxy.h"
@implementation FrameworkLibAPI
id<NativeCallsProtocol> api = NULL;
+(void) registerAPIforNativeCalls:(id<NativeCallsProtocol>) aApi
{
api = aApi;
}
@end
extern "C"
{
void sendMessageToMobileApp(const char* message)
{
return [api sendMessageToMobileApp:[NSString stringWithUTF8String:message]];
}
}
- Add NativeCallProxy.h and NativeCallProxy.mm files to the Unity.
- Create a bridging header file in the iOS project.
#import <UnityFramework/NativeCallProxy.h>
- Send message to the iOS project using NativeAPI in the Unity project.
public class NativeAPI {
[DllImport("__Internal")]
public static extern void sendMessageToMobileApp(string message);
}
public void ButtonPressed()
{
pressCount++;
NativeAPI.sendMessageToMobileApp("The button has been tapped " + pressCount.ToString() + " times!");
}
- Implement the NativeCallsProtocol in the iOS project. And get message from Unity using sendMessage() function.
extension ViewController: NativeCallsProtocol {
func sendMessage(toMobileApp message: String) {
print(message)
}
}