-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.ts
More file actions
102 lines (89 loc) · 3.02 KB
/
main_test.ts
File metadata and controls
102 lines (89 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { Accessor, createSignal } from "solid/signal";
import { renderOn, For, LoadPrefab, Bind, H } from "solid/unity";
// 一个自定义组件,参数是位置
const testSphere = (pos: Accessor<CS.UnityEngine.Vector3>) => {
// 支持普通的 GameObject,不一定非要是 uGUI 节点。
// 返回的元素只是为了让外层组件获取。并不意味着一定会被 parent 到外层组件的 GameObject上。
return LoadPrefab('sphere', {
transform: [
// 通过绑定,属性能根据数据源变化自动更新,也会自动清理监听。
Bind.prop('position', pos),
],
})
}
const testUiItem = (value: Accessor<number>, posY: Accessor<number>) =>{
// 通过自定义组件 testSphere 创建元素
// 如果当前组件被删除时,这个闭包内部创建的元素会被自动删除。即,自动生命周期管理。
// 由于没有进行 insert 操作,它会直接放在场景根节点。
// 生命周期管理,不要求必须 parent 到某个节点。
H(
testSphere,
() => new CS.UnityEngine.Vector3(value(), posY() + 1, 0)
);
// 返回一个 uGUI 节点
return LoadPrefab('test_ui_item', {
text: [
Bind.prop('text', () => `value: ${value()}`),
],
})
}
const testUiPanel = () => {
const [count, setCount] = createSignal(0);
const [list, setList] = createSignal(new Array<number>());
const [posY, setPosY] = createSignal(1);
function onClickAdd() {
const c = setCount(c => c + 1);
setList(l => {
if (c < 4) {
return [...l, c];
} else {
return l.slice(0, -1);
}
});
}
function onClickPos() {
setPosY(y => (y + 1) % 4);
}
// 根据 list 数据,利用自定义组件 testUiItem 生成 children 元素
// For 会自动管理 children 的生命周期,当 list 变化时,会自动更新 children。
// 并且会尽量复用已有的元素,减少创建和销毁。
const children = For(list, (item) => H(
testUiItem,
() => item, // value
posY, // posY
));
return LoadPrefab('test_ui_panel', {
text_count: [
Bind.prop('text', count),
],
button_add: [
Bind.unityEvent('onClick', onClickAdd),
],
button_pos: [
Bind.unityEvent('onClick', onClickPos),
],
even: [
Bind.invoke('SetActive', () => count() % 2 == 0),
],
list: [
// 把 children insert 到 list 节点下
Bind.insert(() => children),
],
})
}
function runTestUi() {
const canvas = CS.UnityEngine.GameObject.Find('Canvas');
renderOn(canvas, () => H(testUiPanel));
}
runTestUi();
function printWithTrace(...args: any[]) {
const err = args[1];
if (err instanceof Error) {
console.error(err.message);
if (err.stack) {
print(err.stack);
}
} else {
console.error(err);
}
}