Created
December 23, 2018 22:40
-
-
Save luluco250/b2d7aca31120c8949381e4cc2111a920 to your computer and use it in GitHub Desktop.
Adding persistent events in Unity
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
#if UNITY_EDITOR | |
using UnityEngine; | |
using UnityEngine.UI; | |
using UnityEngine.Events; | |
using UnityEditor; | |
using UnityEditor.Events; | |
public class AddKeyComponents : MonoBehaviour { | |
public GameObject virtualKeyboard; | |
public void OnExecute() { | |
Debug.Log("Adding key components..."); | |
if (virtualKeyboard == null) { | |
Debug.LogError("No VirtualKeyboard game object assigned!"); | |
return; | |
} | |
foreach (Transform child in virtualKeyboard.transform) { | |
var key = child.gameObject; | |
var oldTextKey = key.GetComponent<VirtualKeyboardTextKey>(); | |
if (oldTextKey != null) | |
DestroyImmediate(oldTextKey); | |
var textKey = key.AddComponent<VirtualKeyboardTextKey>(); | |
textKey.lowerText = child.name.ToLower(); | |
textKey.upperText = child.name.ToUpper(); | |
var button = key.GetComponent<Button>() ?? key.AddComponent<Button>(); | |
var action = new UnityAction(textKey.OnClick); | |
// Remove all listeners. | |
button.onClick = new Button.ButtonClickedEvent(); | |
UnityEventTools.AddVoidPersistentListener( | |
button.onClick, | |
action | |
); | |
Debug.Log("Added key component to " + key.name); | |
} | |
Debug.Log("Finished!"); | |
} | |
} | |
[CanEditMultipleObjects] | |
[CustomEditor(typeof(AddKeyComponents))] | |
public class AddKeyComponentsEditor : Editor { | |
public override void OnInspectorGUI() { | |
base.OnInspectorGUI(); | |
if (GUILayout.Button("Execute")) | |
foreach (Object obj in targets) | |
((AddKeyComponents)obj).OnExecute(); | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment