-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathbase-node.ts
More file actions
1401 lines (1251 loc) · 49.6 KB
/
base-node.ts
File metadata and controls
1401 lines (1251 loc) · 49.6 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module scene-graph
*/
import { ccclass, editable, serializable } from 'cc.decorator';
import { DEV, DEBUG, EDITOR } from 'internal:constants';
import { Component } from '../components/component';
import { property } from '../data/decorators/property';
import { CCObject } from '../data/object';
import { Event } from '../event';
import { errorID, warnID, error, log, getError } from '../platform/debug';
import { SystemEventType } from '../platform/event-manager/event-enum';
import { ISchedulable } from '../scheduler';
import IdGenerator from '../utils/id-generator';
import * as js from '../utils/js';
import { baseNodePolyfill } from './base-node-dev';
import { legacyCC } from '../global-exports';
import { Node } from './node';
import type { Scene } from './scene';
import { PrefabInfo } from '../utils/prefab-utils';
const Destroying = CCObject.Flags.Destroying;
const DontDestroy = CCObject.Flags.DontDestroy;
const Deactivating = CCObject.Flags.Deactivating;
export const TRANSFORM_ON = 1 << 0;
// const CHILD_ADDED = 'child-added';
// const CHILD_REMOVED = 'child-removed';
const idGenerator = new IdGenerator('Node');
function getConstructor<T> (typeOrClassName: string | Constructor<T>): Constructor<T> | null | undefined {
if (!typeOrClassName) {
errorID(3804);
return null;
}
if (typeof typeOrClassName === 'string') {
return js.getClassByName(typeOrClassName) as Constructor<T> | undefined;
}
return typeOrClassName;
}
/**
* @en The base class for [[Node]], it:
* - maintains scene hierarchy and life cycle logic
* - provides EventTarget ability
* - emits events if some properties changed, ref: [[SystemEventType]]
* - manages components
* @zh [[Node]] 的基类,他会负责:
* - 维护场景树以及节点生命周期管理
* - 提供 EventTarget 的事件管理和注册能力
* - 派发节点状态相关的事件,参考:[[SystemEventType]]
* - 管理组件
*/
@ccclass('cc.BaseNode')
export class BaseNode extends CCObject implements ISchedulable {
/**
* @en Gets all components attached to this node.
* @zh 获取附加到此节点的所有组件。
*/
get components (): ReadonlyArray<Component> {
return this._components;
}
/**
* @en If true, the node is an persist node which won't be destroyed during scene transition.
* If false, the node will be destroyed automatically when loading a new scene. Default is false.
* @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。
* 如果为false,节点将在加载新场景时自动销毁。默认为 false。
* @default false
* @protected
*/
@property
get _persistNode (): boolean {
return (this._objFlags & DontDestroy) > 0;
}
set _persistNode (value) {
if (value) {
this._objFlags |= DontDestroy;
} else {
this._objFlags &= ~DontDestroy;
}
}
// API
/**
* @en Name of node.
* @zh 该节点名称。
*/
@editable
get name (): string {
return this._name;
}
set name (value) {
if (DEV && value.indexOf('/') !== -1) {
errorID(1632);
return;
}
this._name = value;
}
/**
* @en The uuid for editor, will be stripped after building project.
* @zh 主要用于编辑器的 uuid,在编辑器下可用于持久化存储,在项目构建之后将变成自增的 id。
* @readOnly
*/
get uuid () {
return this._id;
}
/**
* @en All children nodes.
* @zh 节点的所有子节点。
* @readOnly
*/
@editable
get children () {
return this._children;
}
/**
* @en
* The local active state of this node.
* Note that a Node may be inactive because a parent is not active, even if this returns true.
* Use [[activeInHierarchy]]
* if you want to check if the Node is actually treated as active in the scene.
* @zh
* 当前节点的自身激活状态。
* 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
* 如果你想检查节点在场景中实际的激活状态可以使用 [[activeInHierarchy]]
* @default true
*/
@editable
get active () {
return this._active;
}
set active (isActive: boolean) {
if (this._active !== isActive) {
this._active = isActive;
const parent = this._parent;
if (parent) {
const couldActiveInScene = parent._activeInHierarchy;
if (couldActiveInScene) {
legacyCC.director._nodeActivator.activateNode(this, isActive);
}
}
}
}
/**
* @en Indicates whether this node is active in the scene.
* @zh 表示此节点是否在场景中激活。
*/
@editable
get activeInHierarchy () {
return this._activeInHierarchy;
}
/**
* @en The parent node
* @zh 父节点
*/
@editable
get parent () {
return this._parent;
}
set parent (value) {
this.setParent(value);
}
/**
* @en Which scene this node belongs to.
* @zh 此节点属于哪个场景。
* @readonly
*/
get scene () {
return this._scene;
}
/**
* @en The event processor of the current node, it provides EventTarget ability.
* @zh 当前节点的事件处理器,提供 EventTarget 能力。
* @readonly
*/
get eventProcessor () {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this._eventProcessor;
}
protected static idGenerator = idGenerator;
// For walk
protected static _stacks: Array<Array<(BaseNode | null)>> = [[]];
protected static _stackId = 0;
/**
* Call `_updateScene` of specified node.
* @param node The node.
*/
protected static _setScene (node: BaseNode) {
node._updateScene();
}
protected static _findComponent<T extends Component> (node: BaseNode, constructor: Constructor<T>): T | null {
const cls = constructor as any;
const comps = node._components;
if (cls._sealed) {
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i];
if (comp.constructor === constructor) {
return comp as T;
}
}
} else {
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i];
if (comp instanceof constructor) {
return comp;
}
}
}
return null;
}
protected static _findComponents<T extends Component> (node: BaseNode, constructor: Constructor<T>, components: Component[]) {
const cls = constructor as any;
const comps = node._components;
if (cls._sealed) {
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i];
if (comp.constructor === constructor) {
components.push(comp);
}
}
} else {
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i];
if (comp instanceof constructor) {
components.push(comp);
}
}
}
}
protected static _findChildComponent<T extends Component> (children: BaseNode[], constructor: Constructor<T>): T | null {
for (let i = 0; i < children.length; ++i) {
const node = children[i];
let comp = BaseNode._findComponent(node, constructor);
if (comp) {
return comp;
}
if (node._children.length > 0) {
comp = BaseNode._findChildComponent(node._children, constructor);
if (comp) {
return comp;
}
}
}
return null;
}
protected static _findChildComponents (children: BaseNode[], constructor, components) {
for (let i = 0; i < children.length; ++i) {
const node = children[i];
BaseNode._findComponents(node, constructor, components);
if (node._children.length > 0) {
BaseNode._findChildComponents(node._children, constructor, components);
}
}
}
@serializable
protected _parent: this | null = null;
@serializable
protected _children: this[] = [];
@serializable
protected _active = true;
@serializable
protected _components: Component[] = [];
// The PrefabInfo object
@serializable
protected _prefab: PrefabInfo|null = null;
protected _scene: Scene = null!;
protected _activeInHierarchy = false;
protected _id: string = idGenerator.getNewId();
protected _name: string;
protected _eventProcessor: any = new legacyCC.NodeEventProcessor(this);
protected _eventMask = 0;
protected _siblingIndex = 0;
/**
* Set `_scene` field of this node.
* The derived `Scene` overrides this method to behavior differently.
*/
protected _updateScene () {
if (this._parent == null) {
error('Node %s(%s) has not attached to a scene.', this.name, this.uuid);
} else {
this._scene = this._parent._scene;
}
}
protected _registerIfAttached = !EDITOR ? undefined : function _registerIfAttached (this: BaseNode, register) {
if (EditorExtends.Node && EditorExtends.Component) {
if (register) {
EditorExtends.Node.add(this._id, this);
for (let i = 0; i < this._components.length; i++) {
const comp = this._components[i];
EditorExtends.Component.add(comp._id, comp);
}
} else {
for (let i = 0; i < this._components.length; i++) {
const comp = this._components[i];
EditorExtends.Component.remove(comp._id);
}
EditorExtends.Node.remove(this._id);
}
}
const children = this._children;
for (let i = 0, len = children.length; i < len; ++i) {
const child = children[i];
child._registerIfAttached!(register);
}
};
constructor (name?: string) {
super(name);
this._name = name !== undefined ? name : 'New Node';
}
/**
* @en
* Properties configuration function.
* All properties in attrs will be set to the node,
* when the setter of the node is available,
* the property will be set via setter function.
* @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。
* @param attrs - Properties to be set to node
* @example
* ```
* var attrs = { name: 'New Name', active: false };
* node.attr(attrs);
* ```
*/
public attr (attrs: unknown) {
js.mixin(this, attrs);
}
// HIERARCHY METHODS
/**
* @en Get parent of the node.
* @zh 获取该节点的父节点。
*/
public getParent () {
return this._parent;
}
/**
* @en Set parent of the node.
* @zh 设置该节点的父节点。
*/
public setParent (value: this | Scene | null, keepWorldTransform = false) {
if (this._parent === value) {
return;
}
const oldParent = this._parent;
const newParent = value as this;
if (DEBUG && oldParent
// Change parent when old parent deactivating or activating
&& (oldParent._objFlags & Deactivating)) {
errorID(3821);
}
this._parent = newParent;
// Reset sibling index
this._siblingIndex = 0;
this._onSetParent(oldParent, keepWorldTransform);
if (this.emit) {
this.emit(SystemEventType.PARENT_CHANGED, oldParent);
}
if (oldParent) {
if (!(oldParent._objFlags & Destroying)) {
const removeAt = oldParent._children.indexOf(this);
if (DEV && removeAt < 0) {
errorID(1633);
return;
}
oldParent._children.splice(removeAt, 1);
oldParent._updateSiblingIndex();
if (oldParent.emit) {
oldParent.emit(SystemEventType.CHILD_REMOVED, this);
}
}
}
if (newParent) {
if (DEBUG && (newParent._objFlags & Deactivating)) {
errorID(3821);
}
newParent._children.push(this);
this._siblingIndex = newParent._children.length - 1;
if (newParent.emit) {
newParent.emit(SystemEventType.CHILD_ADDED, this);
}
}
this._onHierarchyChanged(oldParent);
}
/**
* @en Returns a child with the same uuid.
* @zh 通过 uuid 获取节点的子节点。
* @param uuid - The uuid to find the child node.
* @return a Node whose uuid equals to the input parameter
*/
public getChildByUuid (uuid: string) {
if (!uuid) {
log('Invalid uuid');
return null;
}
const locChildren = this._children;
for (let i = 0, len = locChildren.length; i < len; i++) {
if (locChildren[i]._id === uuid) {
return locChildren[i];
}
}
return null;
}
/**
* @en Returns a child with the same name.
* @zh 通过名称获取节点的子节点。
* @param name - A name to find the child node.
* @return a CCNode object whose name equals to the input parameter
* @example
* ```
* var child = node.getChildByName("Test Node");
* ```
*/
public getChildByName (name: string) {
if (!name) {
log('Invalid name');
return null;
}
const locChildren = this._children;
for (let i = 0, len = locChildren.length; i < len; i++) {
if (locChildren[i]._name === name) {
return locChildren[i];
}
}
return null;
}
/**
* @en Returns a child with the given path.
* @zh 通过路径获取节点的子节点。
* @param path - A path to find the child node.
* @return a Node object whose path equals to the input parameter
* @example
* ```
* var child = node.getChildByPath("subNode/Test Node");
* ```
*/
public getChildByPath (path: string) {
const segments = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-this-alias
let lastNode: this = this;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.length === 0) {
continue;
}
const next = lastNode.children.find((childNode) => childNode.name === segment);
if (!next) {
return null;
}
lastNode = next;
}
return lastNode;
}
/**
* @en Add a child to the current node.
* @zh 添加一个子节点。
* @param child - the child node to be added
*/
public addChild (child: this | Node): void {
(child as this).setParent(this);
}
/**
* @en Inserts a child to the node at a specified index.
* @zh 插入子节点到指定位置
* @param child - the child node to be inserted
* @param siblingIndex - the sibling index to place the child in
* @example
* ```
* node.insertChild(child, 2);
* ```
*/
public insertChild (child: this | Node, siblingIndex: number) {
child.parent = this;
child.setSiblingIndex(siblingIndex);
}
/**
* @en Get the sibling index of the current node in its parent's children array.
* @zh 获取当前节点在父节点的 children 数组中的位置。
*/
public getSiblingIndex () {
return this._siblingIndex;
}
/**
* @en Set the sibling index of the current node in its parent's children array.
* @zh 设置当前节点在父节点的 children 数组中的位置。
*/
public setSiblingIndex (index: number) {
if (!this._parent) {
return;
}
if (this._parent._objFlags & Deactivating) {
errorID(3821);
return;
}
const siblings = this._parent._children;
index = index !== -1 ? index : siblings.length - 1;
const oldIndex = siblings.indexOf(this);
if (index !== oldIndex) {
siblings.splice(oldIndex, 1);
if (index < siblings.length) {
siblings.splice(index, 0, this);
} else {
siblings.push(this);
}
this._parent._updateSiblingIndex();
if (this._onSiblingIndexChanged) {
this._onSiblingIndexChanged(index);
}
}
}
/**
* @en Walk though the sub children tree of the current node.
* Each node, including the current node, in the sub tree will be visited two times,
* before all children and after all children.
* This function call is not recursive, it's based on stack.
* Please don't walk any other node inside the walk process.
* @zh 遍历该节点的子树里的所有节点并按规则执行回调函数。
* 对子树中的所有节点,包含当前节点,会执行两次回调,preFunc 会在访问它的子节点之前调用,postFunc 会在访问所有子节点之后调用。
* 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。
* 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。
* @param preFunc The callback to process node when reach the node for the first time
* @param postFunc The callback to process node when re-visit the node after walked all children in its sub tree
* @example
* ```
* node.walk(function (target) {
* console.log('Walked through node ' + target.name + ' for the first time');
* }, function (target) {
* console.log('Walked through node ' + target.name + ' after walked all children in its sub tree');
* });
* ```
*/
public walk (preFunc: (target: this) => void, postFunc?: (target: this) => void) {
// const BaseNode = cc._BaseNode;
let index = 1;
let children: this[] | null = null;
let curr: this | null = null;
let i = 0;
let stack = BaseNode._stacks[BaseNode._stackId];
if (!stack) {
stack = [];
BaseNode._stacks.push(stack);
}
BaseNode._stackId++;
stack.length = 0;
stack[0] = this;
let parent: this | null = null;
let afterChildren = false;
while (index) {
index--;
curr = stack[index] as (this | null);
if (!curr) {
continue;
}
if (!afterChildren && preFunc) {
// pre call
preFunc(curr);
} else if (afterChildren && postFunc) {
// post call
postFunc(curr);
}
// Avoid memory leak
stack[index] = null;
// Do not repeatedly visit child tree, just do post call and continue walk
if (afterChildren) {
if (parent === this._parent) break;
afterChildren = false;
} else {
// Children not proceeded and has children, proceed to child tree
if (curr._children.length > 0) {
parent = curr;
children = curr._children;
i = 0;
stack[index] = children[i];
index++;
} else {
stack[index] = curr;
index++;
afterChildren = true;
}
continue;
}
// curr has no sub tree, so look into the siblings in parent children
if (children) {
i++;
// Proceed to next sibling in parent children
if (children[i]) {
stack[index] = children[i];
index++;
} else if (parent) {
stack[index] = parent;
index++;
// Setup parent walk env
afterChildren = true;
if (parent._parent) {
children = parent._parent._children;
i = children.indexOf(parent);
parent = parent._parent;
} else {
// At root
parent = null;
children = null;
}
// ERROR
if (i < 0) {
break;
}
}
}
}
stack.length = 0;
BaseNode._stackId--;
}
/**
* @en
* Remove itself from its parent node.
* If the node have no parent, then nothing happens.
* @zh
* 从父节点中删除该节点。
* 如果这个节点是一个孤立节点,那么什么都不会发生。
*/
public removeFromParent () {
if (this._parent) {
this._parent.removeChild(this);
}
}
/**
* @en Removes a child from the container.
* @zh 移除节点中指定的子节点。
* @param child - The child node which will be removed.
*/
public removeChild (child: this | Node) {
if (this._children.indexOf(child as this) > -1) {
// invoke the parent setter
child.parent = null;
}
}
/**
* @en Removes all children from the container.
* @zh 移除节点所有的子节点。
*/
public removeAllChildren () {
// not using detachChild improves speed here
const children = this._children;
for (let i = children.length - 1; i >= 0; i--) {
const node = children[i];
if (node) {
node.parent = null;
}
}
this._children.length = 0;
}
/**
* @en Is this node a child of the given node?
* @zh 是否是指定节点的子节点?
* @return True if this node is a child, deep child or identical to the given node.
*/
public isChildOf (parent: this | Scene | null): boolean {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let child: BaseNode | null = this;
do {
if (child === parent) {
return true;
}
child = child._parent;
}
while (child);
return false;
}
// COMPONENT
/**
* @en
* Returns the component of supplied type if the node has one attached, null if it doesn't.
* You can also get component in the node by passing in the name of the script.
* @zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。
* @param classConstructor The class of the target component
* @example
* ```
* // get sprite component.
* var sprite = node.getComponent(Sprite);
* ```
*/
public getComponent<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* @en
* Returns the component of supplied type if the node has one attached, null if it doesn't.
* You can also get component in the node by passing in the name of the script.
* @zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。
* @param className The class name of the target component
* @example
* ```
* // get custom test class.
* var test = node.getComponent("Test");
* ```
*/
public getComponent (className: string): Component | null;
public getComponent<T extends Component> (typeOrClassName: string | Constructor<T>) {
const constructor = getConstructor(typeOrClassName);
if (constructor) {
return BaseNode._findComponent(this, constructor);
}
return null;
}
/**
* @en Returns all components of given type in the node.
* @zh 返回节点上指定类型的所有组件。
* @param classConstructor The class of the target component
*/
public getComponents<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* @en Returns all components of given type in the node.
* @zh 返回节点上指定类型的所有组件。
* @param className The class name of the target component
*/
public getComponents (className: string): Component[];
public getComponents<T extends Component> (typeOrClassName: string | Constructor<T>) {
const constructor = getConstructor(typeOrClassName);
const components: Component[] = [];
if (constructor) {
BaseNode._findComponents(this, constructor, components);
}
return components;
}
/**
* @en Returns the component of given type in any of its children using depth first search.
* @zh 递归查找所有子节点中第一个匹配指定类型的组件。
* @param classConstructor The class of the target component
* @example
* ```
* var sprite = node.getComponentInChildren(Sprite);
* ```
*/
public getComponentInChildren<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* @en Returns the component of given type in any of its children using depth first search.
* @zh 递归查找所有子节点中第一个匹配指定类型的组件。
* @param className The class name of the target component
* @example
* ```
* var Test = node.getComponentInChildren("Test");
* ```
*/
public getComponentInChildren (className: string): Component | null;
public getComponentInChildren<T extends Component> (typeOrClassName: string | Constructor<T>) {
const constructor = getConstructor(typeOrClassName);
if (constructor) {
return BaseNode._findChildComponent(this._children, constructor);
}
return null;
}
/**
* @en Returns all components of given type in self or any of its children.
* @zh 递归查找自身或所有子节点中指定类型的组件
* @param classConstructor The class of the target component
* @example
* ```
* var sprites = node.getComponentsInChildren(Sprite);
* ```
*/
public getComponentsInChildren<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* @en Returns all components of given type in self or any of its children.
* @zh 递归查找自身或所有子节点中指定类型的组件
* @param className The class name of the target component
* @example
* ```
* var tests = node.getComponentsInChildren("Test");
* ```
*/
public getComponentsInChildren (className: string): Component[];
public getComponentsInChildren<T extends Component> (typeOrClassName: string | Constructor<T>) {
const constructor = getConstructor(typeOrClassName);
const components: Component[] = [];
if (constructor) {
BaseNode._findComponents(this, constructor, components);
BaseNode._findChildComponents(this._children, constructor, components);
}
return components;
}
/**
* @en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @param classConstructor The class of the component to add
* @throws `TypeError` if the `classConstructor` does not specify a cc-class constructor extending the `Component`.
* @example
* ```
* var sprite = node.addComponent(Sprite);
* ```
*/
public addComponent<T extends Component> (classConstructor: Constructor<T>): T;
/**
* @en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @param className The class name of the component to add
* @throws `TypeError` if the `className` does not specify a cc-class constructor extending the `Component`.
* @example
* ```
* var test = node.addComponent("Test");
* ```
*/
public addComponent (className: string): Component;
public addComponent<T extends Component> (typeOrClassName: string | Constructor<T>) {
if (EDITOR && (this._objFlags & Destroying)) {
throw Error('isDestroying');
}
// get component
let constructor: Constructor<T> | null | undefined;
if (typeof typeOrClassName === 'string') {
constructor = js.getClassByName(typeOrClassName) as Constructor<T> | undefined;
if (!constructor) {
if (legacyCC._RF.peek()) {
errorID(3808, typeOrClassName);
}
throw TypeError(getError(3807, typeOrClassName));
}
} else {
if (!typeOrClassName) {
throw TypeError(getError(3804));
}
constructor = typeOrClassName;
}
// check component
if (typeof constructor !== 'function') {
throw TypeError(getError(3809));
}
if (!js.isChildClassOf(constructor, legacyCC.Component)) {
throw TypeError(getError(3810));
}
if (EDITOR && (constructor as typeof constructor & { _disallowMultiple?: unknown })._disallowMultiple) {
this._checkMultipleComp!(constructor);
}
// check requirement
const ReqComp = (constructor as typeof constructor & { _requireComponent?: typeof Component })._requireComponent;
if (ReqComp && !this.getComponent(ReqComp)) {
this.addComponent(ReqComp);
}
/// / check conflict
//
// if (EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) {
// return null;
// }
//
const component = new constructor();
component.node = (this as unknown as Node); // TODO: HACK here
this._components.push(component);
if (EDITOR && EditorExtends.Node && EditorExtends.Component) {
const node = EditorExtends.Node.getNode(this._id);
if (node) {
EditorExtends.Component.add(component._id, component);
}
}
if (this._activeInHierarchy) {
legacyCC.director._nodeActivator.activateComp(component);
}
return component;
}
/**
* @en
* Removes a component identified by the given name or removes the component object given.
* You can also use component.destroy() if you already have the reference.
* @zh
* 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
* 如果你已经获得组件引用,你也可以直接调用 component.destroy()
* @param classConstructor The class of the component to remove
* @deprecated please destroy the component to remove it.
* @example
* ```
* node.removeComponent(Sprite);
* ```
*/
public removeComponent<T extends Component> (classConstructor: Constructor<T>): void;
/**
* @en
* Removes a component identified by the given name or removes the component object given.
* You can also use component.destroy() if you already have the reference.
* @zh
* 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
* 如果你已经获得组件引用,你也可以直接调用 component.destroy()
* @param classNameOrInstance The class name of the component to remove or the component instance to be removed
* @deprecated please destroy the component to remove it.