在Update()中仅实例化一个对象

时间:2019-06-01 21:10:31

标签: c# unity3d

我试图在udpate方法中仅实例化一个预制件,但事实是,它实例化了两次。我不知道该如何解决这个问题。

我该怎么办?我创建了一个名为spawned的布尔值,但是它不起作用。

public class SpawnaCasos : MonoBehaviour
{    
    public GameObject[] Casos;

    private GameController gameController;//variável para acessar o script do gamecontroller
    private GameObject controller;
    private bool spawned = false;
    // Start is called before the first frame update
    void Start()
    {
        controller = GameObject.FindGameObjectWithTag("Controller");
        gameController = controller.GetComponent<GameController>();
    }

    // Update is called once per frame
    void Update()
    {
        if (gameController.contadorPontos == 14 && spawned == false)
        {
            Instantiate(Casos[UnityEngine.Random.Range(0, 8)], transform.position, this.transform.rotation);
            spawned = true;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public class SpawnaCasos : MonoBehaviour
{    
    public GameObject[] Casos;

    private GameController gameController;
    private GameObject controller;

    void Start()
    {
        controller = GameObject.FindGameObjectWithTag("Controller");
        gameController = controller.GetComponent<GameController>();
        InstantiateCasos();
    }

    void Update()
    {
        if (gameController.contadorPontos == 14)
            InstantiateCasos();
    }
    void InstantiateCasos(){
        Instantiate(Casos[UnityEngine.Random.Range(0, 8)], transform.position, transform.rotation);
    }
}