- Home /
Unable to randomly instantiate prefab from array
New to Unity and programming in general. Looking for a C# solution please.
I am trying to spawn an object that is selected at random from a group of objects (asteroids in this case), however, nothing is spawning in Unity when I run the game. Within the Unity interface I have set the prefabs in the array. There are no errors or warnings. I have similar scripts that instantiate a single object repeatedly with no trouble at all.
I have spent many hours trying to figure this out (including scouring the net for an answer) and I have made no headway. Please help if you can.
The full code I am using for this script: ` using System.Collections; using System.Collections.Generic;
public class AsteroidSpawnerScript : MonoBehaviour
{
public float numAsteroids;
public float xMin = 15f;
public float xMax = 30f;
public float yMin = 3.5f;
public float yMax = -4.5f;
public GameObject[] asteroidGroup = new GameObject[7];
void start()
{
InvokeRepeating ("SpawnAsteroid", 1, 5f);
}
void SpawnAsteroid()
{
GameObject newParent = GameObject.Find ("L2 Enviro Elements");
for (int i = 0; i < numAsteroids; i++)
{
Vector3 newPos = new Vector3 (Random.Range (xMin, xMax), Random.Range (yMin, yMax), 0);
GameObject asteroidMG = Instantiate (asteroidGroup[Random.Range (0,6)], newPos, Quaternion.identity) as GameObject;
asteroidMG.transform.parent = newParent.transform;
}
}
}
What have I done wrong here? I would be in better shape if Unity would give me an error, but being so new to programming I don't really know what to change.
Answer by robertbu · Apr 28, 2014 at 09:45 PM
You misspelled 'Start'. You need an upper case 'S'.
Oh. $$anonymous$$y. God.
Well, thank you! That was certainly it. Jeeze...
Answer by Kyle Cavasos · Apr 28, 2014 at 10:03 PM
Perhaps try:
void Start()
{
InvokeRepeating ("SpawnAsteroid", 1, 5f);
}
?
Note the capital S in start. :)