A, requirements,

  • Add Unity3D element to iOS App, App realizes functional operation by using KPI provided by Unity

Unity integration into iOS native projects

  1. Unity export project, can be as an independent App online, can also inherit the form of the Framework to the original project (usually the company project needs to recruit a Unity development, of course, to learn, do a simple demo is very simple, online tutorials are also a lot of)
  2. There are many ways to integrate Unity. My project here uses Cocospod, and the current project basically uses POD. I only write associated POD here
  3. The operation is as follows :(NativeiOS is a NativeiOS project, UnityTest_Device is a project exported by Unity, real machine debugging)

  1. Drag the UnityTest_Device project directly to NativeiOS. The project structure directory is as follows:

  1. Open the native project and add Unity to your workspace as follows:
  • Native project structure

  • Add Untity, “+” Files Add in the lower left corner

  • Choose Untiy – iPhone. Xcodeproj

  • The project structure should then look like this:

  • Expand the Unity-iphone project and select the Data folder, as shown in the following figure:

  • Select and compile to get Unity’s frame

  • After compiling successfully, expand the iOS native project and select Target

  • After adding the frameword, inheritance is completed, and the code is implemented

Three, code implementation

    1. The main implement
int main(int argc, char * argv[]) {

    NSString * appDelegateClassName;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@(argc) forKey:@"argc"];
    [userDefaults synchronize];
    
    [userDefaults setObject:[NSString stringWithFormat:@"%p",argv] forKey:@"argv"];
    [userDefaults synchronize];

    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
Copy the code
    1. AppDelegate.h
#import <UIKit/UIKit.h> #include <UnityFramework/UnityFramework.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic, strong) UIWindow *window; @property (nonatomic, strong) UnityFramework *ufw; // Display Unity view - (void)showUnityView; // display native iOS view - (void)showNativeView; @endCopy the code
  1. AppDelegate.m
/// UnityFrameworkLoad UIKIT_STATIC_INLINE UnityFramework* UnityFrameworkLoad() { NSString* bundlePath = nil; bundlePath = [[NSBundle mainBundle] bundlePath]; bundlePath = [bundlePath stringByAppendingString: @"/Frameworks/UnityFramework.framework"]; NSBundle* bundle = [NSBundle bundleWithPath: bundlePath]; if ([bundle isLoaded] == false) [bundle load]; UnityFramework* ufw = [bundle.principalClass getInstance]; if (! [ufw appController]) { // unity is not initialized [ufw setExecuteHeader: &_mh_execute_header]; } return ufw; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // initialize Unity [self initUnity]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:launchOptions forKey:@"launchOptions"]; [userDefaults synchronize]; return YES; } #pragma mark - Unity - (BOOL)unityIsInitialized {return [self ufw] && [[self ufw] appController]; } // initialize Unity - (void)initUnity {// Check whether Unity is initialized if ([self unityIsInitialized]) return; // Initialize Unity self.ufw = UnityFrameworkLoad(); [self.ufw setDataBundleId:"com.unity3d.framework"]; [self.ufw registerFrameworkListener:self]; // [NSClassFromString(@"FrameworkLibAPI") registerAPIforNativeCalls:self]; NSString *argvStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"argv"]; char **argv; sscanf([argvStr cStringUsingEncoding:NSUTF8StringEncoding], "%p",&argv); int argc = [[[NSUserDefaults standardUserDefaults] valueForKey:@"argc"] intValue]; NSDictionary *launchOptions = [[NSUserDefaults standardUserDefaults] valueForKey:@"launchOptions"]; [self.ufw runEmbeddedWithArgc:argc argv:argv appLaunchOpts:launchOptions]; } // display Unity view - (void)showUnityView {if (! [self unityIsInitialized]){NSLog(@"Unity is not initialized "); } [self.ufw showUnityWindow]; } // display iOS native view - (void)showNativeView {[self.window makeKeyAndVisible]; } #pragma mark - UnityFrameworkListener - (void)unityDidUnload:(NSNotification *)notification { NSLog(@"========== %s ============",__func__); [self.window makeKeyAndVisible]; [[self ufw] unregisterFrameworkListener: self]; [self setUfw: nil]; } - (void)unityDidQuit:(NSNotification *)notification { NSLog(@"========== %s ============",__func__); } - (void)applicationWillResignActive:(UIApplication *)application { [[[self ufw] appController] applicationWillResignActive: application]; } - (void)applicationDidEnterBackground:(UIApplication *)application { [[[self ufw] appController] applicationDidEnterBackground: application]; } - (void)applicationWillEnterForeground:(UIApplication *)application { [[[self ufw] appController] applicationWillEnterForeground: application]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [[[self ufw] appController] applicationDidBecomeActive: application]; } - (void)applicationWillTerminate:(UIApplication *)application { [[[self ufw] appController] applicationWillTerminate: application]; }Copy the code
    1. In custom xxxController, create Unity’s view as required
#import "appdelegate. h" 2. // unityContentView @property (nonatomic, weak) UIView *unityContentView; /// AppDelegate @property (nonatomic, strong) AppDelegate *appDelegate; - (void)awakeFromNib { [super awakeFromNib]; AppDelegate *appDelegate = (AppDelegate *)([UIApplication sharedApplication].delegate); self.appDelegate = appDelegate; / / Unity view UIView * view = self in appDelegate. Ufw. AppController. RootViewController. View; view.frame = CGRectMake(0, 0, 300, 500); [self addSubview:view]; } - (IBAction)slowDownClick:(UIButton *)sender {[self.appdelegate.ufw sendMessageToGOWithName:"ybot" functionName:"slowDown" message:""]; } /// acceleration - (IBAction)accelerateClick:(UIButton *) Sender {[self.appdelegate. ufw sendMessageToGOWithName:"ybot" functionName:"speedUp" message:""]; }Copy the code