Created
June 7, 2024 05:29
-
-
Save SolarianZ/661c4fe7e1f1123e8f356eab78f3a8c6 to your computer and use it in GitHub Desktop.
{"category": "Unity Engine/Editor/Extensions", "keywords": "Unity, Editor, Alert, Message, Remove, Component"} Custom editor to show alert message on remove component.
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
using System; | |
using System.Reflection; | |
using UnityEditor; | |
using UnityEngine; | |
// [CustomEditor(typeof(YOUR_COMPONENT))] | |
public class AlertOnRemoveComponentEditor : | |
#if ODIN_INSPECTOR | |
Sirenix.OdinInspector.Editor.OdinEditor | |
#else | |
UnityEditor.Editor | |
#endif | |
{ | |
public static string GetAlertMessageOnRemoveMethodName { get; set; } = "GetAlertMessageOnRemove"; | |
public bool AlertInPlayMode { get; set; } = false; | |
public string AlertMessageOnRemove { get; set; } | |
#if ODIN_INSPECTOR | |
protected override void OnEnable() | |
{ | |
base.OnEnable(); | |
#else | |
protected virtual void OnEnable() | |
{ | |
#endif | |
if (AlertInPlayMode || !Application.isPlaying) | |
{ | |
InitializeAlertMessageOnRemoveFromTarget(); | |
} | |
} | |
#if ODIN_INSPECTOR | |
protected override void OnDisable() | |
{ | |
base.OnDisable(); | |
#else | |
protected virtual void OnDisable() | |
{ | |
#endif | |
if (AlertInPlayMode || !Application.isPlaying) | |
{ | |
AlertComponentRemoved(); | |
} | |
} | |
protected void InitializeAlertMessageOnRemoveFromTarget(string defaultMessage = null) | |
{ | |
Type targetType = target.GetType(); | |
MethodInfo miGetAlert = null; | |
Type hierarchyType = targetType; | |
while (hierarchyType != null && miGetAlert == null) | |
{ | |
miGetAlert = hierarchyType.GetMethod(GetAlertMessageOnRemoveMethodName, | |
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); | |
hierarchyType = hierarchyType.BaseType; | |
} | |
if (miGetAlert != null) | |
{ | |
if (miGetAlert.IsStatic) | |
{ | |
AlertMessageOnRemove = miGetAlert.Invoke(null, null) as string; | |
} | |
else | |
{ | |
AlertMessageOnRemove = miGetAlert.Invoke(target, null) as string; | |
} | |
} | |
if (string.IsNullOrEmpty(AlertMessageOnRemove)) | |
{ | |
AlertMessageOnRemove = !string.IsNullOrEmpty(defaultMessage) | |
? defaultMessage | |
: $"You removed the '{targetType!.Name}' component."; | |
} | |
} | |
protected void AlertComponentRemoved() | |
{ | |
if (!target && EditorUtility.DisplayDialog("Alert", AlertMessageOnRemove, "Revert", "Ignore")) | |
{ | |
Undo.PerformUndo(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment