首页 文章

当实例化的gameobject被破坏时,它不再产生克隆

提问于
浏览
0

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

它不再实例化球并且不断为它应该发起的每个球提供这个错误 . 我希望我的脚本继续实例化克隆 .

1 回答

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

相关问题