- Home /
Should OnEnabled() be changed to be called after Start()?
So I ran into an issue with two scripts, one A that holds a reference, and one B that calls that reference. The problem is I have to call the reference every time I enable the object B, but A's reference is another object that gets set up during Start(). So B calls the Reference that isn't setup yet making an error, but this is only a problem the very first time it is enabled. and OnEnabled isn't like Start or Awake because it isn't only called once in the lifetime, so an example like the above will happen a lot, as its main purpose isn't to do initial setup, it is to do repeated setup. What are your thoughts, and how can I solve this problem in the future?
I did see an idea on this thread, but it doesn't pertain to if you need to keep using OnEnabled repeatedly, more just if you use it once to initialize.
Answer by ignacevau · Dec 26, 2018 at 09:29 AM
Say you have class A
and class B
, I would just check whether class B
is ready, and if not, use a Coroutine to wait for the Start
method of class B
.
public class ClassA : MonoBehaviour {
private IEnumerator WaitUntilBReady()
{
while (!ClassB.Ready)
{
yield return null;
}
DoSomething();
}
private void OnEnable()
{
if(!ClassB.Ready)
StartCoroutine(WaitUntilBReady());
else
DoSomething();
}
}
public class ClassB : MonoBehaviour {
public static bool Ready;
private void Start()
{
Ready = true;
}
}
Your answer
Follow this Question
Related Questions
Execution Order of Scripts - Awake and OnEnable 1 Answer
OnEnable, Awake, Start order 8 Answers
If a script is attached to more than one gameObject, will Start() & Awake() run more than once? 2 Answers
Does the access modifier of Start(), Awake(), OnEnable() make a difference to Unity? 3 Answers
does finction start or awake run when the object or script is enabled mid game 3 Answers