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

Unity随机树木生成器脚本如何实现int类型number值随机化

解决方案

  • 你需要在执行生成树逻辑、也就是调用PlaceTree()方法之前,给number变量赋值随机int值
  • Unity中生成随机int值用Random.Range(min, max)即可,注意int重载的规则是左闭右开:会返回大于等于min、小于max的整数,如果你想要包含max值,需要把入参的max设为max+1
  • 注意设置的随机范围下限不能小于0,否则number为负时for循环不会执行,不会生成任何树木
  • 因为你的number是public变量,Unity Inspector面板中设置的数值会默认覆盖代码中的赋值,所以一定要在运行时逻辑(Start/Awake方法)里赋值,才会覆盖Inspector的默认值

修改后完整代码

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

public class randomspawn : MonoBehaviour
{
    public GameObject tree;
    public int number;
    public int yaxis;
    // 可在Inspector面板自定义树木数量的随机上下限
    public int minTreeCount = 10;
    public int maxTreeCount = 100;

    void Start()
    {
        // 调用生成方法前先给number赋随机值
        // 此处maxTreeCount+1是为了让随机结果包含你设置的maxTreeCount数值
        number = Random.Range(minTreeCount, maxTreeCount + 1);
        PlaceTree();
    }
    void PlaceTree()
    {
        for (int i = 0; i < number; i++)
        {
            Instantiate(tree, GeneratedPosition(), Quaternion.identity);
        }
    }

    Vector3 GeneratedPosition()
    {
        int x, y, z;
        x = Random.Range(-1000, 1000);
        y = UnityEngine.Random.Range(-yaxis, yaxis);
        z = Random.Range(-1000, 1000);
        return new Vector3(x, y, z);
    }
}

如果不需要在Inspector调整范围,也可以直接把范围写死在方法里,比如number = Random.Range(20, 201);就代表随机生成20到200棵树。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 02:00:05