- Home /
How to add a gameobject to a null gameobject
The question may seem confusing but I can't think of another way to ask it about it. So I have a project in cloning TWO DOTS the game. So I am making a grid system and I'm trying to assign the circles as game objects onto each grid. The following script creates the grid.
using UnityEngine;
using System.Collections;
public class gridManager : MonoBehaviour
{
public int width;
public int height;
public GameObject[] prefabArray;
private infoClass[] gridInfo1D;
private infoClass[,] gridInfo2D;
public float circleRad;
//private circleProperty[] circles;
void Start ()
{
gridInfo1D = Initialize (width * height);
gridInfo2D = Converter (gridInfo1D, width, height);
for (int row = 0; row < gridInfo2D.GetLength(0); row++) {
for (int column = 0; column < gridInfo2D.GetLength(1); column++) {
GameObject tempCircle = (GameObject)Instantiate (prefabArray [Random.Range (0, prefabArray.Length)], transform.position, Quaternion.identity);
gridInfo2D [row, column].circle = tempCircle;
gridInfo2D [row, column].SendMessage ("SetPos", new Vector2 (row * circleRad, column * circleRad));
}
}
}
infoClass[] Initialize (int size)
{
infoClass[] array = new infoClass[size];
return array;
}
infoClass[,] Converter (infoClass[] array1D, int width, int height)
{
infoClass[,] array2D = new infoClass[width, height];
for (int i=0; i<array1D.Length; i++) {
int row = i / width;
int column = i % width;
array2D [row, column] = array1D [i];
}
return array2D;
}
}
The next script below is the actual class for the grid.
using UnityEngine;
using System.Collections;
public class infoClass : MonoBehaviour
{
public string color;
public bool occupyCheck;
public GameObject circle;
void Update ()
{
if (circle) {
occupyCheck = true;
color = circle.tag;
} else {
occupyCheck = false;
}
}
void SetPos (Vector2 xy)
{
float x = xy.x;
float y = xy.y;
circle.transform.position = new Vector3 (x, y);
}
}
The problem is that when I run the code, it gives me a null reference error when I try to assign tempCircle to circle.
gridInfo2D [row, column].circle = tempCircle;
I understand when I first initialized the gridInfo2D the circle object doesn't exist yet, but is there a way where I can replace that null with an actual game object later?
Answer by Owen-Reynolds · Feb 22, 2015 at 03:39 PM
This is a regular C# problem. Nothing do to with gameObjects. Read a little more, just from a general site, about making arrays of classes. The array AND everything inside needs to be new'ed.
In other words, if you had a single infoClass A;, you'd need A=new infoClass();. If you have 1000 of them in an array, you don't get free stuff. You still need to NEW all 1000 of them.