referring static variable of existing script gives null

Hello guys, I got 2 scripts lets say MenuController and BodyModController.
I have got tons of other scripts that works fine with same access ways so a bit unsure.


public class MenuController : MonoBehaviour
{
    public static MenuController menuControllerRef;
    Start()
    {
        fun1();
    }
    private fun1()
    {
        BodyModController.bodyRef.menuRef = this;
		BodyModController.bodyRef.MenuEnable();
    }
}


public class BodyModController : MonoBehaviour
{
    public static MenuController menuRef;
    public static BodyModController bodyRef;
    private void Awake()
    {
         bodyRef = this;
    }
    public void MenuEnable()
    {
         //... SomeCode
     }
}

Now ‘BodyModController.bodyRef’ results in Null. I have no idea why.
Also, other scripts access ‘MenuController menuControllerRef’ in Start() or OnEnable() so changing execution order did not help much as my errors count increased to 5.
Any help is greatly appreciated.

P.S. MenuController is attached to GameObject at root(level 1) and active, whereas BodyModController is at 4th child level if seen in the hierarchy and is setActive(false) to all its parents and grandparents.
Not sure what is terminology but I hope the last point was helpful if relevant.

My own observation is that child objects are “Started” or “Awaken” before parents in default layout (without using the editor to control script execution order).

I sense this code isn’t posted from a compiled example (Start without void wouldn’t compile).

private void Awake() is probably fine, but I always see that void Awake() (where private is just assumed) - my thought here is to be sure that Awake is actually executing, try a breakpoint to witness that.

Anyway, the initialization you’re invoking in Awake or Start to initialize the static bodyRef may not fit into the timing design of Awake or Start, and as a concept isn’t a Unity framework notion, but a more general object oriented design notion, independent of Unity.

Try moving that static member initialization to a default constructor for BodyModController, which should fire the moment the object is created, before an Awake could even be called.

Note, too, there is nothing enforcing singleton behavior here - so, some thought to that might be warranted.

Another method you could consider is to make the static bodyRef private, and insist on the use of the static through a public static method that performs lazy initialization. Any caller that witnesses the bodyRef is null would “Find” the object by name, initialize the static bodyRef, then (in all cases) return it. This is a one time self initialization on first use.