- Home /
Control which class is instantiated first
In the scenario where I have two classes, AClass
and BClass
, which both have some basic code in the constructor, but AClass relies on BClass being instantiated first , how can I control the order of instantiation?
I guess I'm also looking to know how to control which scripts hit the Unity event functions (Awake(), Start() etc) first.
More details:
I have have two GameObjects in my scene (no parent/child relationship), and they each have their own class attached:
ObjectA has AClass
ObjectB has BClass
Bclass
needs to be instatiated after AClass
, because the code relies on this:
public class AClass : MonoBehaviour
{
public static AClass ObjectReference;
public AClass()
{
if( ObjectReference == null )
ObjectReference = this;
else
{
Destroy( ObjectReference );
ObjectReference = this;
}
}
}
public class BClass : MonoBehaviour
{
bool Pass;
public BClass()
{
if (AClass.ObjectReference != null )
{
Debug.Log( "AClass was instantiated first" );
Pass = true; // we obviously want Pass to be true
}
else
{
Debug.Log( "BClass was instantiated first" );
Pass = false;
}
}
}
You shouldn't be declaring constructors for your $$anonymous$$onoBehaviours at all (if you want to know why, just search this site for "$$anonymous$$onobehaviour constructor" and you'll find plenty of discussion of the matter). Ins$$anonymous$$d, do your set up using the Start and Awake functions that get called automatically. If part of the set-up of one component is dependent on another component being set up first, then put it in a (different) initialisation function so that you are in control of when it happens, and call that function as part of (eg at the end of) the other class's set-up.
Answer by TreyH · Jan 22, 2019 at 08:04 PM
You're thinking of Script Execution Order. You can configure that in your Project Settings:
@oxidedivision Good to see you've got this working but you really must stop writing constructors for your $$anonymous$$onoBehaviours. It'll only cause problems.
Your answer
![](https://koobas.hobune.stream/wayback/20220612190247im_/https://answers.unity.com/themes/thub/images/avi.jpg)