基本的なところはここを見ながら進める。
https://qiita.com/tkyaji/items/7dbd56b41b6ac3e72635
SwiftでUnityクラスを作る。上の記事ならこんなかんじ。
class Unity: NSObject, UnityFrameworkListener, NativeCallsProtocol {
static let shared = Unity()
private let unityFramework: UnityFramework
override init() {
let bundlePath = Bundle.main.bundlePath
let frameworkPath = bundlePath + "/Frameworks/UnityFramework.framework"
let bundle = Bundle(path: frameworkPath)!
if !bundle.isLoaded {
bundle.load()
}
let frameworkClass = bundle.principalClass as! UnityFramework.Type
let framework = frameworkClass.getInstance()!
if framework.appController() == nil {
var header = _mh_execute_header
framework.setExecuteHeader(&header)
}
unityFramework = framework
super.init()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
unityFramework.register(self)
FrameworkLibAPI.registerAPIforNativeCalls(self)
unityFramework.setDataBundleId("com.unity3d.framework")
unityFramework.runEmbedded(withArgc: CommandLine.argc, argv: CommandLine.unsafeArgv, appLaunchOpts: launchOptions)
}
var view: UIView {
unityFramework.appController()!.rootView!
}
func showHostMainWindow(_ color: String!) {
}
}
ViewControllerを作る。
class LaunchViewController: UIViewController {}
class ViewController: UIViewController {
private let unityView = Unity.shared.view
override func loadView() {
super.loadView()
view.addSubview(unityView)
NSLayoutConstraint.activate([
unityView.topAnchor.constraint(equalTo: view.topAnchor),
unityView.leftAnchor.constraint(equalTo: view.leftAnchor),
unityView.rightAnchor.constraint(equalTo: view.rightAnchor),
unityView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
}
後述するが、LaunchViewController
なるものを作っておく。
AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
lazy var window: UIWindow? = .init(frame: UIScreen.main.bounds)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window?.rootViewController = LaunchViewController()
window?.makeKeyAndVisible()
Unity.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
window?.rootViewController = ViewController()
return true
}
}
起動時にUnityクラスを初期化しておく。
runEmbedded
はwindowが無いと上手く動かないので、先ほど作ったLaunchViewController
でwindowを作り、そのあとでメインのViewControllerに差し替える。
起動直後にUnityを出さないのであれば、適当にwindowが出来てから呼べばOK