77 lines
2.5 KiB
C#
77 lines
2.5 KiB
C#
using UnityEngine;
|
|
using UnityEditor;
|
|
using System.Reflection;
|
|
using System;
|
|
|
|
[CustomEditor(typeof(MonoBehaviour), true)]
|
|
public class DynamicIDGeneratorEditor : Editor
|
|
{
|
|
public override void OnInspectorGUI()
|
|
{
|
|
base.OnInspectorGUI();
|
|
|
|
MonoBehaviour targetScript = (MonoBehaviour)target;
|
|
|
|
if (HasUniqueIDField(targetScript) && GUILayout.Button("Generate Unique ID"))
|
|
{
|
|
bool confirmed = true;
|
|
|
|
// Check if the uniqueID field is not empty
|
|
if (!string.IsNullOrEmpty(GetUniqueID(targetScript)))
|
|
{
|
|
// Display confirmation dialog before generating a new ID
|
|
confirmed = EditorUtility.DisplayDialog("Confirmation", "Generating a new Unique ID will override the previous one. Are you sure?", "Yes", "No");
|
|
}
|
|
|
|
if (confirmed)
|
|
{
|
|
GenerateUniqueID(targetScript);
|
|
EditorUtility.SetDirty(targetScript);
|
|
}
|
|
}
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
MonoBehaviour targetScript = (MonoBehaviour)target;
|
|
|
|
// Automatically generate a unique ID if the script has a uniqueID field and the uniqueID is empty
|
|
if (HasUniqueIDField(targetScript) && string.IsNullOrEmpty(GetUniqueID(targetScript)))
|
|
{
|
|
GenerateUniqueID(targetScript);
|
|
EditorUtility.SetDirty(targetScript);
|
|
}
|
|
}
|
|
|
|
private bool HasUniqueIDField(MonoBehaviour script)
|
|
{
|
|
// Check if the script has a field named "uniqueID"
|
|
return script.GetType().GetField("uniqueID") != null;
|
|
}
|
|
|
|
private string GetUniqueID(MonoBehaviour script)
|
|
{
|
|
// Get the value of the uniqueID field using reflection
|
|
FieldInfo uniqueIDField = script.GetType().GetField("uniqueID");
|
|
return uniqueIDField != null ? (string)uniqueIDField.GetValue(script) : null;
|
|
}
|
|
|
|
private void GenerateUniqueID(MonoBehaviour script)
|
|
{
|
|
Type scriptType = script.GetType();
|
|
string uniqueID = $"{scriptType.Name}_{Guid.NewGuid().ToString()}";
|
|
|
|
// Set the value of the uniqueID field using reflection
|
|
FieldInfo uniqueIDField = scriptType.GetField("uniqueID");
|
|
if (uniqueIDField != null)
|
|
{
|
|
uniqueIDField.SetValue(script, uniqueID);
|
|
Debug.Log($"Generated Unique ID: {uniqueID}");
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError($"The script {scriptType.Name} does not have a 'uniqueID' field.");
|
|
}
|
|
}
|
|
}
|