ShitEngine 1.4.2
基于 C++20 与 SDL3 的轻量级 2D 游戏引擎
载入中...
搜索中...
未找到
ComponentRef.h
浏览该文件的文档.
1#pragma once
2// ═══════════════════════════════════════════════════════════════
3// P20: 组件引用(类似 Unity 的 Object 引用字段)
4//
5// ComponentRef<T> 是"可序列化的组件引用":字段内只存目标组件的持久
6// UUID(64 位,随 .scene 落盘),get() 时经当前场景的 uuid → 组件索引
7// 懒解析。目标组件被移除/所属对象销毁后,get() 返回 nullptr——永不悬垂。
8//
9// 用法(配合反射扫描器,字段自动被识别为引用字段):
10// SHIT_FIELD
11// Shit::ComponentRef<Shit::UIText> coinText; // 编辑器可拖拽赋引用
12//
13// if (auto t = coinText.get()) t->setText("...");
14//
15// 与 WeakComponentRef 的区别:WeakComponentRef 是"会话期弱引用"
16// (存 owner + 生命周期令牌,不序列化);ComponentRef 是"持久引用"
17// (存 UUID,序列化到 .scene,目标销毁自动失效)。
18//
19// 约束:引用仅限同一场景(UUID 索引挂在 Scene 上);跨场景引用解析为 null。
20// ═══════════════════════════════════════════════════════════════
21
23
24#include <cstdint>
25
26namespace Shit {
27
28 class Scene; // 前向声明
29 class Component; // 前向声明(dynamic_cast 在实例化点解析)
30
33
38 template <typename T>
40 public:
41 ComponentRef() = default;
42
45 T* get() const {
46 if (!m_uuid) return nullptr;
47 Component* comp = ComponentRefLookup(m_uuid);
48 if (!comp) return nullptr;
49 return dynamic_cast<T*>(comp);
50 }
51
53 T* operator->() const { return get(); }
54
56 explicit operator bool() const { return get() != nullptr; }
57
59 uint64_t uuid() const { return m_uuid; }
61 void setUuid(uint64_t uuid) { m_uuid = uuid; }
62
63 bool operator==(const ComponentRef& other) const { return m_uuid == other.m_uuid; }
64 bool operator!=(const ComponentRef& other) const { return !(*this == other); }
65
66 private:
67 uint64_t m_uuid = 0;
68 };
69
70} // namespace Shit
#define SHIT_API
定义 Core.h:14
组件基类
定义 Component.h:25
bool operator!=(const ComponentRef &other) const
定义 ComponentRef.h:64
ComponentRef()=default
T * operator->() const
便捷解引用(目标失效返回 nullptr,调用前可判空)
定义 ComponentRef.h:53
uint64_t uuid() const
目标组件 UUID(0 = 空引用;编辑器/序列化用)
定义 ComponentRef.h:59
void setUuid(uint64_t uuid)
设置引用目标(传入 0 清空引用;编辑器拖拽赋引用用)
定义 ComponentRef.h:61
bool operator==(const ComponentRef &other) const
定义 ComponentRef.h:63
T * get() const
解析引用(当前场景的 uuid 索引查找 + 类型校验) 目标组件已移除/对象已销毁/类型不符/跨场景时返回 nullptr。
定义 ComponentRef.h:45
场景类
定义 Scene.h:36
定义 AnimationClip.h:12
Component * ComponentRefLookup(uint64_t uuid)
内部:从当前上下文的活跃场景按 uuid 查组件(实现在 ComponentRef.cpp,跨 TU/DLL 共享)
@ T
定义 KeyCode.h:37