【问题标题】:Instantiate GameObject at Random time is not working在随机时间实例化游戏对象不起作用
【发布时间】:2015-06-13 00:38:40
【问题描述】:

我希望敌人在 1-5 秒之间随机生成,但是当我在游戏中应用脚本时,游戏中充斥着大量敌人,并且它不断地不断生成敌人!

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

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    好像在更新里面你缺少一个'='

    即:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      相关资源
      最近更新 更多