Godot中GDScript调用set_size报错:无法将float转为Vector2
解决Godot中ColorRect.set_size()的类型错误问题
错误原因
报错Invalid type in function 'set_size' in base 'ColorRect'. Cannot convert argument 1 from float to Vector2的核心问题是:
Godot 4的Control.set_size()方法仅接受单个Vector2类型参数,你传入了两个独立的float数值(x和y),导致类型不匹配。
修正代码
将报错的set_size调用改为传入Vector2对象即可,推荐直接使用属性赋值的方式(更符合Godot 4的惯用写法):
extends Area2D # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta: float) -> void: var offset = 8 var target_size = Vector2( $ColorPicker.size.x + offset * 2, $ColorPicker.size.y + offset * 2 ) # 两种写法二选一,推荐属性赋值 $ColorRect.size = target_size # $ColorRect.set_size(target_size)
性能优化建议
如果不需要每帧强制更新,更高效的做法是监听ColorPicker的尺寸变化信号,只有当尺寸实际改变时才更新ColorRect:
extends Area2D func _ready() -> void: # 连接尺寸变化信号到回调 $ColorPicker.size_changed.connect(_on_color_picker_size_changed) # 初始化一次尺寸 _update_color_rect_size() func _on_color_picker_size_changed() -> void: _update_color_rect_size() func _update_color_rect_size() -> void: var offset = 8 $ColorRect.size = Vector2( $ColorPicker.size.x + offset * 2, $ColorPicker.size.y + offset * 2 )
验证结果
修改后运行,ColorRect会正确跟随ColorPicker的尺寸变化,同时不会再触发类型错误。
内容的提问来源于stack exchange,提问作者harry mckay
相关产品推荐
相关产品推荐

