Last active
April 12, 2020 22:18
-
-
Save mattbajorek/eedcfdc7aca09925c2d18541a81fd974 to your computer and use it in GitHub Desktop.
Setting up game object in constructor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using UnityEngine; | |
namespace Plugins.NativeCalculations | |
{ | |
... | |
public static class NativeCalculations | |
{ | |
// Game object is created to receive async messages | |
private const string GAME_OBJECT_NAME = "PluginBridge"; | |
private static GameObject gameObject; | |
... | |
static NativeCalculations() | |
{ | |
// Create Game Object to allow sending messages from Java or Objective C to Unity | |
gameObject = new GameObject(); | |
// Object name must match UnitySendMessage call in Java or Objective C | |
gameObject.name = GAME_OBJECT_NAME; | |
// Attach this class to allow for handling of callbacks from Java or Objective C | |
gameObject.AddComponent<NativeCalculationsCallbackHandler>(); | |
// Do not destroy when loading a new scene | |
UnityEngine.Object.DontDestroyOnLoad(gameObject); | |
// Initialize Plugin | |
switch (Application.platform) | |
{ | |
case RuntimePlatform.Android: | |
var androidJavaUnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); | |
// Current activity does not change for Unity | |
var currentActivity = androidJavaUnityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); | |
// Initialize native Java object | |
androidJavaNativeCalculation = new AndroidJavaObject(JAVA_OBJECT_NAME, currentActivity); | |
break; | |
case RuntimePlatform.IPhonePlayer: | |
// No initialization needed | |
break; | |
default: | |
throw new PlatformNotSupportedException(); | |
} | |
} | |
... | |
/* | |
* ----------------------------- | |
* Native Async Callback Handler | |
* ----------------------------- | |
*/ | |
private class NativeCalculationsCallbackHandler : MonoBehaviour | |
{ | |
private void HandleException(string exception) | |
{ | |
throw new Exception(exception); | |
} | |
private void HandleAsyncCalculation(string calculationResultsJSON) | |
{ | |
var calculationResults = JsonUtility.FromJson<CalculationResults>(calculationResultsJSON); | |
handleAsyncCalculation?.Invoke(calculationResults); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment