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

Unity自定义MonoBehaviour中是否存在双常量随机范围内置类型?

Unity自定义MonoBehaviour中是否有双常量随机的内置类型?

Unity并没有提供开箱即用、直接满足需求的内置类型——也就是那种在Inspector面板显示为范围滑块,且读取时自动返回确定随机值的类型。不过有几个相关的内置工具可以参考:

1. 使用ParticleSystem.MinMaxFloat

虽然它属于粒子系统命名空间,但可以直接在自定义MonoBehaviour中使用,Inspector面板会自动显示为范围滑块。不过它只是存储最小值和最大值,需要手动调用方法获取随机值:

using UnityEngine;

public class RandomRangeTest : MonoBehaviour
{
    // Inspector中会显示为范围滑块
    public ParticleSystem.MinMaxFloat randomValueRange;

    void Update()
    {
        // 获取范围内的随机值
        float randomVal = randomValueRange.GetRandomValue();
        Debug.Log($"随机值:{randomVal}");
    }
}

2. 自定义Serializable类(更灵活)

如果觉得依赖粒子系统命名空间不舒服,可以自己写一个简单的可序列化类,配合Editor自定义属性Drawer实现Inspector的范围滑块显示,同时封装随机值获取逻辑:

核心类定义

using UnityEngine;

[Serializable]
public class FloatRandomRange
{
    public float min;
    public float max;

    // 封装获取随机值的方法
    public float GetRandom()
    {
        return Random.Range(min, max);
    }
}

Editor自定义Drawer(放在Editor文件夹下)

#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(FloatRandomRange))]
public class FloatRandomRangeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);
        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

        var minProp = property.FindPropertyRelative("min");
        var maxProp = property.FindPropertyRelative("max");

        float minVal = minProp.floatValue;
        float maxVal = maxProp.floatValue;

        // 显示MinMax滑块,可自定义允许的范围(这里是0到10)
        EditorGUI.MinMaxSlider(position, ref minVal, ref maxVal, 0f, 10f);

        minProp.floatValue = minVal;
        maxProp.floatValue = maxVal;

        EditorGUI.EndProperty();
    }
}
#endif

使用示例

public class CustomRangeTest : MonoBehaviour
{
    public FloatRandomRange myCustomRange;

    void Start()
    {
        Debug.Log($"自定义范围随机值:{myCustomRange.GetRandom()}");
    }
}

总结

没有完全符合需求的内置类型,但用ParticleSystem.MinMaxFloat可以快速实现Inspector的范围显示,自己写自定义类则更灵活且不依赖粒子系统模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:37:11