prowl-scenes
GitHub提供 Prowl 游戏引擎的脚本编写指南,涵盖组件生命周期、GameObject、场景及物理回调等核心概念,并说明与 Unity 的差异。
Trigger Scenarios
Install
npx skills add ProwlEngine/Prowl --skill prowl-scenes -g -y
SKILL.md
Frontmatter
{
"name": "prowl-scenes",
"description": "How to write Prowl game scripts. Use when writing or reviewing a Component, working with GameObjects, components, Transform, scenes, prefabs, input, time, physics callbacks, async code with GameTask, or editor only script code. Covers where Prowl differs from Unity."
}
Prowl scripting: scenes, GameObjects and components
Prowl looks like Unity but differs in many details. Check anything not listed here with Library/prowl command api --type <Name> before using it.
Scripts derive from Component. There is no MonoBehaviour class, and code written against one will not compile.
A correct component
using System;
using System.Threading;
using Prowl.Runtime;
using Prowl.Runtime.Resources;
using Prowl.Vector;
[RequireComponent(typeof(Rigidbody3D), typeof(BoxCollider))]
[AddComponentMenu("Game/Player Mover")]
public sealed class PlayerMover : Component
{
public float Speed = 5f; // public fields are saved and shown in the inspector
public PrefabAsset BulletPrefab; // assigned in the inspector or with the CLI
private Rigidbody3D _body; // no constructor, no engine calls in field initializers
public override void OnEnable() => _body = GetComponent<Rigidbody3D>();
public override void Start() => Blink();
public override void Update()
{
Float2 move = Input.GetWASD();
_body.LinearVelocity = new Float3(move.X * Speed, _body.LinearVelocity.Y, move.Y * Speed); // never move a dynamic body through its Transform
if (Input.GetKeyDown(KeyCode.Space) && BulletPrefab.IsValid())
GameObject.Instantiate(BulletPrefab, Transform.Position + Transform.Forward, Transform.Rotation);
}
public override void OnCollisionBegin(Collision collision)
{
Debug.Log($"{GameObject.Name} hit {collision.GameObject.Name}");
}
private async void Blink()
{
CancellationToken token = DestroyCancellationToken;
try
{
while (true)
{
await GameTask.Delay(1f, token);
Debug.Log("tick");
}
}
catch (OperationCanceledException) { }
}
}
Lifecycle
Lifecycle methods are virtual overrides: write public override void Update(). A method with the right name but no override is never called.
OnAddedToScene(), thenOnEnable()when the object enters an active sceneStart()once, before the firstFixedUpdateorUpdateFixedUpdate()(fixed steps),Update(),LateUpdate()every frameOnDisable(), thenOnRemovedFromScene()when it leavesOnDispose()when destroyed. This replaces Unity'sOnDestroy. Override it asprotected override void OnDispose()and callbase.OnDispose().- There is no
Awakeand noOnDestroy. UseOnEnableorStart, andOnDispose. OnValidate()runs after a field is changed in the inspector or with the CLIsetcommand.- Physics:
OnCollisionBegin/Stay/End(Collision).OnTriggerEnter/Stay/Exit(Rigidbody3D other)andOnCharacterEnter/Stay/Exit(CharacterController)fire only on a GameObject that has aTriggerVolumecomponent. Colliders have no trigger flag. See the prowl-physics skill. - Drawing helpers:
DrawGizmos(),DrawGizmosSelected(). Runtime UI:OnGui(Paper paper). - An exception in a callback is logged and the frame continues.
No constructors. Components are created before they are attached and before saved values are applied, so a constructor sees no GameObject and its values are overwritten. Analyzers flag constructors (PROWLCO001, PROWLCO002) and field initializers that call engine code (PROWLCO003, PROWLCO004). Do setup in OnEnable or Start.
Attributes: [RequireComponent(typeof(A), typeof(B))] (adds missing components automatically, and can be repeated), [DisallowMultipleComponent] (a second one of that type or a subclass is refused, AddComponent returns null), [AddComponentMenu("Path")], [ExecuteAlways] (run callbacks outside play mode), [ExecutionOrder(n)]. Inspector attributes include [HideInInspector], [Range], [Header], [Space], [Tooltip], [ReadOnly], [TextArea], [ShowIf], [Button] on methods.
GameObject
new GameObject("Name")is in no world until you callgo.MoveTo(world)or parent it under an object that is in one. Until then it never getsOnEnableor updates.world.Create("Name")makes a live object directly, andGameObject.Instantiate(...)spawns into the world for you.- Components:
AddComponent<T>(),GetComponent<T>(),TryGetComponent<T>(out var c),GetComponents<T>(),GetComponentInParent<T>(),GetComponentInChildren<T>()(both include the object itself by default),RemoveComponent(c).AddComponentreturns null if the component can not be created. - Hierarchy:
SetParent(parent, worldPositionStays = true), passnullto detach.Parent,Children,GetChildrenDeep(). Name(inside a component,Nameis the component's own name, useGameObject.Name),Tag,CompareTag(ignores case),Layer,Enabled,EnabledInHierarchy,Identifier(stable Guid).Find(name),FindGameObjectWithTag(tag)are instance methods that search that object's scene.go.Destroy()removes it at the end of the frame. Until thenIsValid()is still true and it keeps updating, so checkIsDestroyQueuedto treat it as gone, or callDispose()to tear it down now.Dispose()tears it down immediately. There is no staticDestroy(obj).- Spawning:
GameObject.Instantiate(prefab),(prefab, position, rotation),(prefab, parent), and the same overloads with aGameObjectto copy. With a position the transform is set beforeOnEnableruns.
Null checks
A destroyed engine object is still a live reference, so null checks miss it. Always use obj.IsValid() and obj.IsNotValid(). ?., ?[], ??, ??=, == null, != null, is null and is not null on any EngineObject (GameObject, components, assets, scenes) are compile errors (PROWLEO001, PROWLEO002, PROWLEO003). ReferenceEquals(obj, null) is the rare true null check.
Transform
Transform lives in namespace Prowl.Vector (with Float2, Float3, Quaternion). Reach it as Transform inside a component or go.Transform.
Position,LocalPosition,Rotation,LocalRotation,EulerAngles,LocalEulerAngles(degrees),LocalScale,LossyScale,Forward(+Z),Right,UpTranslate(delta)is in world space unless you pass a transform.Rotate(Float3 eulerDegrees, relativeToSelf = true),Rotate(Float3 axis, float degrees, relativeToSelf = true),RotateAround(point, axis, degrees),LookAt(target)TransformPoint,InverseTransformPoint,TransformDirection,SetPositionAndRotation,Find(path)Quaternion.AxisAngletakes radians. The Transform methods take degrees.
Scenes
Scene is in Prowl.Runtime.Resources. There is no SceneManager.
SceneInstance.Mainis the game world. Inside a component use its ownSceneproperty, elsewhereSceneInstance.Active, the world whose code is running.Sceneis the saved scene asset.- A component's
Scenethrows while it is in no world: on a detached object, a prefab asset, and inOnValidateandOnAfterDeserialize. CheckIsInWorldfirst there. - A world has sections:
Persistentfirst, then one per loaded scene.ActiveSectionis where new objects go and whose environment shows. - Queries:
world.Create(name),Roots,Objects,ObjectCount,Get<T>(),GetAll<T>(),FindObject(name),FindObjectByPath("A/B"),FindObjectWithTag(tag),FindObject(guid). level.Load()replaces the world's sections with the level,level.LoadAdditive()adds one,section.Unload()removes one. All apply at the end of the frame and return or take effect through aSceneLoadyou can await.go.Persistent = trueon a root keeps it, and what it owns, across loads (game worlds only).world.Pausedstops the world's updates, physics, animation and navigation.world.Clockis its time scale and time.SceneInstance.Main.Physicshas the raycasts (main thread only, see the prowl-physics skill).Environmentholds the sky material, ambient light and fog.
Time, input, logging
Time.DeltaTime,UnscaledDeltaTime,FixedDeltaTime,TimeScale,FrameCount(long),TimeSinceStartupInput.GetKey/GetKeyDown/GetKeyUp(KeyCode.W),GetMouseButton(0),MousePosition,MouseDelta,MouseWheelDelta,GetWASD(),LockCursor(),UnlockCursor(). Key names:AtoZ,Number0toNumber9,Space,Enter,Escape,ShiftLeft,ControlLeft,Up,F1. Check others withapi --type KeyCode.Input.MouseDelta.Yis positive when the mouse moves down, as in window coordinates. For mouse look, subtract it from the pitch.- Input actions: an
InputActionMap(an asset made from the Input Actions create menu, or built in code),Input.RegisterActionMap(map),Input.FindAction(name), thenReadValue<T>(),IsPressed(),WasPressedThisFrame(). Actions start disabled and read their default until you callmap.Enable(). Debug.Log,LogWarning,LogError,LogException, andLogOnce(id, message)for things that repeat every frame.Debug.DrawLine,DrawWireCube,DrawWireSpheredraw gizmos. If you also useSystem.Diagnostics, writeProwl.Runtime.Debug.
Async and threads
await GameTask.NextFrame(),Frames(n),Delay(seconds)(game time, stops while paused),DelayRealtime(seconds),WaitUntil(() => cond),WorkerThread(),MainThread(). All but the last two take an optionalCancellationToken.- Await inside a component resumes on the main thread.
- When play stops or scripts reload, pending continuations are dropped without running their
finally. PassDestroyCancellationTokenorGameTask.SessionTokenand catchOperationCanceledExceptionwhen you need to clean up. - Scene objects may only be touched on the main thread. Most writes throw off the main thread, but reads do not, so a wrong read from a worker fails silently.
- Never block with
.Result,.Wait()orGetAwaiter().GetResult()in a component (PROWLTH001). It deadlocks. - A live world never equals a scene asset:
GameObject.Scene == levelis a compile error (PROWLSC001). CompareGameObject.Scene.Source == level.
Layers, tags and audio defaults
LayerMaskdefaults to everything, not nothing. Build masks from layer names withLayerMask.NameToLayer.- Setting
go.Layerorgo.Tagto a name that is not defined silently stores -1 instead of failing. Define tags and layers first (see the eval recipe in the prowl-cli skill). AudioSourcedefaults to 3D (Spatial) with aMaxDistanceof 10 and linear falloff, so a sound more than 10 units away is silent. A camera does not come with anAudioListener, add one to the player camera.
Find any other built in component with api --search.
Editor only code
- Scripts in any folder named
Editorcompile into the editor only assembly and are never shipped. - Wrap editor code elsewhere in
#if PROWL_EDITOR. The editor compiles every script withPROWL_EDITORdefined, so a missing guard only shows up in a build. - Without
[ExecuteAlways], gameplay callbacks only run in play mode.
Version History
- f68efb0 Current 2026-11-21 16:09


