- Home /
ExecuteInEditMode Component construct "twice" and "reset" custom classes
Hello community. I have an independant class, and I want, from Editor, create a component with a member in this type. It works well, but when I click on "Play Button", custom classes AND private members are reset, like the RAM were flushed by garbage collector of something. I manage to reproduce this behaviour in an EMPTY project, just add this two script files:
In a MyClass.cs :
#if UNITY_3_3
using UnityEngine;
using UnityEditor;
#endif
public class MyClass
{
public string Name;
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3
[MenuItem("Custom/InitComponent")]
static public void MInitComponent()
{
GameObject MyCubeGO = GameObject.CreatePrimitive(PrimitiveType.Cube);
MyComponent myComp = MyCubeGO.AddComponent<MyComponent>() as MyComponent;
myComp.MyPublicBool= true;
myComp.MyClassInstance.Name = "John Doe";
}
#endif
}
And in a MyComponent.cs :
using System;
using System.Collections;
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3
using UnityEngine;
[ExecuteInEditMode()]
public class MyComponent : MonoBehaviour
{
private bool MyPrivateBool;
public bool MyPublicBool;
public MyClass MyClassInstance;
public bool AlreadyConstructed=false;
// Use this for initialization
void Awake()
{
if (!AlreadyConstructed)
{
Debug.Log("Awaking...");
MyClassInstance = new MyClass();
MyPrivateBool = true;
MyPublicBool = true;
AlreadyConstructed = true;
}
}
// Update is called once per frame
void Start()
{
Debug.Log("Starting...");
Debug.Log("MyPublicBool is at value =" + MyPublicBool);
Debug.Log("MyPrivateBool is at value =" + MyPrivateBool);// <==== OK(true) In Editor, RESET (at false) when cliking on PLAY !
Debug.Log("My Name is ="+MyClassInstance.Name); // <==== OK In Editor, CRASH when cliking on PLAY !
MyPrivateBool = false; //Checking the reset here too.
}
}
#endif
As a result , I have for output :
Awaking... Starting... MyPublicBool is at value =True MyPrivateBool is at value =True My Name is =John Doe
//here I click on PLAY Starting... MyPublicBool is at value =True MyPrivateBool is at value =False //WHICH IS WRONG NullReferenceException: Object reference not set to an instance of an object at MyComponent.Start () [0x0003e] in C:\UNITY\Debug01\Assets\MyComponent.cs:37
(Filename: Assets/MyComponent.cs Line: 37) // it this line: Debug.Log("My Name is ="+MyClassInstance.Name);
How can I avoid this kind of behaviour, to keep my initialisation also when I click on "PLAY" ? Thank you for your help!
Your answer
Follow this Question
Related Questions
Is there a 'Play On Awake' function for animations? 1 Answer
Cached references set in awake aren't persisting 0 Answers
Invoke not working from Start() ? 1 Answer
Debug.Log print order, or Awake vs Start issue? 1 Answer
when loading a scene, the execution order is load->constructor->finishfunction->awake->start? 1 Answer