- Home /
Problem with calling function calling order [C#]
Hi, i am having a problem in which i am trying to make a space invaders game, however when the cubes spawn they only descend when in a certain order, for example, thing 4 will only descend when thing 3 is descending, and thing 3 will only descend when thing 2 is descending, and thing 2 will only descend when thing 1 is descending. So they have to wait for thing 1 to spawn before the rest can descend etc. Thanks in advance, Matt.
using UnityEngine;
using System.Collections;
public class moveUp : MonoBehaviour {
public GameObject shot;
public Transform pos1;
public Transform pos2;
public Transform pos3;
public Transform pos4;
public Rigidbody enemy;
private Rigidbody thing1;
private Rigidbody thing2;
private Rigidbody thing3;
private Rigidbody thing4;
public float speed = 2f;
private bool boolean = true;
void Update(){
StartCoroutine("hi");
thing1.transform.Translate(Vector3.down * speed * Time.deltaTime);
thing2.transform.Translate(Vector3.down * speed * Time.deltaTime);
thing3.transform.Translate(Vector3.down * speed * Time.deltaTime);
thing4.transform.Translate(Vector3.down * speed * Time.deltaTime);
}
public IEnumerator hi(){
if(boolean == true){
boolean = false;
int random = Random.Range(1, 7);
switch (random) {
case 1:
thing1 = Instantiate(enemy, pos1.position, pos1.rotation) as Rigidbody;
break;
case 2:
thing2 = Instantiate(enemy, pos2.position, pos2.rotation) as Rigidbody;
break;
case 3:
thing3 = Instantiate(enemy, pos3.position, pos3.rotation) as Rigidbody;
break;
case 4:
thing4 = Instantiate(enemy, pos4.position, pos4.rotation) as Rigidbody;
break;
}
yield return new WaitForSeconds(3);
boolean = true;
}
}
}
Answer by GameVortex · Mar 08, 2014 at 07:18 PM
That is because you cannot use an object that has no value, so before the things have been instantiated the script throws null reference errors in the update and stops working. Easiest way to fix this is to check if the thing object is not null before using it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135714im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
A node in a childnode? 1 Answer
Run Function when user shakes mobile andriod unity c# 0 Answers
How many objects is too many? 2 Answers