-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #77 from asadm/improved-callback-handler
Centralized Callback Manager
- Loading branch information
Showing
4 changed files
with
125 additions
and
42 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Runtime.InteropServices; | ||
using UnityEngine; | ||
|
||
namespace Playroom | ||
{ | ||
public static class CallbackManager | ||
{ | ||
private static Dictionary<string, Delegate> callbacks = new(); | ||
|
||
public static string RegisterCallback(Delegate callback, string key = null) | ||
{ | ||
if (string.IsNullOrEmpty(key)) | ||
key = GenerateKey(); | ||
|
||
|
||
if (!callbacks.ContainsKey(key)) | ||
{ | ||
callbacks.Add(key, callback); | ||
} | ||
else | ||
{ | ||
callbacks[key] = callback; | ||
} | ||
|
||
return key; | ||
} | ||
|
||
|
||
public static void InvokeCallback(string key, string arg1 = null) | ||
{ | ||
if (callbacks.TryGetValue(key, out Delegate callback)) | ||
{ | ||
if (callback is Action action) action?.Invoke(); | ||
else if (callback is Action<string> stringAction) stringAction?.Invoke(arg1); | ||
else Debug.LogError($"Callback with key {key} is of unsupported type!"); | ||
} | ||
else | ||
{ | ||
Debug.LogError($"Callback with key {key} not found!"); | ||
} | ||
} | ||
|
||
private static string GenerateKey() | ||
{ | ||
return Guid.NewGuid().ToString(); | ||
} | ||
|
||
|
||
|
||
/// <summary> | ||
/// Calls an external method to convert a string associated with a given key, called from the JS side only. | ||
/// </summary> | ||
/// <param name="key">The key associated with the string to be converted.</param> | ||
[DllImport("__Internal")] | ||
private static extern void ConvertString(string key); | ||
|
||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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