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

2D array GameObject GetComponent NullReferenceException

Discussion in '2D' started by kichiro09, Jun 20, 2018.

  1. kichiro09

    kichiro09

    Joined:
    Jun 20, 2018
    Posts:
    1
    Hi, i'm newbie
    i have a question
    i had 2d array, after instantiate gameObject, i set it to array and try to call it by getComponent
    in next time i try to call exist object in array by index, it's not null but it doesnt have component,i haven't removed this component
    Someone has idea ?!
    Thanks for your help .
     

    Attached Files:

  2. 1Piotrek1

    1Piotrek1

    Joined:
    Mar 14, 2014
    Posts:
    130
    Your code is really complicated, I stared at it for like 5 minutes and I still can't really understand what is happening.
    Maybe if you posted the entire code it would be easier.

    My thoughts:
    Try to log the name of the blocks[1, 0] object to see what it really is.
    Maybe it was set or modified in different case label after being assigned, I can't see the rest of the switch statement.

    On a side note:
    Don't use GetComponent that often. It is a very expensive function. Consider changing the type of your array to Block.
    It should also help you with your problem because then it'd be impossible to have a block without Block component.
    If you need to assign different Block classes to the array you can always make them inherit from the Block class:
    Code (CSharp):
    1. class Block : MonoBehaviour{ ... }
    2. class ShiningBlock : Block { ... }
    3. class AnimatedBlock : Block { ... }
    4.  
    5. Block blocks[,]= new Block[x, y];
    6. blocks[0, 0]=new ShingBlock();
    After you called an expensive function once you should save its results for later, so:
    Code (CSharp):
    1. a.GetComponent<Fruit>().SetPos(j, i);
    2. a.GetComponent<Fruit>().SetVal(k);
    should be:
    Code (CSharp):
    1. Fruit fruit=a.GetComponent<Fruit>();
    2. fruit.SetPos(j, i);
    3. fruit.SetVal(k);
    Same goes for GameObject.FindGameObjectWithTag(). Each time you call it Unity must loop through every object on the scene and compare it's tag with the one you provided. And again, it is really slow and you should call it only once and save its results for later.