Question by
ltrout1999 · Oct 12, 2016 at 01:27 AM ·
nullreferenceexceptionnull reference exceptionobject-reference-error
Unknown Cause of NullReferenceException?
So I was going through a question I asked awhile ago because I needed a script someone helped me make off of it and found it and was going to use it in my game, but I'm getting a NullReferenceException error.
Here is the error:
NullReferenceException: Object reference not set to an instance of an object
GridCreator.Place () (at Assets/Scripts/GridCreator.cs:27)
My code for the GridCreator.cs is this: using UnityEngine; using System.Collections; using UnityEditor;
public class GridCreator : MonoBehaviour {
[MenuItem("Grid Creator/Create the Grid (9x13)")]
static void Place()
{
// change these to work for you:
string prefabName = "AnchorPoint"; // case sensitive
Vector3 gridSize = new Vector3(9, 1, 13); // ie. (10, 1, 5) will generate 10 cubes in the x direction, 1 in the y, and 5 in the z
Vector3 offset = new Vector3(1, 1, 1); // size of the cubes - default is (1, 1, 1)
string newCubeName = "AnchorPoint"; // leave blank for default name eg. "Cube(Clone)"
GameObject cube = Resources.Load(prefabName, typeof(GameObject)) as GameObject;
for (int x = 0; x < gridSize.x; ++x)
{
for (int y = 0; y < gridSize.y; ++y)
{
for (int z = 0; z < gridSize.z; ++z)
{
Vector3 pos = new Vector3(x * offset.x, y * offset.y, z * offset.z);
GameObject go = Instantiate(cube, pos, cube.transform.rotation) as GameObject;
if (newCubeName != "")
go.name = newCubeName;
}
}
}
}
}
I am confused as to why it is suddenly not working when it did last time I used it. Only difference is the prefab I'm using. I was using a cube, now I'm using a sphere, but that shouldn't matter.
Comment
Best Answer
Answer by ltrout1999 · Oct 12, 2016 at 01:41 AM
Nevermind, I fixed my issue! Forgot I had to put "/Prefabs/(insert prefab name here)" as the string prefabName.