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

Roblox大亨开发报错:attempt to index nil with 'Value'求助

修复Roblox大亨游戏脚本报错:attempt to index nil with 'Value'

报错原因分析

第5行的报错指向两种可能性:

  • values.MoneyValue为nil:要么script.Parent.Parent.Parent.Parent.Values的层级路径错误,要么Values文件夹里没有名为MoneyValue的数值类型对象(IntValue/NumberValue)
  • hit:FindFirstChild("CashValue")为nil:碰撞到的DropperPart里没有CashValue对象,或者对象名称拼写错误(Roblox对名称大小写敏感)

分步修复方案

1. 替换不可靠的层级路径

多层Parent调用极易因为对象层级调整失效,改用按对象名称向上查找的方式定位Tycoon根节点:

-- 替换原脚本第一行的values定义
local tycoon = script.Parent:FindFirstAncestor("Tycoon")
local values = tycoon and tycoon:FindFirstChild("Values")
local moneyValue = values and values:FindFirstChild("MoneyValue")

只要Tycoon对象的名称不变,无论中间层级怎么调整,都能稳定找到目标。

2. 增加对象存在性判断

在访问Value属性前,先确认对象是否存在,避免nil索引报错:

script.Parent.Touched:Connect(function(hit)
    if hit.Name == "DropperPart" and hit:IsA("BasePart") then
        -- 先确保MoneyValue有效再执行后续逻辑
        if not moneyValue then return end
        
        local cashValue = hit:FindFirstChild("CashValue")
        -- 同时检查CashValue是否存在且为数值类型
        if cashValue and cashValue:IsA("NumberValue") then
            moneyValue.Value += cashValue.Value
            hit:Destroy()
        end
    end
end)

3. 手动排查验证步骤

  • 打开Roblox Studio,检查Tycoon/Values文件夹下是否确实存在MoneyValue,名称拼写完全一致
  • 检查生成DropperPart的脚本,确认是否正确给零件添加了CashValue对象,且对象类型为NumberValue/IntValue
  • 可以添加调试打印语句,定位哪一步找不到对象:
print("找到的Tycoon对象:", tycoon)
print("找到的Values文件夹:", values)
print("找到的MoneyValue:", moneyValue)

运行游戏后查看输出窗口,就能明确是哪一步出现了问题。

完整修复后脚本

local tycoon = script.Parent:FindFirstAncestor("Tycoon")
local values = tycoon and tycoon:FindFirstChild("Values")
local moneyValue = values and values:FindFirstChild("MoneyValue")

script.Parent.Touched:Connect(function(hit)
    if hit.Name == "DropperPart" and hit:IsA("BasePart") then
        if not moneyValue then return end
        
        local cashValue = hit:FindFirstChild("CashValue")
        if cashValue and cashValue:IsA("NumberValue") then
            moneyValue.Value += cashValue.Value
            hit:Destroy()
        end
    end
end)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:37:12