当实例化的游戏对象被销毁时,它不再产生克隆

when instantiated gameobject is destroyed it does not produce anymore clones

我正在制作一个 2D 游戏,其中一个球不断实例化为红色、绿色、蓝色或黄色。有一个带有所有 4 种颜色的方形桨。如果球击中相同的颜色,它应该自我毁灭。我已经制作了一个用于实例化对象的脚本。

这是那个脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ballSpawn : MonoBehaviour {

    public GameObject ball;
    public Transform ballSpawnTransform;
    private float startTime = 2f; 
    private float repeatRate = 2f;

    // Use this for initialization
    void Start () {
        InvokeRepeating ("BallSpawn", startTime, repeatRate);
    }

    // Update is called once per frame
    void Update () {

    }

    public void BallSpawn(){
        ball = Instantiate (ball, ballSpawnTransform.position, ballSpawnTransform.rotation);
    }
}

我在预制件上附上了变色方法和破坏方法。下面提供了脚本:-

public class ball_controller : MonoBehaviour {

    [SerializeField]
    public int colorInt;
    Rigidbody2D rb;

    // Use this for initialization
    void Start () {
        //rb = this.gameObject;
        colorInt = Random.Range (1, 5);
        switch (colorInt) {
        case 1:
            gameObject.GetComponent<Renderer> ().material.color = Color.red;
            break;
        case 2:
            gameObject.GetComponent<Renderer> ().material.color = Color.green;
            break;
        case 3:
            gameObject.GetComponent<Renderer> ().material.color = Color.blue;
            break;
        case 4:
            gameObject.GetComponent<Renderer> ().material.color = Color.yellow;
            break;
        }
        rb = this.gameObject.GetComponent<Rigidbody2D> ();
        rb.velocity = new Vector3 (0f, -5f, 0f);
    }

    // Update is called once per frame
    void Update () {

    }

    void OnTriggerEnter2D(Collider2D hit){
        if (hit.gameObject.GetComponent<Renderer> ().material.color == gameObject.GetComponent<Renderer> ().material.color) {
            Destroy (this.gameObject);
        } else {
            DestroyObject (this.gameObject);
        }

    }
}

但是当它销毁游戏对象时。它给出了以下错误。

"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object."

它不再实例化球,并为它本应启动的每个球不断给出此错误。我希望我的脚本继续实例化克隆。

我相信这可能是因为您正在用新实例化的球覆盖 ball。一旦该球被销毁,对该组件的引用就会被破坏。相反,您应该有两个单独的游戏对象变量 - 一个用于保存球预制件,一个用于保存对脚本中新球的引用:

public GameObject ball; //the prefab you want to spawn
private GameObject spawnedball; //a local temporary reference

public void BallSpawn(){
    spawnedball = Instantiate (ball, ballSpawnTransform.position, ballSpawnTransform.rotation);
}