I’m working on a Guid system that works in editor and play mode I want to create a new Guid each time a specific game object is added to the scene no matter if is in play oder editor mode. I’m using [ExecuteAlways] also tried [ExecuteInEditMode]
The problem I have is when duplicating parented prefabs. When doing so the initialization of the MonoBehaviour is Awake, OnEnable, OnDisable, OnEnable, Start. This only happens for Prefabs with a parent. With the second OnEnable the override I just did in Awake disappears.
Screenshot:
Code:
using System;
using UnityEngine;
[ExecuteAlways]
public class PrefabExecuteAlways : MonoBehaviour
{
[SerializeField]
private string guid = string.Empty;
public Guid Guid
{
get
{
Guid realGuid;
if (!Guid.TryParse(guid, out realGuid))
{
realGuid = Guid.NewGuid();
guid = realGuid.ToString();
}
return realGuid;
}
set
{
guid = value.ToString();
}
}
protected void Awake()
{
var newGuid = Guid.NewGuid();
Debug.Log($"ExecuteAlways Awake {this.name}, instanceID {gameObject.GetInstanceID()}, oldGuid {newGuid}, newGuid {guid}");
Guid = newGuid;
}
protected void Start()
{
Debug.Log($"ExecuteAlways Start {this.name}, instanceID {gameObject.GetInstanceID()}, newGuid {guid} ");
}
protected void OnEnable()
{
Debug.Log($"ExecuteAlways OnEnable {this.name}, instanceID {gameObject.GetInstanceID()}, newGuid {guid} ");
}
protected void OnDisable()
{
Debug.Log($"ExecuteAlways OnDisable {this.name}, instanceID {gameObject.GetInstanceID()}, newGuid {guid} ");
}
protected void OnDestroy()
{
Debug.Log($"ExecuteAlways OnDestroy {this.name}, instanceID {gameObject.GetInstanceID()}, newGuid {guid} ");
}
}
Notes:
- I might be able to use Start instead of Awake. This is still a very weird thing to happen.
- This is a striped down piece of code for reproduction
- I’m on Unity 2022.03.10f1