如何使用Transform数组随机选取点位实例化GameObject?
Unity 钥匙随机生成点功能实现
你原有代码报错的核心原因:
- C# 原生数组没有内置
GetRandom()方法,无法直接调用 - 数组元素访问需要使用方括号
[],不能用圆括号(),且需要先拿到Transform元素后才能访问position属性
可直接运行的完整代码
public GameObject theKeyItself; public Transform[] spawnPoints; void Start() { ChooseSpawnPoint(); } void ChooseSpawnPoint() { // 前置校验,避免未配置参数时触发空引用报错 if (spawnPoints == null || spawnPoints.Length == 0) { Debug.LogError("请先在Inspector面板配置钥匙生成点位数组"); return; } if (theKeyItself == null) { Debug.LogError("请先在Inspector面板配置钥匙预制体"); return; } // 生成随机数组索引:int版本Random.Range返回值为[min, max),即*包含最小值、不包含最大值*,不会出现索引越界 int randomIndex = Random.Range(0, spawnPoints.Length); Transform selectedPoint = spawnPoints[randomIndex]; // 在选中点位实例化钥匙,默认使用生成点的旋转值 Instantiate(theKeyItself, selectedPoint.position, selectedPoint.rotation); }
使用说明
- 脚本挂载到场景内任意活跃GameObject上
- 在Inspector面板将钥匙预制体拖拽赋值给
theKeyItself字段,将所有预设的生成点Transform对象拖拽添加到spawnPoints数组中 - 如果不需要钥匙继承生成点的旋转角度,将
Instantiate的第三个参数替换为Quaternion.identity即可,生成的钥匙会保持默认朝向 - 如果需要每次开局钥匙位置都重新随机,把
ChooseSpawnPoint()的调用放到对应的游戏初始化逻辑里即可
内容的提问来源于stack exchange,提问作者Bonnie49er1
相关产品推荐
相关产品推荐

