为何Roblox脚本输出始终为0?数值读取异常求助
问题原因
你在脚本初始化阶段就把I.Value、II.Value、III.Value的数值赋值给了变量I、II、III,这意味着这些变量只会存储脚本启动时的初始值(也就是0)。后续即使Explorer里这些数值对象的Value发生变化,变量也不会自动同步更新——因为你保存的是固定数值,而非对数值对象的引用。
解决方案
有两种可行的修复方式:
方式一:每次触发事件时读取最新值
将获取数值的代码移到Changed事件的回调函数内部,确保每次触发事件时都读取最新的Value:
script.Parent.Changed:Connect(function() if script.Parent.Value == true then script.Parent.Value = false script.Parent.Parent.Turn.Value = 1 -- 每次触发时获取最新数值 local I = script.Parent.Parent.I.Value local II = script.Parent.Parent.II.Value local III = script.Parent.Parent.III.Value print("cast") print(I + II + III) end end)
方式二:保存对象引用而非固定数值
如果需要在多个地方使用这些数值,可以只保存对数值对象的引用,每次访问时直接取Value属性:
-- 保存数值对象的引用,而非一次性读取的固定值 local IObj = script.Parent.Parent.I local IIObj = script.Parent.Parent.II local IIIObj = script.Parent.Parent.III script.Parent.Changed:Connect(function() if script.Parent.Value == true then script.Parent.Value = false script.Parent.Parent.Turn.Value = 1 print("cast") -- 访问对象的Value属性获取最新值 print(IObj.Value + IIObj.Value + IIIObj.Value) end end)
内容的提问来源于stack exchange,提问作者Tea Enjoyer
相关产品推荐
相关产品推荐

