You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何随机选择游戏对象?如何随机生成不同尺寸平台?

解答:Unity随机选择游戏对象与生成不同尺寸平台

一、随机选择不同的游戏对象

要随机挑选游戏对象,最实用的方法是把候选对象放进数组,通过随机索引获取目标元素:

  • 先在脚本里定义一个公共数组,用来存放你的平台预制体(之后可以在Inspector面板里把不同预制体拖进去):
    public GameObject[] platformPrefabs;
    
  • 接着用Random.Range()生成合法的随机索引,注意int类型的Random.Range是左闭右开区间,所以第二个参数直接用数组长度就行:
    int randomIndex = UnityEngine.Random.Range(0, platformPrefabs.Length);
    GameObject pickedPlatform = platformPrefabs[randomIndex];
    
  • 额外提醒:使用前最好判断数组是否为空,避免出现空引用错误:
    if (platformPrefabs != null && platformPrefabs.Length > 0) {
        // 执行随机选择逻辑
    }
    

二、随机生成不同尺寸的平台

这里有两种实现思路,你可以根据需求选:

方式1:用不同尺寸的预制体随机切换

如果你已经做好了各种尺寸的平台预制体,直接结合上面的随机选择逻辑就行——每个预制体自带固定尺寸,随机选中后直接实例化即可。

方式2:动态调整单个预制体的尺寸

如果想基于同一个基础预制体灵活改尺寸,可以在实例化后修改它的缩放,同时记得同步调整碰撞体(比如BoxCollider)的大小,不然会出现碰撞检测异常:

// 先实例化选中的平台
GameObject newPlatform = Instantiate(pickedPlatform, transform.position, transform.rotation);

// 随机生成宽高参数
float randomWidth = UnityEngine.Random.Range(minWidth, maxWidth);
float randomHeight = UnityEngine.Random.Range(minHeight, maxHeight);

// 修改平台的缩放
newPlatform.transform.localScale = new Vector3(randomWidth, randomHeight, newPlatform.transform.localScale.z);

// 如果平台带有BoxCollider,同步调整碰撞体大小
BoxCollider collider = newPlatform.GetComponent<BoxCollider>();
if (collider != null) {
    collider.size = new Vector3(randomWidth, randomHeight, collider.size.z);
    // 要是需要调整碰撞体中心,也可以修改collider.center
}

三、修正你当前代码里的问题

看你提供的代码,有两个明显的错误需要调整:

  1. Random.Range调用错误:thePlatforms[UnityEngine.Random.Range]缺少范围参数,必须传入索引的最小值和最大值;
  2. Random.Range参数顺序颠倒:Random.Range(platformHeightMax,platformHeightMin)会导致生成的高度和预期相反,应该把最小值放在前面;

修正后的完整代码示例:

public GameObject[] thePlatforms;
public Transform generationPoint;
public float platformWidth;
public float platformHeightMin, platformHeightMax;
public float distanceBetweenMin, distanceBetweenMax;

void Update () { 
    if (transform.position.x < generationPoint.position.x) { 
        // 修正高度范围的参数顺序
        float platformHeight = UnityEngine.Random.Range(platformHeightMin, platformHeightMax); 
        float distanceBetween = UnityEngine.Random.Range(distanceBetweenMin, distanceBetweenMax); 

        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, platformHeight, transform.position.z); 

        // 修正随机索引的生成逻辑,同时增加数组非空判断
        if (thePlatforms != null && thePlatforms.Length > 0) {
            int randomIndex = UnityEngine.Random.Range(0, thePlatforms.Length);
            Instantiate(thePlatforms[randomIndex], transform.position, transform.rotation); 
        }
    } 
}

内容的提问来源于stack exchange,提问作者Calw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:59:23