簡體   English   中英

實例化一定數量的預制件,統一C#

[英]Instantiate a certain amount of prefabs, unity c#

我想知道如何實例化一定數量的預制C#。

例如:

if(Input.GetKeyDown(KeyCode.K))
{
//Instantiate 20 prefabs
}

當按下按鈕時,運行一個循環,直到達到Space-1 ,然后在循環中每次實例化一個預制件。 這應該在Update功能中完成。 如果正確執行此操作,則不應繼續實例化。

int Space = 20;
public GameObject prefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.K))
    {
        //Instantiate 20 prefabs
        for (int i = 0; i < Space; i++)
        {
            GameObject obj = Instantiate(prefab);
            obj.transform.position = new Vector3(0, 0, 0);
        }
    }
}

我會用一個整數參數創建一個簡單的方法,允許您指定要創建多少個敵人。 除非在庫存廣告位對象本身中進行處理,否則您很可能需要使用其他邏輯來處理它們的位置。

public GameObject enemyPrefab;

//runs every frame, to check for the key press in this case
public void Update ()
{
    //did we press the specified key? (C)
    if (Input.GetKeyDown(KeyCode.C))
    {
        //call our method to create our enemies!
        CreateEnemies(20);
    }
}    

public void CreateEnemies (int enemies)
{
    //the amount of enemies we want to have
    //run through this loop until we hit the amount of enemies we want
    for (int i = 0; i < enemies; i++)
    {
        //create the new enemy based on the provided prefab
        Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM