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

时间:2018-07-03 14:57:43

标签: c# unity3d rigid-bodies

我正在制作2D游戏,其中球不断以红色,绿色,蓝色或黄色显示。有一个全部四种颜色的方形桨。如果球击中相同的颜色,则应自行消灭。我已经创建了一个用于实例化对象的脚本。

这是脚本:

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:类型为'GameObject'的对象为   已销毁,但您仍在尝试访问它。您的脚本应该   请检查它是否为null或不应该破坏该对象。”

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

1 个答案:

答案 0 :(得分:3)

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

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);
}