Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding Unity's Mono Behaviour's start() execution

I am absolutely confused and therefore simply hope that I am able to describe my issue sufficiently.

I have a class Test inheriting from MonoBehaviour. It takes a UnityEngine.UI.Button array buttons as a constructor parameter.

Later the first element of this button array is read. However, this resulted in an out of bounds exception. So, I tried to debug the problem by adding helpful logs. That resulted in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Hacking : MonoBehaviour
{
    /*
     * Handels the hacking panel
     * Once the hacking panel is opened, numbers will randomly appear and the player tries to create a number that fulfills the condition written at the right side.
     */
    public Button[] buttons;

    // Start is called before the first frame update
    void Start()
    {
        print("Start");
        print("Length: " + buttons.Length);
        // add on Click methods
        foreach (Button button in buttons)
        {
            print("Loop");
            print("Button: " + button);
        }
        print(buttons[0]);
    }
}

The crazy thing is that this logs as:

Start
Length: 0
IndexOutOfRangeException: Index was outside the bounds of an array.
Length: 1
Loop
Button buttonname (UnityEngine.UI.Button)
buttonname (UnityEngine.UI.Button)
  1. Why does the Length print appears twice? I think it might be some kind of rescuing by UnrealEngine.
  2. Why does it first run with an empty list? How am I supposed to handle that?

>Solution :

Start indeed runs only once.

After the line

print("Start");

add the line

print(gameObject.GetInstanceID());

Run the code again and see if you get two different instance IDs.
If you do, the chances are that you attached the script Hacking to more than one GameObject.

If not, check if you accidentally attached the same script twice on the same object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading