developer tip

iOS 용 Unity3d 플러그인 빌드 방법

copycodes 2020. 11. 28. 09:40
반응형

iOS 용 Unity3d 플러그인 빌드 방법


iOS 용으로 제작 된 아주 작은 Objective-C 라이브러리가 있는데이를 Unity로 내보내고 싶습니다. 모든 호출을 네이티브 라이브러리에 마샬링하는 csharp 래퍼를 작성하는 기본 프로세스를 이해하지만 어디서부터 시작해야할지 전혀 모릅니다. 누구든지 내 라이브러리와 통합 패키지를 만드는 방법을 단계별로 설명하여 다른 개발자에게 배포 할 수도 있습니다.

Unity3d 문서는 매우 간단하며 설명이 없습니다.

감사.


좋아, Mac에서 Unity3d로 며칠을 플레이 한 후 마침내 알아 냈습니다. 이 가이드의 모든 코드는 더미입니다. 이 글을 15 분 정도만에 썼으니 실수 나 오타에 신경 쓰지 마세요.

1) Unity를 열고 새 프로젝트 (파일-> 새 프로젝트)를 생성하고 어딘가에 저장합니다.

2) 프로젝트가 생성되면 다음과 같은 구조를 갖습니다.

  • ProjectName/Assets (그게 필요한 것입니다)
  • ProjectName/Library (무엇이 있는지 신경 쓰지 마세요)
  • ProjectName/ProjectSettings (당신은 그것에 대해 신경 쓰지 않습니다)
  • ProjectName/ProjectName.sln (MonoDevelop 프로젝트)

3) 이동 ProjectName/Assets하여 다음 폴더를 만듭니다. Plugins/iOS, 그러면 결국 다음과 같은 폴더 구조를 갖게됩니다.ProjectName/Assets/Plugins/iOS

4) 컴파일 된 라이브러리 (.a) 파일과 필요한 헤더를 내부에 ProjectName/Assets/Plugins/iOS넣거나 라이브러리의 소스 코드 (.mm, .h, .m 등)를 복사합니다. 일반적으로 C #에서만 C- 함수에 액세스 할 수 있으므로 Objective-C 항목을 어떻게 든 C- 코드로 래핑해야합니다. 제 경우에는 모든 Objective-C 개체가 Singleton 형식으로 구현되었으므로 그렇지 않았습니다. 예를 들어 C 스타일 래퍼를 만들기가 어렵습니다.

CWrapper.h :

extern "C" void MySDKFooBarCFunction();

CWrapper.mm

#import "CWrapper.h"
#import "MyObjectiveCLibrary.h" // your actual iOS library header

void MySDKFooBarCFunction() {
    [MyObjectiveCLibrary doSomeStuff];
}

5) 그런 다음 ProjectName/AssetsCSharp 래퍼 클래스에 대한 폴더를 만들고 원하는대로 이름을 지정합니다. 예 :ProjectName/Assets/MySDK

6) MySDK 폴더 안에 MySDK.cs 파일을 생성하면 C # 래퍼의 더미 예제는 다음과 같습니다.

using UnityEngine;
using System;
using System.Runtime.InteropServices;

public class MySDK
{
    // import a single C-function from our plugin
    [DllImport ("__Internal")]
    private static extern void MySDKFooBarCFunction();

    // wrap imported C-function to C# method
    public static void FooBarCFunction() {
        // it won't work in Editor, so don't run it there
        if(Application.platform != RuntimePlatform.OSXEditor) {
            MySDKFooBarCFunction();
        }
    }
}

7)이 물건을 .unitypackage압축 할 셸 스크립트를 만들어 프로젝트 폴더 (내부 아님) 옆에 넣습니다. 필요에 따라 스크립트에서 EXPORT_PATHPROJECT_PATH변수를 조정 하십시오.

#!/bin/sh

WORKDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
UNITY_BIN="/Applications/Unity/Unity.app/Contents/MacOS/Unity"
EXPORT_PATH="${WORKDIR}/ProjectName.unitypackage"
PROJECT_PATH="${WORKDIR}/ProjectName"
ASSETS_PATH="Assets"

$UNITY_BIN -batchmode -quit \
-logFile export.log \
-projectPath $PROJECT_PATH \
-exportPackage $ASSETS_PATH $EXPORT_PATH

8) 생성 된 bash 스크립트를 실행하여 패키지 빌드를 가져옵니다. 에셋의 모든 항목은 Unity 에디터에서 파일-> 빌드 설정을 통해 생성 할 때 Unity 프로젝트 용 XCode 프로젝트에 포함됩니다. 생성 된 패키지를 사용하여 다른 개발자에게 코드를 배포 할 수 있으므로 패키지 파일을 두 번 클릭하여 Unity 프로젝트에 라이브러리를 포함 할 수 있습니다.

이 스크립트를 실행할 때 Unity 에디터를 종료하는 것을 잊지 마십시오. 그렇지 않으면 패키지 빌드에 실패 할 수 있습니다.

If you have some issues and package does not show up, this script always prints log to export.log

Next steps make sense only if you want to make a Demo unity project for your library (good for testing at least)

9) You can put created Unity project (ProjectName.unity) to Assets/MySDKDemo so you have a demo inside of your package.

10) Create a simple script for your Demo Unity3d scene at Assets/MySDKDemo/MySDKDemo.cs, for example:

using UnityEngine;
using System;
using System.Collections;

public class MySDKDemo : MonoBehaviour
{   
    private GUIStyle labelStyle = new GUIStyle();
    private float centerX = Screen.width / 2;

    // Use this for initialization
    void Start ()
    {   
        labelStyle.fontSize = 24;
        labelStyle.normal.textColor = Color.black;
        labelStyle.alignment = TextAnchor.MiddleCenter;
    }

    void OnGUI ()
    {
        GUI.Label(new Rect(centerX - 200, 20, 400, 35), "MySDK Demo", labelStyle);
        if (GUI.Button(new Rect(centerX - 75, 80, 150, 35), "DoStuff"))
        {
            MySDK.FooBarCFunction();
        }
    }

}

11) Go to Unity Editor. Find the "Main Camera" in left sidebar in Unity Editor, select it and in the bottom of Inspector panel (right sidebar) click on AddComponent, select Scripts -> MySDKDemo script

12) Build the XCode project and run on device.

Few notes

1) Plugins don't work in Unity Editor, simply because they're not compiled in the real-time, well, not sure but probably until you use C# in your plugins, probably C# stuff gets linked immidiately and works in Editor environment.

2) This post does not cover marshaling, or data/memory management between native <-> managed code, as it is very well documented.

Interop with Native Libraries @ Mono project

3) Callbacks from C# to C can be passed using C# delegates, on C-side you use standard functions declarations, on C# side you declare delegates with the same signature. It seems that booleans, integers and strings (C: char*) are marshalled flawlessly (I don't talk about memory management policy and who's responsible to release memory or return value policies).

However it will not work on iOS builds out-of-box due to platform limitations, but C#-to-C callbacks still can be implemented using MonoPInvokeCallbackAttribute, useful links on this topic:

Actually in Unity 4 there's AOT.MonoPInvokeCallbackAttribute already implemented, it's limited to static delegates that can be passed to unmanaged code, but still better than nothing.

4) There's a way to get Unity RootViewController using UnityGetGLViewController function. Just declare this function in your implementation file, i.e.:

extern UIViewController *UnityGetGLViewController();

And use UnityGetGLViewController() whenever you need to get an access to RootViewController.

5) There's much more magic and ugly stuff in details, keep your C interfaces as simple as possible otherwise marshalling can become your nightmare and also keep in mind that managed-to-unmanaged is generally expensive.

6) You definitely use some frameworks in your native code and you don't want linker problems. For example, if you use Keychain in your library then you need to include Security.framework into Xcode project.

I suggest to give a try to XUPorter, it helps Unity to integrate any additional dependencies into Xcode project.

Good luck!


I have written a post on how to create iOS plugin for unity. You can check it here. Hope it helps. Thanks.

참고URL : https://stackoverflow.com/questions/14834626/how-to-build-unity3d-plugin-for-ios

반응형