Search Unity

Script Throws Errors Unless GameObject is Selected

Discussion in 'Scripting' started by UnityMaster2020, Mar 19, 2019.

  1. UnityMaster2020

    UnityMaster2020

    Joined:
    May 10, 2015
    Posts:
    1
    I get a NullReferenceException when trying to view the count of a list after it has been modified via script.

    You can recreate this issue by attaching the following script to any object, using the 'A' and 'D' keys to modify the list, and the 'E' key which is supposed to print the count.

    You will find that if you select the GameObject to which the script is attached in the hierarchy, there will be no errors. Once the object is deselected, errors occur.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. [System.Serializable]
    6. public class Slot
    7. {
    8.     public List<GameObject> layers = new List<GameObject>();
    9. }
    10.  
    11. public class Test : MonoBehaviour
    12. {
    13.     public Slot[] slots;
    14.  
    15.     private IEnumerator Start() // A coroutine is used because it otherwise gives an error
    16.     {
    17.         slots = new Slot[7];
    18.         yield return new WaitForSeconds(0.1f);
    19.         slots[3].layers.Add(null);
    20.     }
    21.  
    22.     private void Update()
    23.     {
    24.         if (Input.GetKeyDown(KeyCode.A)) Rotate(false);
    25.         if (Input.GetKeyDown(KeyCode.D)) Rotate(true);
    26.         if (Input.GetKeyDown(KeyCode.E)) Debug.Log(slots[0].layers.Count);
    27.     }
    28.  
    29.     private void Rotate(bool forward)
    30.     {
    31.         for (int i = 0; i < slots.Length; i++)
    32.         {
    33.             try
    34.             {
    35.                 if (forward) slots[6 - i] = slots[6 - i - 1];
    36.                 else slots[i] = slots[i + 1];
    37.             }
    38.             catch
    39.             {
    40.                 if (forward) slots[6 - i] = null;
    41.                 else slots[i] = null;
    42.             }
    43.         }
    44.     }
    45. }
     
  2. drcrck

    drcrck

    Joined:
    May 23, 2017
    Posts:
    328
    Code (csharp):
    1.  
    2. void OnEnable() {
    3.  if(slots == null) {
    4.   slots = new Slot[7];
    5.   for(var i = 0; i < slots.Length; i++){
    6.     slots[i] = new Slot();
    7.   }
    8.  }
    9. }
    10.