在随机时间实例化GameObject不起作用

时间:2015-06-13 00:38:40

标签: unity3d

我希望敌人在1-5秒之间的随机时间产生,但是当我在游戏中应用脚本时,游戏会被敌人发送垃圾邮件并且它会不断地产生敌人!

enter image description here

 using UnityEngine; using System.Collections;

 public class Game_Control : MonoBehaviour {

     private bool Spawn1=true;
     public GameObject Spearman;
     private float STimer;

     void Start () {
         STimer =  Random.Range(1f,5f);
     }

     void Update () {
         if (Spawn1 = true) {
             Instantiate (Spearman, transform.position, transform.rotation);
             StartCoroutine (Timer ());
         } 
     }

     IEnumerator Timer() {
         Spawn1 = false;
         yield return new WaitForSeconds (STimer);
         Spawn1=true;
     }
 }

1 个答案:

答案 0 :(得分:4)

似乎在更新内你缺少'='

即:

if (Spawn1 = true) 

应该是:

if (Spawn1 == true)

另外,为避免对Update方法进行额外处理,您可以执行以下操作:

void Start() 
{
    StartCoroutine(AutoSpam());
}

void Update() 
{
    // Empty :),
    // but if your Update() is empty you should remove it from your monoBehaviour! 
}

IEnumerator AutoSpam() 
{
    while (true)
    {
        STimer = Random.Range(1f,5f);
        yield return new WaitForSeconds(STimer);
        Instantiate(Spearman, transform.position, transform.rotation);
    }
}
相关问题