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:
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)
- Why does the
Lengthprint appears twice? I think it might be some kind of rescuing by UnrealEngine. - 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.