Search Unity

Object reference not set to an instance of an object, but the object was just instantiated. Help!

Discussion in 'Scripting' started by Rafa_WR, May 15, 2019.

  1. Rafa_WR

    Rafa_WR

    Joined:
    May 15, 2019
    Posts:
    9
    So, I have a bit of experience with Unity and now have found an error which I can't understand.

    The console says that the object I'm referring to isn't instantiated, but the variable was created like this:

    Code (CSharp):
    1. GameObject newPiece = Instantiate(availablePieces[selectedFrame], gameManager.transform);
    Then the reference to the GameObject is passed to another Component that is instantiated but has no issues and then goes into a non MonoBehaviour script and it gives me an error when doing so in these lines of code (the second one to be more specific):
    Code (CSharp):
    1. Piece pieceComponent = newPiece.GetComponent(typeof(Piece)) as Piece;
    2.  
    3. tileMap[x, y].ChangePiece(pieceComponent);
    I don't understand the error as the object reference is already instantiated, so I don't know how to fix it.

    All help is appreciated!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    Did you allocate whatever object is supposed to go into tileMap[x,y] first?
     
  3. Rafa_WR

    Rafa_WR

    Joined:
    May 15, 2019
    Posts:
    9
    Thank you!

    I was thinking the problem was with the instance of the GameObject but now I found out that I have another problem with filling in the tileMap array (it was supposed to be filled with some default tiles but it isn't working right now).
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    The best laid plans of mice and men are often uninitialized.
     
    StarManta likes this.