//思路:使用.Instantiate方法控制生成 但是在生成前一定要計算好生成的魚兒的條件控制
public class FishController : MonoBehaviour
{
public int maxCount = 10; //魚池中魚最大存在的個數
public int count = 0; //當前魚池中魚的個數
public GameObject[] fishArray; //設置與魚的數組隨機生成魚
public float timer = 0; //生成魚的時間間隔
private float timerInvertal = 1f;//時間閘
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
CreatFish();
}
void CreatFish() //生成魚的方法
{
if (count >= maxCount) //如果當前魚池中的魚的數量大於10條結束程序
{
return;
}
timer += Time.deltaTime; //讓生成魚的時間間隔增加
if (timer >= timerInvertal) //如果生時間大於時間閘的時候生成一條魚
{
timer -= timerInvertal; //恢復時間間隔
count++; //魚的數量增加
//開始實例化魚
//首先實例化魚的prefabs
GameObject fishPrefabs = fishArray[Random.Range(0,fishArray.Length)];
//實例化魚的位置
Vector3 fishLoadPos = new Vector3(Random.value, Random.value, -Camera.main.transform.position.z); //隨機實例化魚兒本身的坐標
Vector3 fishWorldPos = Camera.main.ViewportToWorldPoint(fishLoadPos); //實例化魚的世界坐標
//實例化魚兒
GameObject.Instantiate(fishPrefabs, fishWorldPos, fishPrefabs.transform.rotation); //實例化魚的本體 位置 旋轉
}
}
}