ScriptableEntity class in Thread
Base class your gameplay scripts inherit from. Equivalent to Unity's
MonoBehaviour: subclass it, override the lifecycle hooks, then attach it to an entity
with the Native Script component. Registration is generated for you — a script is
a header named after its class; see Native Scripting.
Protected lifecycle methods override
| OnCreate() | void | Called once after the script instance is constructed and attached to its Entity. |
| OnUpdate(float ts) | void | Called every simulation tick during Play. ts is delta-time in seconds. |
| OnDestroy() | void | Called when the entity (or scene) is destroyed. |
| OnSpawn() | void | Every time the entity comes (back) into the world from an EntityPool — including the first. Per-life setup belongs here. |
| OnDespawn() | void | Just before the pool parks the entity. It is still live: drop loot, start an effect. |
| OnTriggerEnter(Entity other) | void | Something entered this entity's trigger volume. |
| OnTriggerExit(Entity other) | void | Something left the trigger volume. |
| OnCollisionEnter(Entity other) | void | A physics contact began with another body. |
| OnCollisionExit(Entity other) | void | A physics contact ended. |
| OnDamaged(const DamageInfo&) | void | This entity's HealthComponent took damage. |
| OnDeath(const DamageInfo&) | void | Its health reached zero. |
Public methods
| GetComponent<T>() | T& | Reference to component T on this entity. Asserts if missing. |
| GetScene() | Scene* | Currently-active Scene (static — usable anywhere during a tick). |
| ChangeScene(path) | void | Requests a scene switch on the next frame boundary. |
Multiplayer
All give the single-player answer when there is no session. See Multiplayer (co-op).
| IsAuthority() | bool | This machine decides the world (host, or alone). Gate damage, loot, spawning. |
| IsLocallyOwned() | bool | This machine simulates this entity. Gate keyboard input. |
| IsHost() / IsClient() / IsOnline() | bool | The session. |
| LocalPlayer() / LocalPeer() | Entity / PeerId | This machine's character and player id. |
| CallHost / CallAll / CallOwner(rpc, args...) | void | Run one of this script's RPCs on another machine. |
| DeclareRpcs(RpcTable&) override | void | r.On("Name", &MyScript::Method), Method takes RpcCall&. |
| DeclareReplicated(Replicated&) override | void | r.Float("Health", m_Health): values the host keeps in step on every client. |
Serialized fields override
Members of a script are never saved. To expose a value the inspector can set per entity and the
scene file keeps, declare it — the engine's [SerializeField].
| DeclareFields(ScriptFields&) | void | Override to state this script's schema. Called by the EDITOR on a throwaway instance, without ever running OnCreate — so it must be a pure description. |
Declaring, on the ScriptFields& you are handed:
| Float(name, def, tip="") | void | Drag-float row. |
| Int(name, def, tip="") | void | Drag-int row. |
| Bool(name, def, tip="") | void | Checkbox. |
| String(name, def, tip="") | void | Text box. |
| Vec3f(name, def, tip="") | void | Three-component drag row. |
| EntityRef(name, tip="") | void | Slot another entity is dragged onto. Stores the target's id. |
| AssetRef(name, AssetType, tip="") | void | Asset picker filtered to that type. |
Reading, from anywhere in the script:
| GetFieldFloat(name, fallback=0) | float | The authored value, or fallback when the field was never set — or when the stored value is of a different type than asked for, which is a miss rather than a reinterpretation. |
| GetFieldInt(name, fallback=0) | int | |
| GetFieldBool(name, fallback=false) | bool | |
| GetFieldString(name, fallback="") | std::string | |
| GetFieldVec3(name, fallback={0,0,0}) | Vec3 | |
| GetFieldEntity(name) | Entity | Resolves the stored id now, not at load. Invalid when unassigned, destroyed, or not in this scene — test it with if (Entity e = ...). |
| GetFieldAsset(name, fallback="") | std::string | Path ready for AssetManager. Empty means unassigned. |
Example
The whole script — one file, Bouncer.h, named after the class. Nothing registers
it by hand.
#pragma once
#include "scene/ScriptableEntity.h"
#include "scene/Components.h"
namespace Thread {
class Bouncer : public ScriptableEntity {
public:
void DeclareFields(ScriptFields& f) override {
f.Float("Height", m_Height, "Peak offset in metres");
f.Float("Rate", m_Rate, "Bounces per second");
}
void OnCreate() override {
m_Height = GetFieldFloat("Height", m_Height);
m_Rate = GetFieldFloat("Rate", m_Rate);
}
void OnUpdate(float ts) override {
m_T += ts;
auto& tc = GetComponent<TransformComponent>();
tc.Translation.y = std::sin(m_T * m_Rate * 6.2831853f) * m_Height;
}
private:
float m_T = 0.0f;
float m_Height = 0.5f;
float m_Rate = 0.5f;
};
}
See also
ScriptableEntity klasa w Thread
Klasa bazowa, po której dziedziczą twoje skrypty gry. Odpowiednik MonoBehaviour z Unity:
dziedzicz, nadpisz zaczepy cyklu życia i podepnij do encji komponentem Native Script.
Rejestracja generuje się sama — skrypt to nagłówek nazwany jak jego klasa; zob.
Skrypty natywne.
Chronione metody cyklu życia override
| OnCreate() | void | Raz, po utworzeniu instancji skryptu i podpięciu jej do Entity. |
| OnUpdate(float ts) | void | Co tick symulacji podczas Play. ts to czas klatki w sekundach. |
| OnDestroy() | void | Gdy encja (albo scena) jest niszczona. |
| OnSpawn() | void | Za każdym razem, gdy encja wchodzi (lub wraca) do świata z EntityPool — także za pierwszym. Tu należy przygotowanie na każde życie. |
| OnDespawn() | void | Tuż przed odłożeniem przez pulę. Encja jeszcze żyje: upuść łup, odpal efekt. |
| OnTriggerEnter(Entity other) | void | Coś weszło w strefę triggera tej encji. |
| OnTriggerExit(Entity other) | void | Coś opuściło strefę triggera. |
| OnCollisionEnter(Entity other) | void | Zaczął się kontakt fizyczny z innym ciałem. |
| OnCollisionExit(Entity other) | void | Kontakt fizyczny się skończył. |
| OnDamaged(const DamageInfo&) | void | HealthComponent tej encji otrzymał obrażenia. |
| OnDeath(const DamageInfo&) | void | Jej zdrowie spadło do zera. |
Metody publiczne
| GetComponent<T>() | T& | Referencja do komponentu T tej encji. Asercja, jeśli go brak. |
| GetScene() | Scene* | Aktywna Scene (statyczne — dostępne wszędzie w trakcie ticku). |
| ChangeScene(path) | void | Zleca zmianę sceny na granicy następnej klatki. |
Multiplayer
Bez sesji wszystkie dają odpowiedź jak w grze jednoosobowej. Zobacz Multiplayer (co-op).
| IsAuthority() | bool | Ten komputer decyduje o świecie (host albo gra solo). Od tego uzależnij obrażenia, łupy, spawnowanie. |
| IsLocallyOwned() | bool | Ten komputer symuluje tę encję. Od tego uzależnij sterowanie z klawiatury. |
| IsHost() / IsClient() / IsOnline() | bool | Stan sesji. |
| LocalPlayer() / LocalPeer() | Entity / PeerId | Postać i numer gracza tego komputera. |
| CallHost / CallAll / CallOwner(rpc, args...) | void | Uruchamia RPC tego skryptu na innym komputerze. |
| DeclareRpcs(RpcTable&) override | void | r.On("Nazwa", &MojSkrypt::Metoda), metoda przyjmuje RpcCall&. |
| DeclareReplicated(Replicated&) override | void | r.Float("Health", m_Health): wartości, które host trzyma w zgodzie u każdego klienta. |
Pola serializowane override
Pola skryptu nigdy nie są zapisywane. Żeby wystawić wartość, którą inspektor ustawi per encja, a
plik sceny zachowa, zadeklaruj ją — to odpowiednik [SerializeField].
| DeclareFields(ScriptFields&) | void | Nadpisz, żeby podać schemat skryptu. Wywoływane przez EDYTOR na tymczasowej instancji, bez OnCreate — musi więc być czystym opisem. |
Deklarowanie, na przekazanym ScriptFields&:
| Float(name, def, tip="") | void | Wiersz przeciąganej liczby zmiennoprzecinkowej. |
| Int(name, def, tip="") | void | Wiersz przeciąganej liczby całkowitej. |
| Bool(name, def, tip="") | void | Checkbox. |
| String(name, def, tip="") | void | Pole tekstowe. |
| Vec3f(name, def, tip="") | void | Wiersz z trzema składowymi. |
| EntityRef(name, tip="") | void | Slot, na który przeciągasz inną encję. Zapisuje id celu. |
| AssetRef(name, AssetType, tip="") | void | Wybór assetu ograniczony do typu. |
Odczyt, z dowolnego miejsca skryptu:
| GetFieldFloat(name, fallback=0) | float | Ustawiona wartość albo fallback, gdy pola nigdy nie ustawiono — albo gdy zapisana wartość jest innego typu niż żądany, co jest chybieniem, a nie reinterpretacją. |
| GetFieldInt(name, fallback=0) | int | |
| GetFieldBool(name, fallback=false) | bool | |
| GetFieldString(name, fallback="") | std::string | |
| GetFieldVec3(name, fallback={0,0,0}) | Vec3 | |
| GetFieldEntity(name) | Entity | Rozwiązuje zapisane id teraz, nie przy wczytaniu. Nieważna, gdy nieprzypisana, zniszczona albo nie w tej scenie — sprawdzaj przez if (Entity e = ...). |
| GetFieldAsset(name, fallback="") | std::string | Ścieżka gotowa dla AssetManager. Pusta = nieprzypisana. |
Przykład
Cały skrypt — jeden plik, Bouncer.h, nazwany jak klasa. Nic nie rejestruje go
ręcznie.
#pragma once
#include "scene/ScriptableEntity.h"
#include "scene/Components.h"
namespace Thread {
class Bouncer : public ScriptableEntity {
public:
void DeclareFields(ScriptFields& f) override {
f.Float("Height", m_Height, "Peak offset in metres");
f.Float("Rate", m_Rate, "Bounces per second");
}
void OnCreate() override {
m_Height = GetFieldFloat("Height", m_Height);
m_Rate = GetFieldFloat("Rate", m_Rate);
}
void OnUpdate(float ts) override {
m_T += ts;
auto& tc = GetComponent<TransformComponent>();
tc.Translation.y = std::sin(m_T * m_Rate * 6.2831853f) * m_Height;
}
private:
float m_T = 0.0f;
float m_Height = 0.5f;
float m_Rate = 0.5f;
};
}