2016-04-19 29 views
0

我有SpawnScript(下面) 我想在SPAWN中創建一個函數,因此我可以放置檢查器可以創建對象的最小和最大延遲時間。設置產生對象的延遲時間

using System.Collections; 
using System.Collections.Generic; 

public class SpawnController : MonoBehaviour 
{ 

    public float maxWidth; 
    public float minWidth; 

    public float minTime; 
    public float maxTime; 

    public float rateSpawn; 
    private float currentRateSpawn; 

    public GameObject tubePrefab; 

    public int maxSpawnTubes; 

    public List<GameObject> tubes; 

    // Use this for initialization 
    void Start() 
    { 


     for (int i = 0; i < maxSpawnTubes; i++) { 
      GameObject tempTube = Instantiate (tubePrefab) as GameObject; 
      tubes.Add (tempTube); 
      tempTube.SetActive (false); 

     } 

     currentRateSpawn = rateSpawn; 

    } 

    // Update is called once per frame 
    void Update() 
    { 

     currentRateSpawn += Time.deltaTime; 
     if (currentRateSpawn > rateSpawn) { 
      currentRateSpawn = 0; 
      Spawn(); 
     } 
    } 

    private void Spawn() 
    { 

     float randWitdh = Random.Range (minWidth, maxWidth); 

     GameObject tempTube = null; 

     for (int i = 0; i < maxSpawnTubes; i++) { 
      if (tubes [i].activeSelf == false) { 
       tempTube = tubes [i]; 
       break; 
      } 
     } 

     if (tempTube != null) 
      tempTube.transform.position = new Vector3 (randWitdh, transform.position.y, transform.position.z); 
     tempTube.SetActive (true); 
    } 
} 
+0

你要做的就是使用** **調用。再簡單不過了。如果你想要一個隨機的時間,它只是Random.Range(min,max);你可以像你說的那樣將min,max設置爲公共變量。 – Fattie

回答

1

你可以使用Time.realtimeSinceStartup作爲時間戳 - 這種有點適合你做atm的方式。 或者你使用的是非常統一的協程,並且更好地學習使用它們的時間早於晚。 或者您使用的調用可能是最簡單的方法。

http://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.htmlhttp://docs.unity3d.com/Manual/Coroutines.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

編輯: 好其實你也可以只在rateSpawn = Random.Range(minTime, maxTime);更新if語句中,這將最適合你目前的做法。

1

InvokeRepeating方法是處理代碼重複的方法。 你可以調用啓動事件的內部重複調用您的產卵方法,並指定時間根據您的選擇,因爲調用重複定義:

public void InvokeRepeating(string methodName, float time, float repeatRate); 

調用的方法,方法名的時間秒,然後每 repeatRate秒反覆。

這樣的編輯需要在您的腳本:

void Start(){ 
InvokeRepeating("Spawn",2, 0.3F); 
}