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

Godot 3.5.1中Tool脚本无法在编辑器更新ColorRect尺寸问题

Godot 3.5.1 Mono Tool脚本编辑器不更新血条UI的解决方法

这不是Godot的Bug,是C# Tool脚本在3.x版本中的特性问题,需要手动处理属性变更后的UI刷新,具体解决步骤如下:

  • 确保脚本正确标记Tool特性并使用可导出属性
    不要直接修改私有字段_maxHealth、_health,而是将它们封装为带[Export]特性的公共属性,在setter方法中触发血条更新逻辑:

    [Tool]
    public class HealthBar : ColorRect
    {
        private int _maxHealth = 100;
        private int _health = 100;
    
        [Export]
        public int MaxHealth
        {
            get => _maxHealth;
            set
            {
                _maxHealth = value;
                RefreshHealthBar();
            }
        }
    
        [Export]
        public int Health
        {
            get => _health;
            set
            {
                _health = Mathf.Clamp(value, 0, _maxHealth);
                RefreshHealthBar();
            }
        }
    
        private void RefreshHealthBar()
        {
            if (Parent == null) return;
            float healthRatio = (float)_health / _maxHealth;
            RectSize = new Vector2(Parent.RectSize.x * healthRatio, RectSize.y);
            QueueRedraw();
        }
    
        public override void _Ready()
        {
            RefreshHealthBar();
        }
    }
    
  • 关键注意点

    1. 编辑器中修改的是导出的公共属性,而非私有字段,这样才能触发setter里的刷新逻辑
    2. 在属性变更后调用QueueRedraw()强制编辑器更新UI显示
    3. 增加Parent == null的判断,避免编辑器中节点未完全初始化时出现错误
    4. 不要在_Process中添加if (!Engine.EditorHint) return;这类阻止编辑器执行的代码,除非你有特殊需求
  • 验证操作
    修改代码后,重新加载脚本,在编辑器中调整MaxHealth和Health参数,绿色血条的宽度会实时更新;运行场景时逻辑也会保持正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:15:27