【问题标题】:How can I randomize the public Transform tilePrefab in my code?如何在我的代码中随机化公共 Transform tilePrefab?
【发布时间】:2020-02-16 10:41:23
【问题描述】:

所以我想制作一个地图生成器并为瓷砖制作一个预制件。但我想制作更多随机选择的瓷砖。

如何让 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。

【问题讨论】:

  • 一种方法是制作一个预制件数组,然后仅使用随机索引,例如...或者每次Instantiate 分配随机坐标

标签: c# unity3d random


【解决方案1】:

拥有一个包含所有瓷砖预制件的数组。为您的新图块随机选择一个索引。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多