Search Results for

    Show / Hide Table of Contents

    Lua API 2 overview

    中文 | 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-overview
    

    API 2 adds a vehicle assembly callback, managed event subscriptions, and interfaces for querying battles, radars, weapons, and vehicle state. If this is your first script, follow Lua Hello World to import and attach a script, then attach the example below to a test vehicle.

    1. Check the version and wait for vehicle assembly

    Older clients may leave GAME_API_VERSION unset. Check (GAME_API_VERSION or 1) >= 2 before calling API 2 methods. On a current client, opening this vehicle in the garage should log Ready once. Entering a battle creates a fresh instance and logs it again.

    Behavior()
    Property = {}
    
    local MyBehavior = class("MyBehavior")
    
    function MyBehavior:OnStarted()
      self.supportsAPI2 = (GAME_API_VERSION or 1) >= 2
      if not self.supportsAPI2 then
        print("[MyBehavior] This mod needs API 2")
      end
    end
    
    function MyBehavior:OnVehicleReady(vehicle)
      if not self.supportsAPI2 then return end
      self.vehicle = vehicle
      print("[MyBehavior] Ready: " .. VehicleAPI.GetDisplayName(vehicle))
      if VehicleAPI.IsGarage(vehicle) then
        self.script:SetUpdateEnabled(false)
        return
      end
      self.script:SetUpdateInterval(0.2)
    end
    
    function MyBehavior:OnUpdated(dt)
      if not self.vehicle then return end
      -- dt is the time in seconds since the previous call. Run periodic battle logic here.
    end
    
    return MyBehavior
    
    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.GameAPI/GetApiVersion",
          "args": []
        },
        "expect": {
          "contains": "(Int32) 2"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local function api2(v) return (v or 1) >= 2 end\nassert(not api2(nil) and not api2(1) and api2(2) and api2(3))\nassert(CS.ShanghaiWindy.Core.API.GameAPI.GetApiVersion() == 2)\nreturn \"API version verified\"\n",
            "manual-api-version",
            "null"
          ]
        },
        "expect": {
          "contains": "API version verified"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local function verify(version, garage)\n  local GAME_API_VERSION = version\n  local function Behavior() end\n  local function class() return {} end\n  local function print() end\n  local vehicle = {}\n  local VehicleAPI = {\n    GetDisplayName = function(target) assert(target == vehicle); return \"Example\" end,\n    IsGarage = function() return garage end,\n  }\n  local seed = {interval = 0, enabled = true}\n  function seed:SetUpdateEnabled(enabled) self.enabled = enabled end\n  function seed:SetUpdateInterval(interval) self.interval = interval end\n  local object = (function()\nBehavior()\nProperty = {}\n\nlocal MyBehavior = class(\"MyBehavior\")\n\nfunction MyBehavior:OnStarted()\n  self.supportsAPI2 = (GAME_API_VERSION or 1) >= 2\n  if not self.supportsAPI2 then\n    print(\"[MyBehavior] This mod needs API 2\")\n  end\nend\n\nfunction MyBehavior:OnVehicleReady(vehicle)\n  if not self.supportsAPI2 then return end\n  self.vehicle = vehicle\n  print(\"[MyBehavior] Ready: \" .. VehicleAPI.GetDisplayName(vehicle))\n  if VehicleAPI.IsGarage(vehicle) then\n    self.script:SetUpdateEnabled(false)\n    return\n  end\n  self.script:SetUpdateInterval(0.2)\nend\n\nfunction MyBehavior:OnUpdated(dt)\n  if not self.vehicle then return end\n  -- dt is the time in seconds since the previous call. Run periodic battle logic here.\nend\n\nreturn MyBehavior\n  end)()\n  object.script = seed\n  object:OnStarted()\n  object:OnVehicleReady(vehicle)\n  object:OnUpdated(0.2)\n  assert(object.supportsAPI2 == ((version or 1) >= 2))\n  assert(seed.enabled == (not object.supportsAPI2 or not garage))\n  assert(seed.interval == ((object.supportsAPI2 and not garage) and 0.2 or 0))\nend\nverify(nil, false)\nverify(1, false)\nverify(2, true)\nverify(3, false)\n\nlocal vehicle, weapon, self = {}, {}, {script = {}}\nlocal ammo, callback = 7\nlocal WeaponAPI = {\n  GetWeapon = function(target, index) assert(target == vehicle and index == 0); return weapon end,\n  GetTotalAmmo = function(target) assert(target == weapon); return ammo end,\n  OnAmmoChanged = function(owner, target, fn)\n    assert(owner == self.script and target == weapon)\n    callback = fn\n    return {IsActive = true}\n  end,\n}\nlocal weapon = WeaponAPI.GetWeapon(vehicle, 0)\nif weapon then\n  self.ammo = WeaponAPI.GetTotalAmmo(weapon)\n  self.ammoSubscription = WeaponAPI.OnAmmoChanged(self.script, weapon, function()\n    self.ammo = WeaponAPI.GetTotalAmmo(weapon)\n  end)\nend\nassert(self.ammo == 7 and self.ammoSubscription.IsActive)\nammo = 6\ncallback()\nassert(self.ammo == 6)\nreturn \"Lifecycle and ammo examples verified with Lua stubs\"\n",
            "manual-api-overview-samples",
            "null"
          ]
        },
        "expect": {
          "contains": "Lifecycle and ammo examples verified with Lua stubs"
        }
      }
    ]
    

    2. Choose lifecycle callbacks and an update interval

    Callback When it runs
    OnStarted() The script instance starts. Its vehicle may still be assembling.
    OnVehicleReady(vehicle) Once after the owning vehicle is assembled, including in the garage. If the vehicle is already assembled when the script starts, this follows the startup routine. Standalone map and effect behaviours have no owning vehicle.
    OnUpdated(dt) Once per frame by default, or at the configured interval. dt is the accumulated time in seconds since the previous call.
    OnVehicleDestroyed(vehicle) The owning vehicle is killed. Use it for a destruction animation or cleanup.
    OnDestroyed() The behaviour instance is destroyed. Release resources managed by the script here. The game disposes of subscriptions owned by this behaviour afterward.

    Tank, turret, and tank weapon behaviours configured in vehicle data receive self.vehicle before OnStarted. Turret behaviours also receive self.turretController, tank weapon behaviours receive self.tankFire, and aircraft weapon behaviours receive self.flightFire. See vehicle initialization timing.

    Method Use
    self.script:GetVehicle() Gets and caches the owning tank, aircraft, or infantry unit. Returns nil for behaviours with no owning vehicle.
    self.script:SetUpdateInterval(seconds) Spreads out calls to OnUpdated. Pass 0 to run on every frame again.
    self.script:SetUpdateEnabled(false) Stops OnUpdated while keeping event callbacks and OnGUI available. Pass true to resume.

    3. Subscribe to state changes

    Get a weapon in OnVehicleReady and subscribe to its ammo updates. Read ammo once for the initial display, then refresh it on OnAmmoChanged. Add the code below to the battle branch in the first example and draw self.ammo in OnGUI.

    local weapon = WeaponAPI.GetWeapon(vehicle, 0)
    if weapon then
      self.ammo = WeaponAPI.GetTotalAmmo(weapon)
      self.ammoSubscription = WeaponAPI.OnAmmoChanged(self.script, weapon, function()
        self.ammo = WeaponAPI.GetTotalAmmo(weapon)
      end)
    end
    
    • self.script owns the subscription. Destroying the behaviour or removing an associated target vehicle ends it.
    • To stop early, check that the subscription object exists and call sub:Dispose(). Repeat calls are safe. sub.IsActive tells you whether the subscription is still registered.
    • A game mode or library script can pass nil as the owner. Subscriptions with a target follow the target's lifetime. Subscriptions with neither an owner nor a target end when the game mode exits.
    • The game stops invoking a subscription callback after 10 consecutive errors. Check the event name and script context in the game log to locate the error.

    4. Find the API and handle return values

    Class Purpose and common methods
    VehicleAPI Vehicle identity, state, queries, and events. GetContext, IsGarage, IsLocalPlayer, IsBot, IsRemote, IsAlive, GetTeam, IsEnemy, GetDisplayName, GetGuid, GetVelocity, GetSpeedKmh, GetAimPoint, CreateQuery, OnVehicleSpawned, OnVehicleKilled.
    RadarAPI Ground and airborne radars. TryGetRadar, IsActive, GetWorkMode, GetScanAzimuth, GetContactCount, GetContact, GetContactWorldAzimuth, GetLockedTarget, TryLock, Unlock, OnLockChanged, OnThreat.
    WeaponAPI Weapons, ammo, reloads, lead, and events. GetWeaponCount, GetWeapon, GetAmmo, GetTotalAmmo, IsReloaded, GetReloadProgress, GetReloadTime, GetMuzzle, GetShellSpeed, PredictLead, OnFired, OnAmmoChanged, OnReloaded, OnHit, OnKill.
    TankAPI Turret and engine. GetTurretCount, GetTurretTransform, GetGunTransform, GetEngineState.
    FlightAPI Flight state and landing gear. IsOnGround, IsGearDown, GetAirspeedKmh, GetAltitude, GetThrottle, IsEngineRunning, OnGearChanged.
    InternalModuleAPI Internal modules. GetInternalModule, IsDestroyed, GetHitPointRatio, OnStateChanged, OnDamaged, OnRepaired.
    CameraAPI Player camera. GetCameraMode, IsZoomed, GetLockTarget.
    TransformAPI Model nodes. FindDeep, FindAllDeep.
    BuffAPI Create a buff with an editable value using CreateValueBuff.
    TimeAPI Check the pause state with IsPaused.

    Find the signatures in ShanghaiWindy.Core.API or use the SDK hints in VS Code after setting up EmmyLua. C# arrays and contact indices start at zero. For methods with out values such as TryGetRadar or GetContact, first check the boolean result in Lua. Handle missing results according to each signature, such as nil, false, or 0. Distances are generally in metres and angles in degrees. Check the method's speed units. For example, GetSpeedKmh returns kilometres per hour.

    Online battle queries filter enemy vehicles by team visibility. Radar contacts are subject to detection. To control a radar, use the vehicle currently controlled by the player and check the result of methods such as TryLock.

    Click to expand MCP actionsClick to collapse MCP actions
    [
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.WeaponAPI"
        },
        "expect": {
          "contains": "OnAmmoChanged"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.VehicleAPI"
        },
        "expect": {
          "contains": "CreateQuery"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.RadarAPI"
        },
        "expect": {
          "contains": "GetContactWorldAzimuth"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.GameAPI"
        },
        "expect": {
          "contains": "GetApiVersion"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.TankAPI"
        },
        "expect": {
          "contains": "GetEngineState"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.FlightAPI"
        },
        "expect": {
          "contains": "OnGearChanged"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.InternalModuleAPI"
        },
        "expect": {
          "contains": "OnStateChanged"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.CameraAPI"
        },
        "expect": {
          "contains": "GetCameraMode"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.TransformAPI"
        },
        "expect": {
          "contains": "FindAllDeep"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.BuffAPI"
        },
        "expect": {
          "contains": "CreateValueBuff"
        }
      },
      {
        "tool": "inspect",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.API.TimeAPI"
        },
        "expect": {
          "contains": "IsPaused"
        }
      },
      {
        "tool": "invoke",
        "arguments": {
          "path": "static:ShanghaiWindy.Core.AssetBundleManager/LuaEnv/DoString",
          "args": [
            "local api = CS.ShanghaiWindy.Core.API\nlocal query = api.VehicleAPI.CreateQuery()\nassert(query:Run(nil) == 0 and query.Count == 0 and query:Get(0) == nil and query:GetDistance(0) == 0)\nassert(api.WeaponAPI.GetWeapon(nil, 0) == nil and api.WeaponAPI.GetTotalAmmo(nil) == 0)\nreturn \"API 2 query and weapon fallbacks verified\"\n",
            "manual-api-query-fallbacks",
            "null"
          ]
        },
        "expect": {
          "contains": "API 2 query and weapon fallbacks verified"
        }
      }
    ]
    

    5. Migrate older scripts

    Create the battle query and cache model nodes in OnVehicleReady. At each update, call query:Run(vehicle) and read results by index with query:Get(index). Run initialization methods such as CreateQuery and FindAllDeep when you build or rebuild the cache. If a node is missing, check the model's name and hierarchy. Subscribe to ammo, reload, module, landing gear, and radar lock changes. Draw the cached result in OnGUI and use SetUpdateInterval for other periodic checks.

    Older approach Current API
    Scanning for vehicles with GetObjectsInWorld("Rigidbody"), FindObjectsOfType, or Identity.GlobalTeamList Reuse VehicleAPI.CreateQuery(). Use RadarAPI for radar contacts. The old GlobalTeamList can omit remote players online.
    Using RaycastAll for ground clutter and calculating elevation limits manually Configure the radar in groundAARadarData and read detections with RadarAPI.GetContact.
    Comparing InstanceNetType as text, reading GarageManager.inGarage, or comparing with GetPlayerVehicle() VehicleAPI.IsGarage, IsLocalPlayer, IsBot, and IsRemote.
    Time.timeScale < 0.01 TimeAPI.IsPaused().
    Retrying TryGetTankInitSystem in OnUpdated Initialize once in OnVehicleReady(vehicle).
    Recursing through GetChild to find TurretTransform, GunTransform, or FFPoint TankAPI.GetTurretTransform, GetGunTransform, and WeaponAPI.GetMuzzle. For arbitrary nodes, use TransformAPI.FindDeep.
    Reading bulletCountList or simpleReloadNowTime, or reflecting private fields WeaponAPI.GetAmmo, GetReloadProgress, and GetReloadTime.
    Counting shots manually WeaponAPI.OnAmmoChanged and GetTotalAmmo.
    Reflecting module hit points every frame InternalModuleAPI.OnStateChanged.
    Guessing field names such as curRPM and engineRPM TankAPI.GetEngineState.
    Checking WheelCollider.isGrounded and interpreting landing gear node names FlightAPI.IsOnGround, IsGearDown, and OnGearChanged.
    Writing a drag-aware lead solver WeaponAPI.PredictLead.
    Replacing a buff every frame with RemoveBuff and a new buff BuffAPI.CreateValueBuff, then SetValue.
    Deduplicating frame callbacks with Time.frameCount SetUpdateInterval and the elapsed time from OnUpdated(dt).

    Examples

    • Missile rack
    • Charged shot
    • Radar display
    • Aircraft warning
    • Module animation trigger
    • Engine RPM and landing gear
    In this article
    Back to top Panzer War Document