-
Notifications
You must be signed in to change notification settings - Fork 544
/
Copy pathUnityPlayerUtils.swift
executable file
·281 lines (228 loc) · 9.13 KB
/
UnityPlayerUtils.swift
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
//
// UnityPlayerUtils.swift
// flutter_unity_widget
//
// Created by Rex Raphael on 30/01/2021.
//
import Foundation
import UnityFramework
private var unity_warmed_up = false
// Hack to work around iOS SDK 4.3 linker problem
// we need at least one __TEXT, __const section entry in main application .o files
// to get this section emitted at right time and so avoid LC_ENCRYPTION_INFO size miscalculation
private let constsection = 0
// keep arg for unity init from non main
var gArgc: Int32 = 0
var gArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>? = nil
var appLaunchOpts: [UIApplication.LaunchOptionsKey: Any]? = [:]
/***********************************PLUGIN_ENTRY STARTS**************************************/
public func InitUnityIntegration(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?) {
gArgc = argc
gArgv = argv
}
public func InitUnityIntegrationWithOptions(
argc: Int32,
argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?,
_ launchingOptions: [UIApplication.LaunchOptionsKey: Any]?) {
gArgc = argc
gArgv = argv
appLaunchOpts = launchingOptions
}
/***********************************PLUGIN_ENTRY END**************************************/
// Load unity framework for fisrt run
func UnityFrameworkLoad() -> UnityFramework? {
var bundlePath: String? = nil
bundlePath = Bundle.main.bundlePath
bundlePath = (bundlePath ?? "") + "/Frameworks/UnityFramework.framework"
let bundle = Bundle(path: bundlePath ?? "")
if bundle?.isLoaded == false {
bundle?.load()
}
return bundle?.principalClass?.getInstance()
}
/*********************************** GLOBAL FUNCS & VARS START**************************************/
public var globalControllers: Array<FLTUnityWidgetController> = [FLTUnityWidgetController]()
private var unityPlayerUtils: UnityPlayerUtils? = nil
func GetUnityPlayerUtils() -> UnityPlayerUtils {
if unityPlayerUtils == nil {
unityPlayerUtils = UnityPlayerUtils()
}
return unityPlayerUtils ?? UnityPlayerUtils()
}
/*********************************** GLOBAL FUNCS & VARS END****************************************/
var controller: UnityAppController?
var sharedApplication: UIApplication?
@objc protocol UnityEventListener: AnyObject {
func onReceiveMessage(_ message: UnsafePointer<Int8>?)
}
@objc public class UnityPlayerUtils: UIResponder, UIApplicationDelegate, UnityFrameworkListener {
var ufw: UnityFramework!
private var _isUnityPaused = false
private var _isUnityReady = false
private var _isUnityLoaded = false
func initUnity() {
if (self.unityIsInitiallized()) {
self.ufw?.showUnityWindow()
return
}
self.ufw = UnityFrameworkLoad()
self.ufw?.setDataBundleId("com.unity3d.framework")
registerUnityListener()
self.ufw?.runEmbedded(withArgc: gArgc, argv: gArgv, appLaunchOpts: appLaunchOpts)
if self.ufw?.appController() != nil {
controller = self.ufw?.appController()
controller?.unityMessageHandler = self.unityMessageHandlers
controller?.unitySceneLoadedHandler = self.unitySceneLoadedHandlers
self.ufw?.appController()?.window?.windowLevel = UIWindow.Level(UIWindow.Level.normal.rawValue - 1)
}
_isUnityLoaded = true
}
// check if unity is initiallized
func unityIsInitiallized() -> Bool {
if self.ufw != nil {
return true
}
return false
}
// Create new unity player
func createPlayer(completed: @escaping (_ view: UIView?) -> Void) {
if self.unityIsInitiallized() && self._isUnityReady {
completed(controller?.rootView)
return
}
NotificationCenter.default.addObserver(forName: NSNotification.Name("UnityReady"), object: nil, queue: OperationQueue.main, using: { note in
self._isUnityReady = true
completed(controller?.rootView)
})
DispatchQueue.main.async {
// if (sharedApplication == nil) {
// sharedApplication = UIApplication.shared
// }
// Always keep Flutter window on top
// let flutterUIWindow = sharedApplication?.keyWindow
// flutterUIWindow?.windowLevel = UIWindow.Level(UIWindow.Level.normal.rawValue + 1) // Always keep Flutter window in top
// sharedApplication?.keyWindow?.windowLevel = UIWindow.Level(UIWindow.Level.normal.rawValue + 1)
self.initUnity()
unity_warmed_up = true
self._isUnityReady = true
self._isUnityLoaded = true
self.listenAppState()
completed(controller?.rootView)
}
}
func registerUnityListener() {
if self.unityIsInitiallized() {
self.ufw?.register(self)
}
}
func unregisterUnityListener() {
if self.unityIsInitiallized() {
self.ufw?.unregisterFrameworkListener(self)
}
}
@objc
public func unityDidUnload(_ notification: Notification!) {
unregisterUnityListener()
self.ufw = nil
self._isUnityReady = false
self._isUnityLoaded = false
}
@objc func handleAppStateDidChange(notification: Notification?) {
if !self._isUnityReady {
return
}
let unityAppController = self.ufw?.appController() as? UnityAppController
let application = UIApplication.shared
if notification?.name == UIApplication.willResignActiveNotification {
unityAppController?.applicationWillResignActive(application)
} else if notification?.name == UIApplication.didEnterBackgroundNotification {
unityAppController?.applicationDidEnterBackground(application)
} else if notification?.name == UIApplication.willEnterForegroundNotification {
unityAppController?.applicationWillEnterForeground(application)
} else if notification?.name == UIApplication.didBecomeActiveNotification {
unityAppController?.applicationDidBecomeActive(application)
} else if notification?.name == UIApplication.willTerminateNotification {
unityAppController?.applicationWillTerminate(application)
} else if notification?.name == UIApplication.didReceiveMemoryWarningNotification {
unityAppController?.applicationDidReceiveMemoryWarning(application)
}
}
// Listener for app lifecycle eventa
func listenAppState() {
for name in [
UIApplication.didBecomeActiveNotification,
UIApplication.didEnterBackgroundNotification,
UIApplication.willTerminateNotification,
UIApplication.willResignActiveNotification,
UIApplication.willEnterForegroundNotification,
UIApplication.didReceiveMemoryWarningNotification
] {
NotificationCenter.default.addObserver(
self,
selector: #selector(self.handleAppStateDidChange),
name: name,
object: nil)
}
}
// Pause unity player
func pause() {
self.ufw?.pause(true)
self._isUnityPaused = true
}
// Resume unity player
func resume() {
self.ufw?.pause(false)
self._isUnityPaused = false
}
// Unoad unity player
func unload() {
self.ufw?.unloadApplication()
}
func isUnityLoaded() -> Bool {
return _isUnityLoaded
}
func isUnityPaused() -> Bool {
return _isUnityPaused
}
// Quit unity player application
func quit() {
self.ufw?.quitApplication(0)
self._isUnityLoaded = false
}
// Post message to unity
func postMessageToUnity(gameObject: String?, unityMethodName: String?, unityMessage: String?) {
if self.unityIsInitiallized() {
self.ufw?.sendMessageToGO(withName: gameObject, functionName: unityMethodName, message: unityMessage)
}
}
/// Handle incoming unity messages looping through all controllers and passing payload to
/// the controller handler methods
@objc
func unityMessageHandlers(_ message: UnsafePointer<Int8>?) {
for c in globalControllers {
if let strMsg = message {
c.handleMessage(message: String(utf8String: strMsg) ?? "")
} else {
c.handleMessage(message: "")
}
}
}
func unitySceneLoadedHandlers(name: UnsafePointer<Int8>?, buildIndex: UnsafePointer<Int32>?, isLoaded: UnsafePointer<Bool>?, isValid: UnsafePointer<Bool>?) {
if let sceneName = name,
let bIndex = buildIndex,
let loaded = isLoaded,
let valid = isValid {
let loadedVal = Bool((Int(bitPattern: loaded) != 0))
let validVal = Bool((Int(bitPattern: valid) != 0))
let addObject: Dictionary<String, Any> = [
"name": String(utf8String: sceneName) ?? "",
"buildIndex": Int(bitPattern: bIndex),
"isLoaded": loadedVal,
"isValid": validVal,
]
for c in globalControllers {
c.handleSceneChangeEvent(info: addObject)
}
}
}
}