NullReferenceException even when the object is declared assigned and then used
Hello, I have a script on a level picker scene, I need to activate the level only when the (level before it) is been played, so I'm saving the achievement of the level in a PlayerPrefs (I know it's not a good practice, I'm planning to change this later to binary file) but that is not the point, the thing is, I have a certain amount of buttons, and a script component (same script component in all buttons), I'm adding them to the LevelPickerControl script via [SerialaizeField] GameObject[], so they are already referenced, when I try to access the script component in each GameObject inside a for loop, I'm getting a NullReferenceException error even though I'm already declaring the script reference, and assigning the component to it, before using it! The funny thing is that the game is running as expected, but it's still annoying to have the error popping up in the console.
// Code
using UnityEngine;
using UnityEngine.UI;
public class LevelsPickerControl : MonoBehaviour
{
[SerializeField] GameObject[] levelsArray;
// Declaring the variable
SceneLoadButton sceneLoadButton;
private void Awake()
{
// Set all levels buttons to disabled
foreach (GameObject level in levelsArray)
{
if (level.GetComponent<Button>() != null)
{
level.GetComponent<Button>().interactable= false;
}
}
levelsArray[0].GetComponent<Button>().interactable= true;
for (int i = 0; i < levelsArray.Length; i++)
{
// initializing, setting the reference
sceneLoadButton = levelsArray[i].GetComponent<SceneLoadButton>();
// Error triggered here, SceneLoadButton script has a serialize field (sceneName) which is set to "" in the script
// In the inspector, this string has the value of the button, for each button
// Example: sceneName = Level 1, for level 1 button gameObject
if (PlayerPrefs.GetInt(sceneLoadButton.sceneName)> 0)
{
if (i < (levelsArray.Length - 1))
{
levelsArray[i + 1].GetComponent<Button>().interactable= true;
}
}
}
}
}