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

GLua脚本运行报错:尝试调用字段'PlayFile'(nil值)

GLua音效脚本报错修复方案

问题根源

报错[ERROR] lua/test.lua:4: attempt to call field 'PlayFile' (a nil value)的核心原因:

  • 混淆了sound.Play和sound.PlayFile的用法,sound.Play不支持回调参数,却传入了类似sound.PlayFile的调用结构;
  • sound.PlayFile是客户端专属API,若脚本在服务器端运行,会直接触发该错误(服务器环境无此函数)。

修复代码

根据运行场景选择对应脚本:

客户端脚本(推荐,音效播放应在客户端处理)

将脚本放在lua/autorun/client/目录下,使用正确的sound.PlayFile调用:

local AudioSource = nil

hook.Add("EntityTakeDamage", "UniqueNameForYourScript", function(ent)
    -- 仅响应本地玩家受伤害事件,避免全局触发
    if ent ~= LocalPlayer() then return end

    sound.PlayFile("sound/hurt1.mp3", "", function(source, err, errname)
        if IsValid(source) then
            AudioSource = source
            source:Play()
        else
            print("Error playing sound: " .. errname)
        end
    end)

    print("OW!")
end)

服务器端脚本(不推荐,同步效果差)

若必须在服务器端执行,使用sound.Play(无需回调,需指定播放位置):

hook.Add("EntityTakeDamage", "UniqueNameForYourScript", function(ent)
    -- 在受伤害实体的位置播放预加载音效
    sound.Play("hurt1", ent:GetPos(), 75, 100, 1)
    print("OW!")
end)

注意:服务器端使用sound.Play时,音频文件需通过resource.AddSingleFile("sound/hurt1.mp3")预加载,且调用时路径无需带后缀。

额外提示

  • 确保音频文件hurt1.mp3放在garrysmod/sound/目录下,路径无误;
  • 客户端脚本不要放在服务器端目录运行,否则会再次触发API不存在错误;
  • 限制仅本地玩家受伤害时播放音效,避免不必要的资源消耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:12:38