Native Scripting
Scripts in ThreadEngine are native C++ — you subclass ScriptableEntity, override lifecycle hooks, and the engine wires the instance to an entity at runtime. No reflection or managed runtime; one rebuild ships everything.
A script is a header
Content Browser ▸ right-click ▸ Code ▸ New Script generates a single
.h in your project's assets/scripts/ folder. There is no companion
.cpp to maintain: the editor generates one translation unit
(_ScriptRegistrations.cpp) that includes every script header it finds and registers
the class each one declares.
.cpp with a
REGISTER_SCRIPT in it keep working exactly as they are — the generator sees the
registration and leaves that class alone. You can mix both styles in one folder.// Player.h — the whole script
#pragma once
#include "scene/ScriptableEntity.h"
#include "scene/Components.h"
#include "core/Input.h"
namespace Thread {
class Player : public ScriptableEntity {
public:
void OnCreate() override {
// Called once when the entity first becomes live.
m_Speed = GetFieldFloat("Speed", m_Speed);
}
void OnUpdate(float ts) override {
// Called every runtime frame. `ts` is delta-time in seconds.
auto& cc = GetComponent<CharacterControllerComponent>();
float fx = Input::IsKeyPressed(Key::D) - Input::IsKeyPressed(Key::A);
float fz = Input::IsKeyPressed(Key::S) - Input::IsKeyPressed(Key::W);
cc.DesiredVelocity.x = fx * m_Speed;
cc.DesiredVelocity.z = fz * m_Speed;
// WasKeyPressed fires on the key-down EDGE; IsKeyPressed is true while held.
if (cc.IsGrounded && Input::WasKeyPressed(Key::Space))
cc.DesiredVelocity.y = 6.0f;
else
cc.DesiredVelocity.y = 0.0f;
}
void OnDestroy() override {} // entity removed or scene unloaded
private:
float m_Speed = 5.0f;
};
}
The class must be named after the file and derive from
ScriptableEntity (or SceneSystem) — that is how the generator knows what
to register. A header it cannot register says so by name in the Console, rather than leaving you
with a script that silently does nothing.
Wiring it to an entity
Add a Native Script component to the entity and pick your script (Add Component ▸ Scripting ▸ Native Script, or just type its name in the Add Component search). An entity can run several scripts — pick another one on the same card. When the scene enters Play, the runtime instantiates each registered type and binds it.
The lifecycle
| Hook | When | Typical use |
|---|---|---|
OnCreate() | First Play frame after the instance is bound to the entity. | Read fields, cache component references, seed RNG. |
OnUpdate(float ts) | Every runtime tick during Play. | Input handling, AI, movement, animation, audio cues. |
OnDestroy() | Entity destroyed or scene unloaded. | Release any external resources owned by the script. |
OnTriggerEnter/Exit(Entity) | After the physics step, main thread. | Pickups, zones — needs a TriggerComponent. |
OnCollisionEnter/Exit(Entity) | After the physics step, main thread. | Damage on impact, landing effects. |
OnSpawn() / OnDespawn() | Each time an EntityPool hands the entity out / parks it. | Per-life reset for pooled projectiles, loot, creatures. |
OnDamaged / OnDeath(const DamageInfo&) | When the entity's HealthComponent takes a blow / reaches zero. |
Flinch, flee, play a sound; drop loot, despawn. |
Scripts run only in Play. That covers construction as well as ticking:
in Edit mode a script instance is not created at all, so neither OnCreate nor
OnUpdate runs, however long the Game panel sits open. Edit-mode previews of the Game
viewport call OnUpdateRuntime with playing=false, which skips scripts,
physics and audio alike.
This is worth stating twice because for a while the engine did not honour it. Edit mode passed
ts = 0 and assumed a zero delta made a tick harmless — which is true only of logic that
reads the delta. Construction ignores it, and so does input, so OnCreate fired when a
scene loaded in the editor, a keypress while authoring ran gameplay code, and anything a
script changed landed in the scene you then saved. Fixed in 0.7.0; if you are on an older build,
that is the behaviour you are looking at.
One consequence to lean on: OnCreate now genuinely means “the game started”. Pressing
Stop destroys the instances, and pressing Play builds them again — so it fires once per Play, not
once per scene load.
Serialized fields
A script's member variables are not saved — the scene stores which script an
entity runs, and nothing else, so every member is default-constructed on load. To expose a value
that a designer can set per entity and that the scene file keeps, declare it. This is the engine's
equivalent of Unity's [SerializeField]; since there is no reflection, the script
states its own schema.
class Player : public ScriptableEntity {
public:
void DeclareFields(ScriptFields& f) override {
f.Float ("Speed", m_Speed, "Metres per second"); // the 3rd arg is a tooltip
f.Int ("Health", m_Health);
f.Bool ("CanFly", m_CanFly);
f.String("Title", m_Title);
f.Vec3f ("Offset", m_Offset);
}
void OnCreate() override {
// The fallback is the member's own default, so the value lives in ONE place
// even when the field was never authored in the inspector.
m_Speed = GetFieldFloat ("Speed", m_Speed);
m_Health = GetFieldInt ("Health", m_Health);
m_CanFly = GetFieldBool ("CanFly", m_CanFly);
m_Title = GetFieldString("Title", m_Title);
m_Offset = GetFieldVec3 ("Offset", m_Offset);
}
private:
float m_Speed = 5.0f;
int m_Health = 100;
bool m_CanFly = false;
std::string m_Title = "Hero";
Vec3 m_Offset { 0.0f, 1.0f, 0.0f };
};
Declaration order is the order the inspector draws them, so group related settings together. The values appear under FIELDS on the Native Script card, and are stored per entity in the scene file.
OnCreate — so do not touch
the scene, allocate, or start anything in it.When a field changes in code
- Changed type — the old value is still in every scene saved before the change. The getter refuses it and returns your fallback instead of reinterpreting the bytes, so you get your default rather than a wrong number. The inspector resets the stored value to the declared default the next time you look at it.
- Renamed or removed — the authored value is kept, not deleted. The inspector lists it under a warning with a ✕, so a rename never silently throws away somebody's work. Remove it once you are sure it is not coming back.
Reference fields
A field can point at another entity or at an asset. Both are filled in the inspector: drag the entity in from the Scene Hierarchy, or press ⊙ on the slot and pick it from a searchable list — which is also the only way when the entity you want sits in a collapsed subtree or off the top of a long hierarchy. ✕ clears the slot. Asset slots work the same way through the standard asset picker.
void DeclareFields(ScriptFields& f) override {
f.EntityRef("Door", "which door this lever opens");
f.AssetRef ("Icon", AssetType::Texture);
}
void OnUpdate(float ts) override {
if (Entity door = GetFieldEntity("Door")) {
door.GetComponent<TransformComponent>().Rotation.y += ts;
}
// GetFieldAsset returns a path ready for AssetManager; empty means unassigned.
}
An entity reference is stored as the target's id, not as a name and not as an internal handle — a handle does not survive a scene reload or Play/Stop, which rebuilds the registry from a snapshot. An asset reference is stored the same way every other asset slot in the editor stores one, so it survives the file being renamed or moved.
Both are resolved when you ask for them, not when the scene loads. That is
deliberate: at OnCreate time the target may not exist yet, because the scene is
still loading or its streamed cell has not arrived. Call the getter when you need the reference;
the lookup is a hash probe, so caching it yourself is only worth it in a hot loop. An unassigned
field, a destroyed target and one that was never in this scene all come back as an invalid
Entity, which is why the if (Entity e = ...) form above is the right
shape.
Accessing components
auto& tc = GetComponent<Thread::TransformComponent>(); // mutable ref
auto& ac = GetComponent<Thread::AudioComponent>();
ac.Volume = 0.3f; // applied immediately
Use HasComponent before
GetComponent when the presence isn't guaranteed — calling
GetComponent on a missing component asserts.
Talking to other entities
By reference field, when a designer should choose the target (see above). By id, when you already have one — Scene::FindByUUID is an indexed lookup, not a scan:
Thread::Entity target = GetScene()->FindByUUID(id);
if (target) { /* ... */ }
By name, when the target is "whoever is the player" rather than a specific object:
if (Thread::Entity player = GetScene()->FindByName("Player")) {
auto& ptc = player.GetComponent<Thread::TransformComponent>();
// ... use ptc ...
}
A linear scan, so keep it out of a hot loop — but note the sharper limit: names are not unique, so this finds some entity called that and cannot tell you it chose. When a duplicate would be a bug, ask for all of them and say so:
auto players = GetScene()->FindAllByName("Player");
if (players.size() != 1)
Thread::Logger::Warn("expected one Player, found " + std::to_string(players.size()));
Reading a name back is entity.GetName(), and SetName writes it. Both are
a wrapper over TagComponent::Tag; a rename changes nothing else about the entity, and in
particular does not change its id — which is exactly why a reference you need to keep is stored as an
id and not as a name.
What a script can reach
Gameplay scripts compile into their own module and link against the symbols the host
exports. Anything header-only — components, GetComponent<T>, math,
the field getters — always works. Of the engine's compiled classes, the ones marked for scripts
today are Input, Logger, the script registry,
Scene::FindByUUID, Scene::FindByName/FindAllByName and
Entity::GetName/SetName.
LNK2019: unresolved external symbol naming it —
not at runtime. SaveGame is the one people reach for first; it is currently
host-only.Common patterns
- Movement — drive CharacterControllerComponent::DesiredVelocity from input. Don't write directly to TransformComponent.Translation if a physics body owns the entity — Jolt will overwrite it next frame.
- Spawn projectiles — call scene->CreateEntity + AddComponent + AddImpulse.
- Audio cues — toggle
AudioComponent::AutoPlayor set a newClipPath; the runtime will (re)play. - Tunable numbers — a serialized field, not a constant. It costs one line and the designer stops needing you.
- State machines — keep state as private fields on the script class.
See also
ScriptableEntity reference · Scripts & IDE workflow · Scene Systems (for batch logic) · Input
Skrypty natywne
Skrypty w ThreadEngine to natywny C++ — dziedziczysz po ScriptableEntity, nadpisujesz zaczepy cyklu życia, a silnik w czasie działania łączy instancję z encją. Bez refleksji i bez zarządzanego runtime; jedna przebudowa wysyła wszystko.
Skrypt to nagłówek
Content Browser ▸ prawy klik ▸ Code ▸ New Script generuje jeden plik .h w
folderze assets/scripts/ projektu. Nie ma towarzyszącego .cpp do utrzymywania:
edytor generuje jedną jednostkę kompilacji (_ScriptRegistrations.cpp), która dołącza każdy
znaleziony nagłówek skryptu i rejestruje zadeklarowaną w nim klasę.
.cpp zawierającym REGISTER_SCRIPT
działają dalej bez zmian — generator widzi rejestrację i zostawia tę klasę w spokoju. W jednym folderze
możesz mieszać oba style.// Player.h — cały skrypt
#pragma once
#include "scene/ScriptableEntity.h"
#include "scene/Components.h"
#include "core/Input.h"
namespace Thread {
class Player : public ScriptableEntity {
public:
void OnCreate() override {
// Raz, gdy encja pierwszy raz ożywa.
m_Speed = GetFieldFloat("Speed", m_Speed);
}
void OnUpdate(float ts) override {
// Co klatkę gry. `ts` to czas klatki w sekundach.
auto& cc = GetComponent<CharacterControllerComponent>();
float fx = Input::IsKeyPressed(Key::D) - Input::IsKeyPressed(Key::A);
float fz = Input::IsKeyPressed(Key::S) - Input::IsKeyPressed(Key::W);
cc.DesiredVelocity.x = fx * m_Speed;
cc.DesiredVelocity.z = fz * m_Speed;
// WasKeyPressed reaguje na ZBOCZE wciśnięcia; IsKeyPressed jest true, dopóki trzymasz.
if (cc.IsGrounded && Input::WasKeyPressed(Key::Space))
cc.DesiredVelocity.y = 6.0f;
else
cc.DesiredVelocity.y = 0.0f;
}
void OnDestroy() override {} // encja usunięta albo scena wyładowana
private:
float m_Speed = 5.0f;
};
}
Klasa musi nazywać się jak plik i dziedziczyć po ScriptableEntity (albo
SceneSystem) — tak generator wie, co zarejestrować. Nagłówek, którego nie umie zarejestrować,
jest wymieniany z nazwy w konsoli, zamiast zostawiać cię ze skryptem, który po cichu nic nie robi.
Podpinanie do encji
Dodaj do encji komponent Native Script i wybierz skrypt (Add Component ▸ Scripting ▸ Native Script albo po prostu wpisz jego nazwę w wyszukiwarce Add Component). Encja może mieć kilka skryptów — wybierz kolejny na tej samej karcie. Gdy scena wchodzi w Play, runtime tworzy każdy zarejestrowany typ i go podpina.
Cykl życia
| Zaczep | Kiedy | Typowe użycie |
|---|---|---|
OnCreate() | Pierwsza klatka Play po podpięciu instancji do encji. | Odczyt pól, zapamiętanie referencji do komponentów, ziarno losowania. |
OnUpdate(float ts) | Każdy tick gry podczas Play. | Obsługa wejścia, AI, ruch, animacja, sygnały dźwiękowe. |
OnDestroy() | Encja zniszczona albo scena wyładowana. | Zwolnienie zewnętrznych zasobów skryptu. |
OnTriggerEnter/Exit(Entity) | Po kroku fizyki, w głównym wątku. | Podnoszenie przedmiotów, strefy — wymaga TriggerComponent. |
OnCollisionEnter/Exit(Entity) | Po kroku fizyki, w głównym wątku. | Obrażenia od uderzenia, efekty lądowania. |
OnSpawn() / OnDespawn() | Za każdym razem, gdy EntityPool wydaje / odkłada encję. | Reset na każde życie pocisków, łupu, stworzeń z puli. |
OnDamaged / OnDeath(const DamageInfo&) | Gdy HealthComponent encji dostaje cios / spada do zera. |
Wzdrygnięcie, ucieczka, dźwięk; upuszczenie łupu, despawn. |
Skrypty działają tylko w Play. Dotyczy to zarówno tworzenia, jak i tykania: w
trybie edycji instancja skryptu w ogóle nie powstaje, więc ani OnCreate, ani
OnUpdate się nie wykonują, choćby panel gry był otwarty bardzo długo. Podglądy viewportu gry
w trybie edycji wołają OnUpdateRuntime z playing=false, co pomija skrypty,
fizykę i dźwięk.
Warto to powiedzieć dwa razy, bo przez jakiś czas silnik tego nie przestrzegał. Tryb edycji
przekazywał ts = 0 i zakładał, że zerowa delta czyni tick nieszkodliwym — co jest prawdą
tylko dla logiki czytającej deltę. Tworzenie ją ignoruje, wejście też, więc OnCreate odpalał
się przy wczytaniu sceny w edytorze, wciśnięcie klawisza podczas tworzenia uruchamiało kod gry, a
wszystko, co skrypt zmienił, trafiało do sceny, którą potem zapisywałeś. Naprawione w 0.7.0; na
starszym buildzie widzisz właśnie to zachowanie.
Konsekwencja, na której można polegać: OnCreate naprawdę znaczy teraz „gra wystartowała”.
Stop niszczy instancje, Play buduje je od nowa — więc odpala raz na Play, a nie raz na wczytanie
sceny.
Pola serializowane
Zmienne skryptu nie są zapisywane — scena przechowuje, który skrypt uruchamia encja, i
nic więcej, więc każde pole po wczytaniu ma wartość domyślną. Żeby wystawić wartość, którą projektant
ustawi per encja i którą plik sceny zachowa, zadeklaruj ją. To odpowiednik [SerializeField]
z Unity; ponieważ nie ma refleksji, skrypt sam podaje swój schemat.
class Player : public ScriptableEntity {
public:
void DeclareFields(ScriptFields& f) override {
f.Float ("Speed", m_Speed, "Metres per second"); // 3. argument to podpowiedź
f.Int ("Health", m_Health);
f.Bool ("CanFly", m_CanFly);
f.String("Title", m_Title);
f.Vec3f ("Offset", m_Offset);
}
void OnCreate() override {
// Wartość zastępcza to domyślna wartość pola, więc wartość żyje w JEDNYM miejscu,
// nawet gdy pole nigdy nie zostało ustawione w inspektorze.
m_Speed = GetFieldFloat ("Speed", m_Speed);
m_Health = GetFieldInt ("Health", m_Health);
m_CanFly = GetFieldBool ("CanFly", m_CanFly);
m_Title = GetFieldString("Title", m_Title);
m_Offset = GetFieldVec3 ("Offset", m_Offset);
}
private:
float m_Speed = 5.0f;
int m_Health = 100;
bool m_CanFly = false;
std::string m_Title = "Hero";
Vec3 m_Offset { 0.0f, 1.0f, 0.0f };
};
Kolejność deklaracji to kolejność w inspektorze, więc grupuj powiązane ustawienia. Wartości pojawiają się pod FIELDS na karcie Native Script i są zapisywane per encja w pliku sceny.
OnCreate — więc nie dotykaj w nim sceny,
nie alokuj i niczego nie uruchamiaj.Gdy pole zmienia się w kodzie
- Zmiana typu — stara wartość wciąż jest w każdej scenie zapisanej przed zmianą. Getter ją odrzuca i zwraca twoją wartość zastępczą zamiast reinterpretować bajty, więc dostajesz wartość domyślną, a nie złą liczbę. Inspektor resetuje zapisaną wartość do zadeklarowanej domyślnej, gdy następnym razem na nią spojrzysz.
- Zmiana nazwy lub usunięcie — ustawiona wartość jest zachowywana, nie kasowana. Inspektor pokazuje ją pod ostrzeżeniem z ✕, więc zmiana nazwy nigdy po cichu nie wyrzuca czyjejś pracy. Usuń ją, gdy masz pewność, że nie wróci.
Pola-odwołania
Pole może wskazywać inną encję albo asset. Oba wypełniasz w inspektorze: przeciągnij encję ze Scene Hierarchy albo kliknij ⊙ na slocie i wybierz ją z listy z wyszukiwarką — to też jedyny sposób, gdy potrzebna encja siedzi w zwiniętym poddrzewie albo daleko w długiej hierarchii. ✕ czyści slot. Sloty assetów działają tak samo przez standardowy wybór assetu.
void DeclareFields(ScriptFields& f) override {
f.EntityRef("Door", "which door this lever opens");
f.AssetRef ("Icon", AssetType::Texture);
}
void OnUpdate(float ts) override {
if (Entity door = GetFieldEntity("Door")) {
door.GetComponent<TransformComponent>().Rotation.y += ts;
}
// GetFieldAsset zwraca ścieżkę gotową dla AssetManager; pusta = nieprzypisane.
}
Odwołanie do encji jest zapisywane jako id celu, nie jako nazwa i nie jako wewnętrzny uchwyt — uchwyt nie przetrwa przeładowania sceny ani Play/Stop, które odbudowują rejestr z migawki. Odwołanie do assetu jest zapisywane tak samo jak w każdym innym slocie assetu w edytorze, więc przetrwa zmianę nazwy lub przeniesienie pliku.
Oba rozwiązują się wtedy, gdy o nie prosisz, a nie przy wczytaniu sceny. To celowe: w
chwili OnCreate cel może jeszcze nie istnieć, bo scena się wczytuje albo jej strumieniowana
komórka nie dotarła. Wołaj getter, gdy potrzebujesz odwołania; wyszukiwanie to jedno sprawdzenie w
tablicy haszującej, więc własne buforowanie opłaca się tylko w gorącej pętli. Nieprzypisane pole,
zniszczony cel i cel, którego nigdy nie było w tej scenie, wracają jako nieważna Entity —
dlatego forma if (Entity e = ...) wyżej jest właściwa.
Dostęp do komponentów
auto& tc = GetComponent<Thread::TransformComponent>(); // modyfikowalna referencja
auto& ac = GetComponent<Thread::AudioComponent>();
ac.Volume = 0.3f; // działa od razu
Używaj HasComponent przed GetComponent, gdy
obecność nie jest pewna — GetComponent na brakującym komponencie kończy się asercją.
Rozmowa z innymi encjami
Przez pole-odwołanie, gdy cel ma wybrać projektant (zob. wyżej). Przez id, gdy już je masz — Scene::FindByUUID to wyszukiwanie po indeksie, nie przeglądanie:
Thread::Entity target = GetScene()->FindByUUID(id);
if (target) { /* ... */ }
Po nazwie, gdy cel to „ktokolwiek jest graczem”, a nie konkretny obiekt:
if (Thread::Entity player = GetScene()->FindByName("Player")) {
auto& ptc = player.GetComponent<Thread::TransformComponent>();
// ... użyj ptc ...
}
To przegląd liniowy, więc trzymaj go poza gorącą pętlą — ale ważniejsze ograniczenie: nazwy nie są unikalne, więc znajdziesz jakąś encję o tej nazwie, a wyszukiwanie nie powie, że wybierało. Gdy duplikat byłby błędem, poproś o wszystkie i to zgłoś:
auto players = GetScene()->FindAllByName("Player");
if (players.size() != 1)
Thread::Logger::Warn("expected one Player, found " + std::to_string(players.size()));
Nazwę odczytasz przez entity.GetName(), a zapiszesz przez SetName. Oba to
nakładka na TagComponent::Tag; zmiana nazwy niczego innego w encji nie zmienia, a zwłaszcza
nie zmienia id — i właśnie dlatego odwołanie, które masz zachować, zapisuje się jako id, a nie nazwę.
Do czego skrypt sięga
Skrypty gry kompilują się do własnego modułu i linkują z symbolami, które host eksportuje.
Wszystko, co jest tylko w nagłówkach — komponenty, GetComponent<T>, matematyka,
gettery pól — działa zawsze. Ze skompilowanych klas silnika dla skryptów oznaczone są dziś
Input, Logger, rejestr skryptów, Scene::FindByUUID,
Scene::FindByName/FindAllByName oraz Entity::GetName/SetName.
Narzędzia edytora mają własną powierzchnię — EditorAPI.
LNK2019: unresolved external symbol z jej nazwą — a
nie w czasie działania. SaveGame to pierwsza, po którą ludzie sięgają; na razie jest tylko po
stronie hosta.Typowe wzorce
- Ruch — steruj CharacterControllerComponent::DesiredVelocity z wejścia. Nie pisz bezpośrednio do TransformComponent.Translation, jeśli encja ma ciało fizyczne — Jolt nadpisze to w następnej klatce.
- Pociski — scene->CreateEntity + AddComponent + AddImpulse, albo EntityPool, gdy jest ich dużo.
- Sygnały dźwiękowe — przełącz
AudioComponent::AutoPlayalbo ustaw nowyClipPath; runtime odtworzy (ponownie). - Liczby do strojenia — pole serializowane, nie stała. Kosztuje jedną linijkę, a projektant przestaje cię potrzebować.
- Maszyny stanów — trzymaj stan w prywatnych polach klasy skryptu.
Zobacz też
Referencja ScriptableEntity · Skrypty i IDE · Systemy sceny (logika wsadowa) · Input