Search Results for

    Show / Hide Table of Contents

    Trigger an animation when a module is destroyed

    δΈ­ζ–‡ | English

    Run this command at the repository root to replay the examples through the local Unity MCP.

    python Docs/Manual/manual/tools/tutorials.py run lua-api2-module-trigger
    
    Click to expand MCP actionsClick to collapse MCP actions

    Prepare the teaching sample. The recipe provides ${variables}.

    {
      "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)"
          }
        }
      ]
    }
    

    Use this example to play an animation when an internal module such as the ammo rack or engine is destroyed. You could open a hatch or play an engine fire effect. The script responds to module events and avoids reading hit points every frame.

    1. Configure the Animator and attach the script

    1. Open the damage model in Prefab Mode. Put the object to animate inside that prefab, such as a child of the module. Add an Animator and assign an Animator Controller. In Animator β†’ Parameters, choose + β†’ Trigger and add Destroyed. Create the target animation state and set Destroyed as its transition condition.
    2. Import the Lua script below. Add LuaBehaviorMono to the object containing the internal module and assign the script.
    3. Drag the object with the Animator into animator. Set triggerName to the exact spelling and case used in the controller. Save the prefab.

    The script resolves the module in OnVehicleReady. In OnStarted, the damage model might still be assembling. If your test does not trigger the animation, check that the script and module share the same object and that animator is assigned.

    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
    
    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "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. Check state changes and animation

    1. In a test drive, take the module from intact to destroyed. The animation should run once when it enters the destroyed state. Repair it and destroy it again to check that the animation can repeat.
    2. To pick different animations by state, accept (oldState, newState) in the OnStateChanged callback and read GetHitPointRatio(module). For feedback on every damaging hit, subscribe to OnDamaged, whose callback receives the hit points lost.
    3. Pass self.script as the owner, as shown in the example. The game ends the subscription when that behaviour is destroyed.

    The xLua replay checks state transitions and trigger counts. Check the actual Animator transition in game.

    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "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