简体   繁体   中英

Trying to setParent during update function gives error

I am trying to spawn a star at a set time interval in Unity. But I would like to parent these stars not to clutter my inspector.

But when I try to do this it gives "NullReferenceExeption: Object reference not set to an instance of an object."

I have used this type of code elsewhere succesfully before but not within the update function.

The code that I use is below. Thanks for your time and help in advance.

UPDATE:

I used

Debug.Log (obj);
Debug.Log (starParent);

to check if the GameObjects exist or not. It find starParent but not obj.

So thee problem is that it returns Null for the GameObject it just instantiated. Does this have something to do with it being with the Update function?

public class StarSpawner : MonoBehaviour {

    public Star star;
    private float spawnRate = 3f;
    public static float time = 0;
    private GameObject starParent;

    void Start() {
        if (!GameObject.Find ("StarParent")) {
            new GameObject ("StarParent");
        }

        starParent = GameObject.Find ("StarParent");
        SetNextStarTime();
    }

    void Update () {
        if (Time.timeSinceLevelLoad > time) {
        Vector3 spawnPosition = new Vector3 (Random.Range (1f, 9f), 7);
        GameObject obj = Instantiate (star, spawnPosition, Quaternion.identity) as GameObject;
        obj.transform.SetParent (starParent.transform);
        SetNextStar ();
        }
    }

    void SetNextStarTime(){
        time = Time.timeSinceLevelLoad + spawnRate + Random.Range(0f, 5f);
    }

}
public Star star;

应该

public GameObject star;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM