- Home /
Random Object Spawning
Hello im trying to spawn two Objects but i get a error "NullReferenceException: Object reference not set to an instance of an object" I know what that means but i cant find my error. The error marks me sometimes the first transform(marked) and sometimes the second. It looks like that he have problems to spawn the second object after the first object was already spawned.
public class PlanetSpawner : MonoBehaviour {
//Planeten
public GameObject Planet1;
public GameObject Planet2;
private int momentanerPlanet = 0;
//Planten-Klons
private GameObject[] CPlanet1;
private GameObject[] CPlanet2;
//Random
private int Planetchoser;
//Settings
public int MaxPlanets = 5;
public float minSpawn = -1f;
public float maxSpawn = 3.5f;
public float spawnRate = 4f;
private Vector2 PlanetPosition = new Vector2(-15f, -25f);
private float timeRespawn;
//Spawn Positions
private float spawnXPosition = 10f;
// Use this for initialization
void Start() {
CPlanet1 = new GameObject[MaxPlanets];
CPlanet2 = new GameObject[MaxPlanets];
for(int i = 0; i < MaxPlanets; i++)
{
Planetchoser = Random.Range(0, 7);
if(Planetchoser < 3 )
{
CPlanet1[i] = (GameObject)Instantiate(Planet1, PlanetPosition, Quaternion.identity);
}
else if(Planetchoser > 3)
{
CPlanet2[i] = (GameObject)Instantiate(Planet2, PlanetPosition, Quaternion.identity);
}
Debug.Log(Planetchoser);
}
}
// Update is called once per frame
void Update()
{
timeRespawn += Time.deltaTime;
if (MainContol.instance.gameOver == false && timeRespawn >= spawnRate)
{
{
timeRespawn = 0;
float YPosition = Random.Range(minSpawn, maxSpawn);
if(Planetchoser < 3)
{
//the Error appears here
CPlanet1[momentanerPlanet].transform.position = new Vector2(spawnXPosition, YPosition);
momentanerPlanet++;
Debug.Log("Planet1");
}
else if(Planetchoser > 3)
{
// or the error appears here
CPlanet2[momentanerPlanet].transform.position = new Vector2(spawnXPosition, YPosition);
momentanerPlanet++;
Debug.Log("Planet2");
}
if( momentanerPlanet >= MaxPlanets)
{
momentanerPlanet = 0;
}
}
}
}
} I trying it for a while now so i hope you can help me
Your answer
Follow this Question
Related Questions
How to Instantiate a GameObject from a ScriptableObject piece of script? 0 Answers
How prefab the instance works? 1 Answer
Clicker game instantiate prefab depending on gold per click 0 Answers
instantiating a projectile continually over time 2 Answers
Problem with instantiating the object in untiy at certain time intervals 1 Answer