ArgumentException: Value does not fall within the expected range. in Awake() vs Start()

Hello community, I have a script for in-game panel, it has a homeButton as its child game object and I use SerializeField to access it. The home button calls the disableInGamePanel method in GameManager singleton to disable the current panel and go back to main menu.

Instead of adding the button callback in inspector, I am trying to add the callback function in script. The code snippet is pretty simple:

    [SerializeField] private Button homeButton;
    
    void Awake() {
        homeButton.onClick.AddListener(GameManager.Manager.disableInGamePanel);
    }

However, when I run my game it throws the ArgumentException: Value does not fall within the expected range error, and home button could not attach the callback action as its listener.

But if I swap the Awake() to Start() without changing anything else, it runs as expected. I am just wondering why I can only add the listener in Start() but not in Awake()? I know Awake() is called before any Start() is called, but what’s the exact affect on how I should be adding the button listener?

Thank you in advance for any guidance!

I am assuming that you are initializing GameManager.Manager in GameManager’s Awake method as well. The order in which scripts run their Awake method is seemingly random unless specified in the Script Execution Order panel. So what’s probably happening is that the button’s Awake is running before GameManager’s, when GameManager.Manager has not been initialized yet.

3 Likes

Yes! This is exactly the case, thanks for your insight