Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Array Null reference

Discussion in 'Scripting' started by DarkX, May 27, 2015.

  1. DarkX

    DarkX

    Joined:
    Apr 6, 2014
    Posts:
    42
    hey guys, I'm with bug that was not to happen, when I try to take an element of an array this error shows: Null reference exception

    Here the script
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. [System.Serializable]
    6. public class Items{
    7. public string itemName;
    8. public int Amount;
    9. }
    10.  
    11. public class New : MonoBehaviour{
    12. public Items [] X;
    13. void Start(){
    14. X =new Items[4];
    15. }
    16. void OnGUI(){
    17. GUI.Label(newRect(Screen.width /2,Screen.height *.2f,Screen.width,Screen.height),"Name: "+ X [0].itemName +" Amount: "+ X [0].Amount);
    18. GUI.Label(newRect(Screen.width /2,Screen.height *.4f,Screen.width,Screen.height),"Name: "+ X [1].itemName +" Amount: "+ X [1].Amount);
    19. GUI.Label(newRect(Screen.width /2,Screen.height *.6f,Screen.width,Screen.height),"Name: "+ X [2].itemName +" Amount: "+ X [2].Amount);
    20. GUI.Label(newRect(Screen.width /2,Screen.height *.8f,Screen.width,Screen.height),"Name: "+ X [3].itemName +" Amount: "+ X [3].Amount);
    21. }
    22. }
    23.  
    someone can help me ?

    thks in advance
     
  2. bear_love_honey

    bear_love_honey

    Joined:
    Jan 7, 2015
    Posts:
    31
    you need first initialize all items in massive. when you write
    1. X =new Items[4];
    it means that you allocate memory for 4 elements in massive.

    After this you need make
    Code (CSharp):
    1. for(int i = 0; i < 4; i++)
    2. X[i] = new Items();
     
    hamsterbytedev likes this.