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.

class ScriptableEntity

Protected lifecycle methods

OnCreate()voidCalled once after the script instance is constructed and attached to its Entity.
OnUpdate(float ts)voidCalled every simulation tick during Play. ts is delta-time in seconds.
OnDestroy()voidCalled when the entity (or scene) is destroyed.
OnSpawn()voidEvery time the entity comes (back) into the world from an EntityPool — including the first. Per-life setup belongs here.
OnDespawn()voidJust before the pool parks the entity. It is still live: drop loot, start an effect.
OnTriggerEnter(Entity other)voidSomething entered this entity's trigger volume.
OnTriggerExit(Entity other)voidSomething left the trigger volume.
OnCollisionEnter(Entity other)voidA physics contact began with another body.
OnCollisionExit(Entity other)voidA physics contact ended.
OnDamaged(const DamageInfo&)voidThis entity's HealthComponent took damage.
OnDeath(const DamageInfo&)voidIts 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)voidRequests 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()boolThis machine decides the world (host, or alone). Gate damage, loot, spawning.
IsLocallyOwned()boolThis machine simulates this entity. Gate keyboard input.
IsHost() / IsClient() / IsOnline()boolThe session.
LocalPlayer() / LocalPeer()Entity / PeerIdThis machine's character and player id.
CallHost / CallAll / CallOwner(rpc, args...)voidRun one of this script's RPCs on another machine.
DeclareRpcs(RpcTable&) voidr.On("Name", &MyScript::Method), Method takes RpcCall&.
DeclareReplicated(Replicated&) voidr.Float("Health", m_Health): values the host keeps in step on every client.

Serialized fields

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&)voidOverride 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="")voidDrag-float row.
Int(name, def, tip="")voidDrag-int row.
Bool(name, def, tip="")voidCheckbox.
String(name, def, tip="")voidText box.
Vec3f(name, def, tip="")voidThree-component drag row.
EntityRef(name, tip="")voidSlot another entity is dragged onto. Stores the target's id.
AssetRef(name, AssetType, tip="")voidAsset picker filtered to that type.

Reading, from anywhere in the script:

GetFieldFloat(name, fallback=0)floatThe 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)EntityResolves 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::stringPath 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

Entity · Scene · Native Scripting guide

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.

class ScriptableEntity

Chronione metody cyklu życia

OnCreate()voidRaz, po utworzeniu instancji skryptu i podpięciu jej do Entity.
OnUpdate(float ts)voidCo tick symulacji podczas Play. ts to czas klatki w sekundach.
OnDestroy()voidGdy encja (albo scena) jest niszczona.
OnSpawn()voidZa 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()voidTuż przed odłożeniem przez pulę. Encja jeszcze żyje: upuść łup, odpal efekt.
OnTriggerEnter(Entity other)voidCoś weszło w strefę triggera tej encji.
OnTriggerExit(Entity other)voidCoś opuściło strefę triggera.
OnCollisionEnter(Entity other)voidZaczął się kontakt fizyczny z innym ciałem.
OnCollisionExit(Entity other)voidKontakt fizyczny się skończył.
OnDamaged(const DamageInfo&)voidHealthComponent tej encji otrzymał obrażenia.
OnDeath(const DamageInfo&)voidJej 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)voidZleca zmianę sceny na granicy następnej klatki.

Multiplayer

Bez sesji wszystkie dają odpowiedź jak w grze jednoosobowej. Zobacz Multiplayer (co-op).

IsAuthority()boolTen komputer decyduje o świecie (host albo gra solo). Od tego uzależnij obrażenia, łupy, spawnowanie.
IsLocallyOwned()boolTen komputer symuluje tę encję. Od tego uzależnij sterowanie z klawiatury.
IsHost() / IsClient() / IsOnline()boolStan sesji.
LocalPlayer() / LocalPeer()Entity / PeerIdPostać i numer gracza tego komputera.
CallHost / CallAll / CallOwner(rpc, args...)voidUruchamia RPC tego skryptu na innym komputerze.
DeclareRpcs(RpcTable&) voidr.On("Nazwa", &MojSkrypt::Metoda), metoda przyjmuje RpcCall&.
DeclareReplicated(Replicated&) voidr.Float("Health", m_Health): wartości, które host trzyma w zgodzie u każdego klienta.

Pola serializowane

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&)voidNadpisz, ż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="")voidWiersz przeciąganej liczby zmiennoprzecinkowej.
Int(name, def, tip="")voidWiersz przeciąganej liczby całkowitej.
Bool(name, def, tip="")voidCheckbox.
String(name, def, tip="")voidPole tekstowe.
Vec3f(name, def, tip="")voidWiersz z trzema składowymi.
EntityRef(name, tip="")voidSlot, na który przeciągasz inną encję. Zapisuje id celu.
AssetRef(name, AssetType, tip="")voidWybór assetu ograniczony do typu.

Odczyt, z dowolnego miejsca skryptu:

GetFieldFloat(name, fallback=0)floatUstawiona 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)EntityRozwią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;
    };
}

Zobacz też

Entity · Scene · Przewodnik po skryptach natywnych