簡體   English   中英

實例化多個預制件

[英]Instantiate multiple prefabs

我正在做一個球類游戲,所以球通過列並根據 columnPoolSize 實例化自己,

我想在這里創建多個預制件。 它只根據列大小初始化一個預制件......我需要為 columnPrefab GameObject 創建另一個數組。 但是我嘗試這樣做,但沒有成功......

public class ColumbPool : MonoBehaviour
{
  public int columnPoolSize = 5;

  public GameObject[] columns;
  public GameObject columnPrefab;
  private Vector2 objectPoolPosition = new Vector2(-15f,-25f);
  private float timeSinceLastSpawn;
  public float spawnRate = 4f;
  public float columnMin = -1f;
  public float columnMax = 3.5f;
  private float spawnXPosition = 10f;
  private int currentColumn = 0;

    void Start()
    {
        columns = new GameObject[columnPoolSize];
        for (int i = 0; i < columnPoolSize; i++)
            {
                columns[i] = (GameObject)Instantiate(columnPrefab, objectPoolPosition, Quaternion.identity);
            }
    }

    void Update()
    {
      timeSinceLastSpawn += Time.deltaTime;
      if (GameController.instance.gameOver==false && timeSinceLastSpawn>=spawnRate)
      {
          timeSinceLastSpawn = 0;
          float spawnYPosition = Random.Range(columnMin, columnMax);
          columns[currentColumn].transform.position = new Vector2(spawnXPosition,spawnYPosition);
          currentColumn++;
          if (currentColumn>=columnPoolSize)
          {
              currentColumn = 0;
          }
      }
   }
}
void Start()
    {
        columns = new GameObject[columnPoolSize];
        for (int i = 0; i < columnPoolSize; i++)
            {
                columns[i] = (GameObject)Instantiate(columnPrefab, objectPoolPosition, Quaternion.identity);
            }
    }

變成

private GameObject[] instantiatedColumns;
public GameObject[] columnPrefabs;
void Start()
    {
        instantiatedColumns= new GameObject[columnPrefabs.Length];
        for (int i = 0; i < columnPrefabs.Length; i++)
            {
                instantiatedColumns[i] = Instantiate(columnPrefabs[i], objectPoolPosition, Quaternion.identity);
            }
    }

通過這種方式,您將實例化預制列數組中的每個預制件(填充在檢查器中)並將引用保存到新數組“instantiatedColumns”中,然后您可以在 Update() 中使用此數組

暫無
暫無

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

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