- Home /
Instantiate and arrays
I am at a loss here. What I am trying to do is create a level from a number of prefabs. This is just the first pass the create 1-5 platforms. I want to build all of the prefabs that get created into an array that I can then check as I add more things to make sure nothing is colliding (I could use code for that too, but for now just want to get the array working :( ). That is what the while Z is for, I want to just move it until I find a location that isn't colliding.
code:
public class CreatePlatforms : MonoBehaviour {
private int x;
private int y;
private bool z;
private float xCoord;
private float zCoord;
public Transform Platform;
private int count = 0;
private GameObject[] prefabArray;
// Use this for initialization
void Start () {
for(x=0;x<5;x++)
{
y = Random.Range(1, 100);
if(y < (x * 20))
{
Debug.Log(count);
prefabArray[count] = Instantiate(Platform, new Vector3(0, 0.5f, 0), Quaternion.identity) as GameObject;
Debug.Log("platform added");
z = false;
while(!z)
{
xCoord = Random.Range(-25.0f, 25.0f);
zCoord = Random.Range(-25.0f, 25.0f);
prefabArray[count].transform.position = new Vector3(xCoord, 0.5f, zCoord);
z = true;
}
count++;
}
}
}
// Update is called once per frame
void Update () {
}
}
error :
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
CreatePlatforms.Start () (at Assets/CreatePlatforms.cs:23)
Any help is much appreciated.
Answer by whebert · Apr 03, 2013 at 12:58 AM
You need to instantiate your prefab array first, before you try to assign anything inside it.
private GameObject[] prefabArray = new GameObject[5];
Thanks, now i get the same error on line 25. prefabArray[count].transform.position = new Vector3(xCoord, 0.5f, zCoord);
Hmm. You probably need to make your "Platform" a GameObject ins$$anonymous$$d of Transform.
idk how you guys know all of this stuff >.< but that worked!! thanks!!
Answer by robertbu · Apr 03, 2013 at 01:03 AM
You are not allocating any space for the array. You can do something like:
private GameObject[] prefabArray = new GameObject[10];
In addition given the way you are using it, make Platform a GameObject (and lower case):
public GameObject platform;
By convention variable names are lower case, classes are upper case. The compiler does not care, but it makes it more difficult for other people to read your code if you use upper case variables.
Your answer
Follow this Question
Related Questions
Prefabs instantiated from an array are keeping their public int value 1 Answer
Finding the Sum of Values of Multiple GameObjects in an Array + Variable Sized arrays 0 Answers
Randomly instantiate objects from array without choosing the same item twice. 2 Answers
An Instantiated object to array problem 2 Answers
How to put gameObjects to the list? 4 Answers