簡體   English   中英

如何在我的代碼中隨機化公共 Transform tilePrefab?

[英]How can I randomize the public Transform tilePrefab in my code?

所以我想制作一個 map 發電機並有一個瓷磚的預制件。 但我想制作更多隨機選擇的瓷磚。

我怎樣才能讓它每次從一組預制件中隨機選擇 tilePrefab?

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

public class MapGenerator : MonoBehaviour
{

    public Transform tilePrefab; //This is the part which I want to be random
    public Vector2 mapSize;

    private void Start()
    {
        GenerateMap();
    }
    public void GenerateMap()
    {
        for (int x = 0; x < mapSize.x; x++)
        {
            for (int y = 0; y < mapSize.y; y++)
            {
                Vector3 tilePosition = new Vector3(-mapSize.x / 2 + 0.5f + x, 0,-mapSize.y / 2 + 0.5f + y);
                Transform newTile = Instantiate(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 360)) as Transform;
            }
        }
    }

}

我希望每次生成瓷磚時都會隨機選擇 tilePrefab。

有一個包含所有瓷磚預制件的數組。 為您的新圖塊隨機選擇一個索引。

            Transform newTile = Instantiate(tilePrefabs[Random.Range(0, tilePrefabs.Length - 1), tilePosition, Quaternion.Euler(Vector3.right * 360)) as Transform;

暫無
暫無

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

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