The question is answered, right answer was accepted
First instantiated gameObject`s component is null
Hello guys! Im just instantiating some gameObjects and then editing some variables. So the problem is only with the first instantiated gameObject doesnt have Image Component, while others have.
This is how i instantiate:
public void constructGrid(int height,int width,Vector2 startPosition, Vector2 Offset)
{
nodes = new GameObject[height, width];
int id = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
nodes[i, j] = Instantiate(NodePrefab, new Vector3(startPosition.x + j * Offset.x, startPosition.y + Offset.y * i, 1), Quaternion.identity) as GameObject;
nodes[i, j].transform.SetParent(transform,false);
nodes[i, j].GetComponent<Node>().ID = id;
id++;
}
}
}
if i dont check if component is null, then i get null reference exeption on first gameObject in array.
void Start()
{
if (GetComponent<Image>() == null)
gameObject.AddComponent<Image>();
ImageComponent = GetComponent<Image>();
}
This is how i check what gameObject has null component, in Debug.Log i get only 0 index which is first element in array.
void Update()
{
if (GetComponent<Image>() == null)
{
Debug.Log(id);
}
}
If i check for null and then add component, than everything works fine, but why does that happen?
I don't think I have all the context I need here. Are those Start () and Update () methods both in your Node class, or in a separate class on the same GameObject?
Thanks for helping, you are write i accidently inherited grid class from node, so i had 2 objects.
Follow this Question
Related Questions
c# animation.Play("animation") 0 Answers
Only spawning power ups that the player wants in that game 1 Answer
Adding classes to objects 0 Answers
GetComponent returns null however comparison to null returns false 2 Answers
Is there no way to inherit children's components for validation/checking purposes? 1 Answer