Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object Reference not set to an instance of an object

Discussion in 'Scripting' started by HAlbera, Jan 7, 2014.

  1. HAlbera

    HAlbera

    Joined:
    Jun 7, 2013
    Posts:
    63
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class gridManager : MonoBehaviour {
    5.  
    6.     bool blahblah = false;
    7.  
    8.     public GameObject[,] world;
    9.  
    10.     public void addToWorld (int x, int y, string type){
    11.         //if the array position is not empty
    12.         if (world [x,y] != null) {
    13.             GameObject n = (GameObject)Instantiate(Resources.Load(type));
    14.             //tell the object where is is
    15.             n.transform.position = new Vector2(x*10,y*10);
    16.             world [x,y] = n;
    17.         }
    18.     }
    19.  
    20.     // Use this for initialization
    21.     void Start () {
    22.    
    23.     }
    24.    
    25.     // Update is called once per frame
    26.     void Update () {
    27.         if (blahblah == false) {
    28.             addToWorld (2,2,"Test Object");
    29.             blahblah = true;
    30.         }
    31.    
    32.     }
    33. }
    34.  
    I assume its not finding the "Test Object" prefab?

    What I'm trying to do is Instantiate a prefab with 'guidance' from a grid manager. For now I'm trying to check if the array position is empty. If it is, instantiate the "Test Object" prefab at the given x,y coords (*10, because grid size ofc.) Then put a reference to the game object in the array so I can check if from other objects later, by position in the array (and by extension in the game world.)

    Any help would be great.

    Halbera.

    EDIT:
    Code (csharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. gridManager.addToWorld (Int32 x, Int32 y, System.String type) (at Assets/gridManager.cs:12)
    3. gridManager.Update () (at Assets/gridManager.cs:28)
     
    Last edited: Jan 7, 2014
  2. MDragon

    MDragon

    Joined:
    Dec 26, 2013
    Posts:
    329
    The full error (particularly the line number) would help. These types of errors are also abstract, but it may help.

    Also, not the best at C#, but in line 8, shouldn't it be GameObject[0] rather than [,]?

    And, sorry that my mind isn't really able to understand that code at the moment. Good luck!
     
  3. HAlbera

    HAlbera

    Joined:
    Jun 7, 2013
    Posts:
    63
    I'm trying to make a 2 dimensional array, I read in the scripting docs that is done using [,]

    Thanks anyway.