Unity--随机生成游戏对象
创建空对象RandomObject及对应C#脚本RandomObject
在脚本中声明数组RandomObjects用于保存生成对象的类型,在project文件中拖入对象。

按下S键在x方向上随机产生一种游戏对象
public GameObject[] randomObjects;
private float zBound = 30f;
private float xBound = 10f;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
float xrange=Random.Range(-xBound,xBound);
int index = Random.Range(0, randomObjects.Length);
Vector3 pos = new Vector3(xrange, 0,zBound);
Instantiate(randomObjects[index],pos , randomObjects[index].transform.rotation);
}
}
将脚本绑定对象
先将脚本拖到一个对象上,然后点击检查器-覆盖-应用到全部,这样将使所有预制件都拥有该属性。

浙公网安备 33010602011771号