Search Results for

    Show / Hide Table of Contents

    模块损毁时播放动画

    中文 | English

    在仓库根目录运行以下命令,用本机 Unity MCP 回放本页示例。

    python Docs/Manual/manual/tools/tutorials.py run lua-api2-module-trigger
    
    点击展开 MCP 操作点击收起 MCP 操作

    准备教学样例。${变量} 由配方提供。

    {
      "variables": {
        "script": "${fixture}/ModuleDestroyedTrigger.lua",
        "prefab": "${fixture}/Tutorial_ModuleDestroyedTrigger.prefab",
        "controller": "${fixture}/ModuleAnimator.controller"
      },
      "calls": [
        {
          "tool": "invoke",
          "arguments": {
            "path": "static:UnityEditor.AssetDatabase/CreateFolder",
            "args": [
              "${fixtureParent}",
              "${folder}"
            ]
          },
          "expect": {
            "contains": "(String)"
          }
        }
      ]
    }
    

    用这段脚本在弹药架或发动机等内部模块损毁时播放演示动画,例如打开盖板,或播放发动机火焰。脚本在游戏发出模块事件时更新,可以省去逐帧读取模块血量。

    1. 配置 Animator 并绑定脚本

    1. 打开伤害模型的 Prefab Mode。把要播放动画的物体放在该预制体内,例如作为模块的子节点,给它添加 Animator 并绑定 Animator Controller。在 Animator → Parameters 用 + → Trigger 创建 Destroyed。为目标动画建状态并设置过渡条件 Destroyed。
    2. 将下方 Lua 脚本导入 Unity。在内部模块所在物体上添加 LuaBehaviorMono 并绑定脚本。
    3. 将有 Animator 的物体拖到 animator,填写 triggerName,字符和大小写需与控制器一致。保存预制体。

    脚本在 OnVehicleReady 获取模块,因为 OnStarted 时伤害模型可能仍未装配。如果测试时没有触发,先核对脚本是否与内部模块挂在同一节点,再检查 animator 引用。

    Behavior()
    Property = {
        animator = { type = "object", value = nil },
        triggerName = { type = "string", value = "Destroyed" },
    }
    
    local ModuleDestroyedTrigger = class("ModuleDestroyedTrigger")
    
    function ModuleDestroyedTrigger:OnVehicleReady(vehicle)
        local module = InternalModuleAPI.GetInternalModule(self.gameObject)
        if module == nil or self.animator == nil then
            return
        end
        local animator = ComponentAPI.GetNativeComponent(self.animator, "Animator")
        if animator == nil then
            return
        end
        local wasDestroyed = InternalModuleAPI.IsDestroyed(module)
        InternalModuleAPI.OnStateChanged(self.script, module, function()
            local destroyed = InternalModuleAPI.IsDestroyed(module)
            if destroyed and not wasDestroyed then
                animator:SetTrigger(self.triggerName)
            end
            wasDestroyed = destroyed
        end)
    end
    
    return ModuleDestroyedTrigger
    
    点击展开 MCP 操作点击收起 MCP 操作
    [
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:System.IO.File/Copy",
          "args": [
            "../../Docs/Manual/tutorials/lua-api2-module-trigger/example.lua",
            "${script}"
          ]
        },
        "expect": {
          "contains": "OK:"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:UnityEditor.AssetDatabase/ImportAsset",
          "args": [
            "${script}",
            "ForceSynchronousImport"
          ]
        },
        "expect": {
          "contains": "OK:"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local e, u = CS.UnityEditor, CS.UnityEngine\nlocal a = e.Animations\nlocal controller = a.AnimatorController.CreateAnimatorControllerAtPath(\"${controller}\")\ncontroller:AddParameter(\"Destroyed\", u.AnimatorControllerParameterType.Trigger)\nlocal machine = controller.layers[0].stateMachine\nlocal intact = machine:AddState(\"Intact\")\nlocal destroyed = machine:AddState(\"Destroyed\")\nmachine.defaultState = intact\nlocal transition = intact:AddTransition(destroyed)\ntransition.hasExitTime = false\ntransition:AddCondition(a.AnimatorConditionMode.If, 0, \"Destroyed\")\ne.EditorUtility.SetDirty(controller)\ne.AssetDatabase.SaveAssets()\nassert(controller.parameters[0].name == \"Destroyed\" and transition.conditions[0].parameter == \"Destroyed\")\nreturn \"Destroyed Animator trigger and transition configured\"\n",
            "manual-module-animator",
            "null"
          ]
        },
        "expect": {
          "contains": "Destroyed Animator trigger and transition configured"
        }
      },
      {
        "tool": "prefab_edit",
        "arguments": {
          "json": {
            "path": "${prefab}",
            "mode": "create",
            "component": "ShanghaiWindy.Core.Lua.LuaBehaviorMono",
            "children": [
              "ModuleAnimator"
            ],
            "references": [
              {
                "property": "luaBehavior",
                "asset": "${script}",
                "type": "ShanghaiWindy.Core.Lua.LuaBehaviorScript"
              },
              {
                "property": "instanceLuaProperty.objectProperties.Array.data[0].value",
                "child": "ModuleAnimator",
                "component": "UnityEngine.GameObject"
              }
            ],
            "values": {
              "instanceLuaProperty": {
                "objectProperties": [
                  {
                    "variableName": "animator"
                  }
                ],
                "stringProperties": [
                  {
                    "variableName": "triggerName",
                    "value": "Destroyed"
                  }
                ]
              }
            }
          }
        },
        "expect": {
          "equals": {
            "ok": true
          }
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "asset:${prefab}/LuaBehaviorMono/luaBehavior/name"
        },
        "expect": {
          "contains": "(String) ModuleDestroyedTrigger"
        }
      },
      {
        "tool": "prefab_edit",
        "arguments": {
          "json": {
            "path": "${prefab}",
            "mode": "update",
            "component": "UnityEngine.Animator",
            "child": "ModuleAnimator",
            "references": [
              {
                "property": "m_Controller",
                "asset": "${controller}",
                "type": "UnityEngine.RuntimeAnimatorController"
              }
            ]
          }
        },
        "expect": {
          "equals": {
            "ok": true
          }
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "asset:${prefab}/LuaBehaviorMono/instanceLuaProperty/objectProperties/0/value/name"
        },
        "expect": {
          "contains": "(String) ModuleAnimator"
        }
      }
    ]
    

    2. 验证状态和动画

    1. 在试车中让该模块从完好变为损毁。只有第一次进入损毁状态时应触发动画。修复后再损毁一次,应能再次触发。
    2. 如果你需要按状态切换不同动画,让 OnStateChanged 回调接收 (oldState, newState),结合 GetHitPointRatio(module) 判断血量比例。每次受伤都需要反馈时,可以另外订阅 OnDamaged,其回调参数是本次扣除的血量。
    3. 按示例把 self.script 作为订阅所有者。行为销毁时订阅自动解除。

    回放验证 xLua 的状态和触发次数。实际 Animator 状态过渡在游戏中检查。

    点击展开 MCP 操作点击收起 MCP 操作
    [
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local E = setmetatable({ Behavior = function() end, class = function() return {} end, print = function() end }, { __index = _G })\nlocal destroyed, notifications, callback = false, 0, nil\nlocal module = {}\nlocal animator = { SetTrigger = function(_, name) assert(name == \"Destroyed\"); notifications = notifications + 1 end }\nE.InternalModuleAPI = {\n    GetInternalModule = function(go) return go.module end,\n    IsDestroyed = function(m) return destroyed end,\n    OnStateChanged = function(owner, m, cb) assert(m == module); callback = cb end\n}\nE.ComponentAPI = { GetNativeComponent = function(target, name) assert(name == \"Animator\"); return target.component end }\n\nlocal B = assert(loadfile('../../Docs/Manual/tutorials/lua-api2-module-trigger/example.lua', 't', E))()\nlocal function instance(t) return setmetatable(t, { __index = B }) end\ninstance({ gameObject = {}, animator = {} }):OnVehicleReady({})\nassert(callback == nil)\ninstance({ gameObject = { module = module }, animator = {} }):OnVehicleReady({})\nassert(callback == nil)\ninstance({ gameObject = { module = module }, animator = { component = animator },\n           triggerName = \"Destroyed\", script = {} }):OnVehicleReady({})\ndestroyed = true\ncallback(\"Good\", \"Destroyed\")\ncallback(\"Destroyed\", \"Destroyed\")\nassert(notifications == 1)\ndestroyed = false\ncallback(\"Destroyed\", \"Good\")\ndestroyed = true\ncallback(\"Good\", \"Destroyed\")\nassert(notifications == 2)\nreturn \"Lua example passed\"\n",
            "manual-lua-api2-module-trigger",
            "null"
          ]
        },
        "expect": {
          "contains": "Lua example passed"
        }
      }
    ]
    
    In this article
    Back to top Panzer War Document