Created
April 12, 2020 22:10
-
-
Save mattbajorek/17c1791481ef4585160062c73f7a9c50 to your computer and use it in GitHub Desktop.
Setting up interface methods
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; | |
// Android only variables | |
private const string JAVA_OBJECT_NAME = "com.example.nativecalculations.NativeCalculationsPlugin"; | |
private static AndroidJavaObject androidJavaNativeCalculation; | |
// iOS only variables | |
#if UNITY_IOS | |
[DllImport("__Internal")] | |
#endif | |
private static extern string syncCalculation(int rectangleHeight, int rectangleWidth); | |
#if UNITY_IOS | |
[DllImport("__Internal")] | |
#endif | |
private static extern void asyncCalculation(int rectangleHeight, int rectangleWidth); | |
// Save a reference of the callback to pass async messages | |
private static Action<CalculationResults> handleAsyncCalculation; | |
... | |
/* | |
* ----------------- | |
* Interface Methods | |
* ----------------- | |
*/ | |
public static CalculationResults PerformSyncCalculation(int rectangleHeight, int rectangleWidth) | |
{ | |
string calculationsResultsJson; | |
switch (Application.platform) | |
{ | |
case RuntimePlatform.Android: | |
calculationsResultsJson = androidJavaNativeCalculation.Call<string>("syncCalculation", rectangleHeight, rectangleWidth); | |
return JsonUtility.FromJson<CalculationResults>(calculationsResultsJson); | |
case RuntimePlatform.IPhonePlayer: | |
calculationsResultsJson = syncCalculation(rectangleHeight, rectangleWidth); | |
return JsonUtility.FromJson<CalculationResults>(calculationsResultsJson); | |
default: | |
throw new PlatformNotSupportedException(); | |
} | |
} | |
public static void PerformAsyncCalculation(int rectangleHeight, int rectangleWidth, Action<CalculationResults> handleAsyncCalculation) | |
{ | |
NativeCalculations.handleAsyncCalculation = handleAsyncCalculation; | |
switch (Application.platform) | |
{ | |
case RuntimePlatform.Android: | |
androidJavaNativeCalculation.Call("asyncCalculation", rectangleHeight, rectangleWidth); | |
break; | |
case RuntimePlatform.IPhonePlayer: | |
asyncCalculation(rectangleHeight, rectangleWidth); | |
break; | |
default: | |
throw new PlatformNotSupportedException(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment