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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
|
#include "UnityPrefix.h"
#include "GameObject.h"
#include "CleanupManager.h"
#include "Runtime/Serialize/AwakeFromLoadQueue.h"
#include "Runtime/Serialize/TransferFunctions/SerializeTransfer.h"
#include "Runtime/Serialize/SerializationMetaFlags.h"
#include "Tags.h"
#include "MessageHandler.h"
#include "Runtime/Misc/ReproductionLog.h"
#include "Runtime/Utilities/Utility.h"
#include "Runtime/Misc/BuildSettings.h"
#include "Runtime/Graphics/Texture2D.h"
#include "Runtime/Graphics/Transform.h"
#include "Runtime/Misc/GameObjectUtility.h"
#include "Runtime/Misc/ComponentRequirement.h"
#include "Runtime/Mono/MonoBehaviour.h"
#include "Runtime/Containers/ConstantStringSerialization.h"
#include "Runtime/Profiler/Profiler.h"
#if UNITY_EDITOR
#include "Editor/Src/BuildPipeline/BuildTargetPlatformSpecific.h"
#include "Editor/Src/Utility/StaticEditorFlags.h"
#endif
#if UNITY_WII
#include <rvlaux/clib.h>
#endif
using namespace std;
namespace Unity
{
PROFILER_INFORMATION (gActivateGameObjectProfiler, "GameObject.Activate", kProfilerScripts)
PROFILER_INFORMATION (gDeactivateGameObjectProfiler, "GameObject.Deactivate", kProfilerScripts)
Unity::GameObject::DestroyGOCallbackFunction* Unity::GameObject::s_GameObjectDestroyedCallback = NULL;
Unity::GameObject::SetGONameFunction* Unity::GameObject::s_SetGONameCallback = NULL;
MessageForwarders* Unity::GameObject::s_RegisteredMessageForwarders = NULL;
MessageHandler* Unity::GameObject::s_MessageHandler = NULL;
GameObject::GameObject (MemLabelId label, ObjectCreationMode mode)
: Super(label, mode),
// m_Component (GameObject::Container::allocator_type (*baseAllocator)),
m_ActiveGONode (this)
{
m_SupportedMessages = 0;
m_IsDestroying = false;
m_IsActivating = false;
m_Tag = 0;
m_IsActive = false;
m_IsActiveCached = -1;
#if UNITY_EDITOR
m_IsOldVersion = false;
m_StaticEditorFlags = 0;
m_IsMarkedVisible = kSelfVisible;
#endif
}
void GameObject::Reset ()
{
Super::Reset ();
m_Layer = kDefaultLayer;
m_Tag = 0;
#if UNITY_EDITOR
m_StaticEditorFlags = 0;
m_TagString = TagToString (m_Tag);
m_NavMeshLayer = 0;
#endif
}
GameObject::~GameObject ()
{
Assert(!m_ActiveGONode.IsInList());
}
void GameObject::WillDestroyGameObject ()
{
Assert(!m_IsDestroying);
m_IsDestroying = true;
// Find a component with the requested ID
Container::const_iterator i;
Container::const_iterator end = m_Component.end ();
for (i=m_Component.begin ();i != end; ++i)
{
Component& com = *i->second;
com.WillDestroyComponent();
}
}
void GameObject::AwakeFromLoad(AwakeFromLoadMode awakeMode)
{
#if SUPPORT_LOG_ORDER_TRACE
if (IsActive() && RunningReproduction())
{
if (SUPPORT_LOG_ORDER_TRACE == 2)
{
LogString(Format("AwakeFromLoad %s (%s) [%d]", GetName(), GetClassName().c_str(), GetInstanceID()));
}
else
{
LogString(Format("AwakeFromLoad %s (%s)", GetName(), GetClassName().c_str()));
}
}
#endif
Super::AwakeFromLoad (awakeMode);
SetSupportedMessagesDirty ();
UpdateActiveGONode ();
if (s_SetGONameCallback)
s_SetGONameCallback(this);
#if UNITY_EDITOR
// When we are modifying the game object active state from the inspector
// We need to Activate / Deactivate the relevant components
// This never happens in the player.
if (awakeMode == kDefaultAwakeFromLoad)
ActivateAwakeRecursively();
#endif
}
int GameObject::CountDerivedComponents (int compareClassID)const
{
int count = 0;
Container::const_iterator i;
for (i=m_Component.begin ();i != m_Component.end (); ++i)
count += Object::IsDerivedFromClassID (i->first, compareClassID);
return count;
}
Component* GameObject::FindConflictingComponentPtr (int classID) const
{
const vector_set<int>& conflicts = FindConflictingComponents(classID);
if (conflicts.empty())
return NULL;
for (Container::const_iterator i = m_Component.begin(); i != m_Component.end(); ++i)
{
for (vector_set<int>::const_iterator c = conflicts.begin(); c != conflicts.end(); ++c)
{
if (Object::IsDerivedFromClassID(i->first, *c))
return i->second;
}
}
return NULL;
}
void GameObject::SetName (char const* name)
{
m_Name.assign(name, GetMemoryLabel());
if (s_SetGONameCallback)
s_SetGONameCallback(this);
SetDirty ();
}
void GameObject::UpdateActiveGONode()
{
m_ActiveGONode.RemoveFromList();
if (IsActive())
{
if (m_Tag != 0)
GetGameObjectManager().m_TaggedNodes.push_back(m_ActiveGONode);
else
GetGameObjectManager().m_ActiveNodes.push_back(m_ActiveGONode);
}
}
void GameObject::MarkActiveRecursively (bool state)
{
Transform &transform = GetComponent (Transform);
for (Transform::iterator i=transform.begin ();i != transform.end ();i++)
(*i)->GetGameObject().MarkActiveRecursively (state);
m_IsActive = state;
SetDirty();
}
void GameObject::ActivateAwakeRecursivelyInternal (DeactivateOperation deactivateOperation, AwakeFromLoadQueue &queue)
{
if (m_IsActivating)
{
ErrorStringObject("GameObject is already being activated or deactivated.", this);
return;
}
bool state;
bool changed;
m_IsActivating = true;
if (m_IsActiveCached != -1)
{
bool oldState = m_IsActiveCached;
m_IsActiveCached = -1;
state = IsActive();
changed = oldState != state;
}
else
{
state = IsActive();
changed = true;
}
Transform *transform = QueryComponent (Transform);
if (transform)
{
// use a loop by index rather than a iterator, as the children can adjust
// the child list during the Awake call, and invalidate the iterator
for (int i = 0; i < transform->GetChildrenCount(); i++)
transform->GetChild(i).GetGameObject().ActivateAwakeRecursivelyInternal (deactivateOperation, queue);
}
if (changed)
{
for (int i=0;i<m_Component.size ();i++)
{
Component& component = *m_Component[i].second;
if (state)
{
AssertIf (&*component.m_GameObject != this);
component.SetGameObjectInternal (this);
if (IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
queue.Add(*m_Component[i].second);
else
component.AwakeFromLoad (kActivateAwakeFromLoad);
}
else
component.Deactivate (deactivateOperation);
}
if (state)
UpdateActiveGONode ();
else
m_ActiveGONode.RemoveFromList();
}
m_IsActivating = false;
}
void GameObject::ActivateAwakeRecursively (DeactivateOperation deactivateOperation)
{
AwakeFromLoadQueue queue (kMemTempAlloc);
ActivateAwakeRecursivelyInternal (deactivateOperation, queue);
queue.AwakeFromLoad (kActivateAwakeFromLoad);
}
void GameObject::SetActiveRecursivelyDeprecated (bool state)
{
if (IS_CONTENT_NEWER_OR_SAME (kUnityVersion3_5_a1))
{
if (IsPrefabParent ())
{
ErrorString(Format("Prefab GameObject's can not be made active! (%s)", GetName()));
return;
}
// First Mark all objects as active
MarkActiveRecursively (state);
// Then awake them.
ActivateAwakeRecursively ();
}
else
{
// Old versions used to mark active and awake each object after another.
// That would cause problems with colliders being created twice, once without the active
// parent rigibdodies, and once with, thus causing the unnecessary creation and destruction
// of static colliders (slow). So we fixed it (see above), but we keep the old behaviour for
// legacy content.
Transform &transform = GetComponent (Transform);
for (Transform::iterator i=transform.begin ();i != transform.end ();i++)
(*i)->GetGameObject().SetActiveRecursivelyDeprecated (state);
if (state)
Activate();
else
Deactivate();
}
}
void GameObject::AddComponentInternal (Component* com)
{
AssertIf (com == NULL);
{
m_Component.push_back (std::make_pair (com->GetClassID (), ImmediatePtr<Component> (com)));
}
// Make sure it isn't already added to another GO
Assert ( com->m_GameObject.GetInstanceID() == 0 || com->GetGameObjectPtr() == this );
com->SetHideFlags(GetHideFlags());
com->m_GameObject = this;
if (IsActive ())
com->AwakeFromLoad (kActivateAwakeFromLoad);
else
com->AwakeFromLoad (kDefaultAwakeFromLoad);
com->SetDirty ();
SetDirty ();
SendMessage(kDidAddComponent, com, ClassID (Component));
SetSupportedMessagesDirty ();
}
Component* GameObject::QueryComponentExactTypeImplementation (int classID) const
{
// Find a component with the requested ID
Container::const_iterator i;
Container::const_iterator end = m_Component.end ();
for (i=m_Component.begin ();i != end; ++i)
{
if (i->first == classID)
return i->second;
}
return NULL;
}
Component* GameObject::QueryComponentImplementation (int classID) const
{
// Find a component with the requested ID
Container::const_iterator i;
Container::const_iterator end = m_Component.end ();
for (i=m_Component.begin ();i != end; ++i)
{
if (Object::IsDerivedFromClassID (i->first, classID))
return i->second;
}
return NULL;
}
void GameObject::RemoveComponentAtIndex (int index)
{
Container::iterator i = m_Component.begin () + index;
Component* com = i->second;
AssertIf (com == NULL);
m_Component.erase (i);
com->m_GameObject = NULL;
com->SetDirty ();
SetDirty ();
SetSupportedMessagesDirty ();
}
void GameObject::SetComponentAtIndexInternal (PPtr<Component> component, int index)
{
m_Component[index].first = component->GetClassID();
m_Component[index].second.SetInstanceID(component.GetInstanceID());
}
void GameObject::SetSupportedMessagesDirty ()
{
Assert(!IsDestroying());
int oldSupportedMessage = m_SupportedMessages;
m_SupportedMessages = 0;
if (IsDestroying ())
return;
GetSupportedMessagesRecalculate ();
if (oldSupportedMessage != m_SupportedMessages)
{
for (Container::iterator i=m_Component.begin ();i != m_Component.end (); ++i)
if (i->second)
i->second->SupportedMessagesDidChange (m_SupportedMessages);
}
}
void GameObject::GetSupportedMessagesRecalculate ()
{
Assert(!IsDestroying());
m_SupportedMessages = 0;
for (Container::iterator i=m_Component.begin ();i != m_Component.end (); ++i)
if (i->second)
m_SupportedMessages |= i->second->CalculateSupportedMessages ();
}
Component* GameObject::GetComponentPtrAtIndex (int i)const
{
return m_Component[i].second;
}
int GameObject::GetComponentIndex (Component *component)
{
Assert(!IsDestroying());
for (int i = 0; i < GetComponentCount (); i++)
{
if (&GetComponentAtIndex (i) == component)
return i;
}
return -1;
}
void GameObject::SwapComponents (int index1, int index2)
{
AssertIf (index1 > m_Component.size() || index1 < 0);
AssertIf (index2 > m_Component.size() || index2 < 0);
ComponentPair tmp = m_Component[index1];
m_Component[index1] = m_Component[index2];
m_Component[index2] = tmp;
Component* comp1 = m_Component[index1].second;
Component* comp2 = m_Component[index2].second;
if (comp1 && comp1->IsDerivedFrom(ClassID(Behaviour)))
{
Behaviour* beh = static_cast<Behaviour*>(comp1);
if (beh->GetEnabled())
{
beh->SetEnabled (false);
beh->SetEnabled (true);
}
}
if (comp2 && comp2->IsDerivedFrom(ClassID(Behaviour)))
{
Behaviour* beh = static_cast<Behaviour*>(comp2);
if (beh->GetEnabled())
{
beh->SetEnabled (false);
beh->SetEnabled (true);
}
}
SetDirty();
}
bool GameObject::IsActive () const
{
if (m_IsActiveCached != -1)
return m_IsActiveCached;
// For pre 4.0 content activate state is the same as m_IsActive.
if (!IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
m_IsActiveCached = m_IsActive;
else
{
// Calculate active state based on the hierarchy
m_IsActiveCached = m_IsActive && !(IsPersistent() || IsPrefabParent());
Transform *trs = QueryComponent (Transform);
if (trs)
{
Transform *parent = GetComponent (Transform).GetParent();
if (parent)
m_IsActiveCached = m_IsActiveCached && parent->GetGameObject().IsActive();
}
}
return m_IsActiveCached;
}
bool GameObject::IsActiveIgnoreImplicitPrefab ()
{
// This function does not make sense to be called for old content.
Assert (IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1));
Transform *trs = QueryComponent (Transform);
if (trs)
{
Transform *parent = GetComponent (Transform).GetParent();
if (parent)
return m_IsActive && parent->GetGameObject().IsActiveIgnoreImplicitPrefab();
}
return m_IsActive;
}
void GameObject::Activate ()
{
if (IsActive())
return;
PROFILER_AUTO(gActivateGameObjectProfiler, this);
SetDirty ();
if (IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
{
m_IsActive = true;
ActivateAwakeRecursively ();
// After AwakeFromLoad, 'this' could have been destroyed (if user is Destroying in OnEnable or Awake)
// So do not access it any further
}
else
{
if (IsPrefabParent ())
{
ErrorString(Format("Prefab GameObject's can not be made active! (%s)", GetName()));
return;
}
if (IS_CONTENT_NEWER_OR_SAME(kUnityVersion3_3_a1) && IsPersistent ())
{
ErrorString(Format("GameObjects stored in assets can not be made active! (%s)", GetName()));
return;
}
m_IsActive = true;
m_IsActiveCached = m_IsActive;
for (int i=0;i<m_Component.size ();i++)
{
Component& component = *m_Component[i].second;
AssertIf (&*component.m_GameObject != this);
component.m_GameObject = this;
component.AwakeFromLoad (kActivateAwakeFromLoad);
}
UpdateActiveGONode ();
}
}
void GameObject::Deactivate (DeactivateOperation operation)
{
PROFILER_AUTO(gDeactivateGameObjectProfiler, this)
if (!IsActive())
{
if (m_IsActive)
{
m_IsActive = false;
SetDirty ();
}
return;
}
m_IsActive = false;
if (IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
ActivateAwakeRecursively (operation);
else
{
m_IsActiveCached = m_IsActive;
for (int i=0;i<m_Component.size ();i++)
{
Component& com = *m_Component[i].second;
com.Deactivate (operation);
}
m_ActiveGONode.RemoveFromList();
}
SetDirty ();
}
void GameObject::SetSelfActive (bool state)
{
if (state)
Activate();
else
Deactivate(kNormalDeactivate);
}
void GameObject::AddComponentInternal (GameObject& gameObject, Component& clone)
{
SET_ALLOC_OWNER(&gameObject);
Assert(clone.m_GameObject == NULL);
gameObject.m_Component.push_back(make_pair(clone.GetClassID(), &clone));
clone.m_GameObject = &gameObject;
}
void GameObject::RemoveComponentFromGameObjectInternal (Component& clone)
{
GameObject* go = clone.GetGameObjectPtr();
if (go == NULL)
return;
int index = go->GetComponentIndex(&clone);
if (index == -1)
return;
go->m_Component.erase(go->m_Component.begin() + index);
clone.m_GameObject = NULL;
}
void GameObject::CheckConsistency ()
{
Super::CheckConsistency ();
// Remove Components from m_Component if they vanished without deactivating.
// (eg. class hierarchy changed and the class doesn't exist anymore when loading from disk)
int i = 0;
while (i < m_Component.size ())
{
// Use is object available instead of normal comparison so that we dont load the object
// which might already trigger the component to query for other components.
int CurComponentInstanceID = m_Component[i].second.GetInstanceID ();
if (!IsObjectAvailable (CurComponentInstanceID))
{
ErrorStringObject (Format("Component %s could not be loaded when loading game object. Cleaning up!", ClassIDToString(m_Component[i].first).c_str()), this);
m_Component.erase (m_Component.begin () + i);
}
else
i++;
}
// Preload all the components!
// This is necessary to avoid recursion and awake functions calling remove component,
// When we are removing the wrong ones anyway.
i = 0;
while (i < m_Component.size ())
{
Component* com = m_Component[i].second;
UNUSED(com);
i++;
}
// Remove Components with wrong gameobject ptrs
i = 0;
while (i < m_Component.size ())
{
Component* com = m_Component[i].second;
if (com && com->GetGameObjectPtr () == this)
{
i++;
continue;
}
if (com)
{
if (com->GetGameObjectPtr () == NULL)
{
com->SetGameObjectInternal (this);
ErrorStringObject ("Component (" + com->GetClassName () + ") has a broken GameObject reference. Fixing!", this);
continue;
}
else
{
ErrorStringObject ("Failed to load component (" + com->GetClassName () + ")! Removing it!", this);
com->SetHideFlags(kHideAndDontSave);
}
}
else
{
ErrorStringObject ("Failed to load component (" + Object::ClassIDToString (m_Component[i].first) + ")! Removing it!", this);
}
m_Component.erase (m_Component.begin () + i);
}
// make sure we always have at least one transform on a gameobject
int transformCount = 0;
for (int i = 0; i < m_Component.size (); ++i)
{
if(m_Component[i].first == ClassID (Transform))
transformCount++;
if (transformCount > 1)
{
// More than one transform on object. If it's a scene object (transient),
// remove the extraneous transform. For prefabs (persistent), touching the
// transform hierarchy will lead to all kinds of troubles so we just leave
// it be.
if (!IsPersistent ())
{
Transform* com = static_cast<Transform*> (&*m_Component[i].second);
com->SetParent (NULL);
RemoveComponentAtIndex (i);
--i;
GameObject* dummyObject = CreateObjectFromCode<GameObject> ();
dummyObject->SetName ("!! ORPHAN TRANSFORM !!");
dummyObject->AddComponentInternal (com);
ErrorStringObject ("Object has multiple transform components. Created dummy GameObject and added transform to it!", this);
}
else
{
ErrorStringObject ("Object has multiple transform components!", this);
}
}
}
if(transformCount == 0)
{
ErrorStringObject (Format("Transform component could not be found on game object. Adding one!"), this);
AddComponentUnchecked(*this,ClassID(Transform), NULL, NULL);
}
#if UNITY_EDITOR
if (m_IsOldVersion && m_IsActive && !IsPersistent() && !IsActiveIgnoreImplicitPrefab())
WarningStringObject ("GameObject is active but a parent is inactive. Active state is now inherited. Change the parenting to get back the old behaviour!", this);
#endif
SetSupportedMessagesDirty ();
}
void GameObject::SetLayer (int layer)
{
if (layer >= 0 && layer < 32)
{
m_Layer = layer;
MessageData data;
SendMessageAny (kLayerChanged, data);
SetDirty ();
}
else
ErrorString ("A game object can only be in one layer. The layer needs to be in the range [0...31]");
}
void GameObject::SetTag (UInt32 tag)
{
#if UNITY_EDITOR
m_TagString = TagToString (tag);
#endif
m_Tag = tag;
UpdateActiveGONode();
AssertIf (tag != -1 && tag != m_Tag);
AssertIf (tag == -1 && m_Tag != 0xFFFF);
MessageData data;
SendMessageAny (kLayerChanged, data);
SetDirty ();
}
void GameObject::SetHideFlags (int flags)
{
SetHideFlagsObjectOnly(flags);
for (int i=0;i<m_Component.size ();i++)
{
Component& com = *m_Component[i].second;
com.SetHideFlags(flags);
}
}
template<class TransferFunction>
void GameObject::TransferComponents (TransferFunction& transfer)
{
Container* components_to_serialize = &m_Component;
// When cloning objects for prefabs and instantiate, we don't use serialization to duplicate the hierarchy,
// we duplicate the hierarchy directly
if (!SerializePrefabIgnoreProperties(transfer))
return;
#if UNITY_EDITOR
Container filtered_components;
if (transfer.IsWritingGameReleaseData ())
{
components_to_serialize = &filtered_components;
for (Container::iterator i = m_Component.begin(); i != m_Component.end(); i++)
{
if (IsClassSupportedOnBuildTarget(i->first, transfer.GetBuildingTarget().platform))
filtered_components.push_back (*i);
}
}
#endif
transfer.Transfer (*components_to_serialize, "m_Component", kHideInEditorMask | kStrongPPtrMask | kIgnoreWithInspectorUndoMask);
}
template<class TransferFunction>
void GameObject::Transfer (TransferFunction& transfer)
{
Super::Transfer (transfer);
transfer.SetVersion (4);
TransferComponents(transfer);
TRANSFER (m_Layer);
#if GAMERELEASE
TransferConstantString(m_Name, "m_Name", kNoTransferFlags, GetMemoryLabel(), transfer);
TRANSFER (m_Tag);
transfer.Transfer (m_IsActive, "m_IsActive");
#else
#if UNITY_EDITOR
if (transfer.IsVersionSmallerOrEqual (3))
m_IsOldVersion = true;
#endif
if (transfer.IsOldVersion (3) || transfer.IsCurrentVersion ())
{
TransferConstantString(m_Name, "m_Name", kNoTransferFlags, GetMemoryLabel(), transfer);
if (transfer.IsSerializingForGameRelease ())
{
TRANSFER (m_Tag);
if (transfer.IsReading ())
m_TagString = TagToString (m_Tag);
transfer.Transfer (m_IsActive, "m_IsActive");
}
else
{
transfer.Transfer (m_TagString, "m_TagString");
if (transfer.IsReading ())
m_Tag = StringToTagAddIfUnavailable (m_TagString);
transfer.Transfer (m_Icon, "m_Icon", kNoTransferFlags);
transfer.Transfer (m_NavMeshLayer, "m_NavMeshLayer", kHideInEditorMask);
transfer.Transfer (m_StaticEditorFlags, "m_StaticEditorFlags", kNoTransferFlags | kGenerateBitwiseDifferences);
// Read deprecated static flag and set it up as m_StaticEditorFlags
if (transfer.IsReadingBackwardsCompatible ())
{
bool isStatic = false;
transfer.Transfer (isStatic, "m_IsStatic", kNoTransferFlags);
if (isStatic)
m_StaticEditorFlags = 0xFFFFFFFF;
}
transfer.Transfer (m_IsActive, "m_IsActive", kHideInEditorMask);
}
}
else if (transfer.IsOldVersion (2))
{
TRANSFER (m_TagString);
m_Tag = StringToTag (m_TagString);
transfer.Transfer (m_IsActive, "m_IsActive");
}
else if (transfer.IsOldVersion (1))
{
TRANSFER (m_Tag);
m_TagString = TagToString (m_Tag);
transfer.Transfer (m_IsActive, "m_IsActive");
}
#endif
// Make sure that old prefabs are always active.
if (transfer.IsVersionSmallerOrEqual (3) && IsPersistent() && IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
m_IsActive = true;
}
bool GameObject::GetIsStaticDeprecated ()
{
#if UNITY_EDITOR
return m_StaticEditorFlags != 0;
#else
return false;
#endif
}
void GameObject::SetIsStaticDeprecated(bool s)
{
#if UNITY_EDITOR
m_StaticEditorFlags = s ? 0xFFFFFFFF : 0;
SetDirty();
#endif
}
bool GameObject::IsStaticBatchable () const
{
#if UNITY_EDITOR
return AreStaticEditorFlagsSet (kBatchingStatic);
#else
return false;
#endif
}
#if UNITY_EDITOR
bool GameObject::AreStaticEditorFlagsSet (StaticEditorFlags flags) const
{
return (m_StaticEditorFlags & (UInt32)flags) != 0;
}
StaticEditorFlags GameObject::GetStaticEditorFlags () const
{
return (StaticEditorFlags)m_StaticEditorFlags;
}
void GameObject::SetStaticEditorFlags (StaticEditorFlags flags)
{
m_StaticEditorFlags = (UInt32)flags;
SetDirty();
}
void GameObject::SetIcon (PPtr<Texture2D> icon)
{
if (m_Icon != icon)
{
m_Icon = icon;
SetDirty ();
}
}
PPtr<Texture2D> GameObject::GetIcon () const
{
return m_Icon;
}
#endif
void GameObject::RegisterDestroyedCallback (DestroyGOCallbackFunction* callback)
{
s_GameObjectDestroyedCallback = callback;
}
void GameObject::InvokeDestroyedCallback (GameObject* go)
{
if (s_GameObjectDestroyedCallback)
s_GameObjectDestroyedCallback (go);
}
void GameObject::RegisterSetGONameCallback (SetGONameFunction* callback)
{
s_SetGONameCallback = callback;
}
static int GetHighestGOComponentClassID ()
{
static int highestGOComponentClassID = 0;
if (highestGOComponentClassID != 0)
return highestGOComponentClassID;
vector<SInt32> classes;
Object::FindAllDerivedClasses (ClassID (Component), &classes, false);
for (int i=0;i<classes.size ();i++)
highestGOComponentClassID = max<int> (highestGOComponentClassID, classes[i]);
return highestGOComponentClassID;
}
void GameObject::RegisterMessageHandler (int classID, const MessageIdentifier& messageIdentifier,
MessagePtr message, int typeId)
{
Assert(s_RegisteredMessageForwarders);
s_RegisteredMessageForwarders->resize (max(classID, GetHighestGOComponentClassID ()) + 1);
(*s_RegisteredMessageForwarders)[classID].RegisterMessageCallback (messageIdentifier.messageID, message, typeId);
}
void GameObject::RegisterAllMessagesHandler (int classID, MessagePtr message, CanHandleMessagePtr canHandleNotification)
{
Assert(s_RegisteredMessageForwarders);
s_RegisteredMessageForwarders->resize (max(classID, GetHighestGOComponentClassID ()) + 1);
(*s_RegisteredMessageForwarders)[classID].RegisterAllMessagesCallback (message, canHandleNotification);
}
static void PropagateNotificationsToDerivedClasses (MessageForwarders& notifications)
{
vector<SInt32> classes;
Object::FindAllDerivedClasses (ClassID (Object), &classes, false);
int highestClassID = 0;
for (unsigned i=0;i<classes.size ();i++)
highestClassID = max<int> (classes[i], highestClassID);
notifications.resize (highestClassID + 1);
for (int classID=0;classID<notifications.size ();classID++)
{
if (Object::ClassIDToRTTI (classID) == NULL)
continue;
int superClassID = Object::GetSuperClassID (classID);
while (superClassID != ClassID (Object))
{
notifications[classID].AddBaseMessages (notifications[superClassID]);
superClassID = Object::GetSuperClassID (superClassID);
}
}
}
void GameObject::InitializeMessageHandlers ()
{
Assert(s_MessageHandler && s_RegisteredMessageForwarders);
PropagateNotificationsToDerivedClasses (*s_RegisteredMessageForwarders);
s_MessageHandler->Initialize (*s_RegisteredMessageForwarders);
s_RegisteredMessageForwarders->clear ();
}
void GameObject::InitializeMessageIdentifiers ()
{
Assert(s_MessageHandler == NULL);
s_MessageHandler = UNITY_NEW(MessageHandler,kMemNewDelete);
s_RegisteredMessageForwarders = UNITY_NEW(MessageForwarders,kMemNewDelete);
GetMessageHandler ().InitializeMessageIdentifiers ();
}
void GameObject::InitializeClass ()
{
GameObjectManager::StaticInitialize();
}
void GameObject::CleanupClass ()
{
GameObjectManager::StaticDestroy();
UNITY_DELETE(s_MessageHandler,kMemNewDelete);
UNITY_DELETE(s_RegisteredMessageForwarders,kMemNewDelete);
}
bool CheckMessageDataType (int messageIdentifier, MessageData& data)
{
return GameObject::GetMessageHandler ().MessageIDToParameter (messageIdentifier) == data.type;
}
void GameObject::SendMessageAny (const MessageIdentifier& messageIdentifier, MessageData& messageData)
{
int messageID = messageIdentifier.messageID;
AssertIf (messageIdentifier.messageID == -1);
#if DEBUGMODE
if (!CheckMessageDataType (messageID, messageData))
AssertString ("The messageData sent has an incorrect type.");
#endif
for (int i=0;i<m_Component.size ();i++)
{
int classID = m_Component[i].first;
if (s_MessageHandler->HasMessageCallback (classID, messageID))
{
Component& component = *m_Component[i].second;
s_MessageHandler->HandleMessage (&component, classID, messageID, messageData);
}
}
}
bool GameObject::WillHandleMessage (const MessageIdentifier& messageIdentifier)
{
int messageID = messageIdentifier.messageID;
AssertIf (messageIdentifier.messageID == -1);
for (Container::iterator i=m_Component.begin ();i != m_Component.end ();i++)
{
int classID = i->first;
if (s_MessageHandler->HasMessageCallback (classID, messageID))
{
Component& component = *i->second;
if (s_MessageHandler->WillHandleMessage (&component, classID, messageID))
return true;
}
}
return false;
}
void GameObject::TransformParentHasChanged ()
{
// Reactivate transform hieararchy, but only if it has been activated before,
// otherwise we change activation order.
if (m_IsActiveCached != -1)
ActivateAwakeRecursively ();
}
void SendMessageDirect (Object& target, const MessageIdentifier& messageIdentifier, MessageData& messageData)
{
int classID = target.GetClassID();
if (GameObject::GetMessageHandler ().HasMessageCallback (classID, messageIdentifier.messageID))
{
GameObject::GetMessageHandler ().HandleMessage (&target, classID, messageIdentifier.messageID, messageData);
}
}
MessageHandler& GameObject::GetMessageHandler ()
{
Assert(s_MessageHandler);
return *s_MessageHandler;
}
char const* Component::GetName () const
{
if (m_GameObject)
return m_GameObject->m_Name.c_str();
else
return GetClassName().c_str();
}
void Component::SetName (char const* name)
{
if (m_GameObject)
m_GameObject->SetName (name);
}
Component::Component (MemLabelId label, ObjectCreationMode mode) : Super(label, mode)
{
m_GameObject = NULL;
}
Component::~Component ()
{
}
void Component::SendMessageAny (const MessageIdentifier& messageID, MessageData& messageData)
{
GameObject* go = GetGameObjectPtr ();
if (go)
go->SendMessageAny (messageID, messageData);
}
void Component::AwakeFromLoad (AwakeFromLoadMode awakeMode)
{
Super::AwakeFromLoad(awakeMode);
#if SUPPORT_LOG_ORDER_TRACE
if (IsActive() && RunningReproduction())
{
if (SUPPORT_LOG_ORDER_TRACE == 2)
{
LogString(Format("AwakeFromLoad %s (%s) [%d]", GetName(), GetClassName().c_str(), GetInstanceID()));
}
else
{
LogString(Format("AwakeFromLoad %s (%s)", GetName(), GetClassName().c_str()));
}
}
#endif
// Force load the game object. This is in order to prevent ImmediatePtrs not being dereferenced after loading.
// Which can cause a crash in Resources.UnloadUnusedAssets()
// Resources.Load used to store incorrect preload data which made this trigger.
GameObject* dereferenceGameObject = m_GameObject;
UNUSED(dereferenceGameObject);
}
template<class TransferFunction>
void Component::Transfer (TransferFunction& transfer)
{
Super::Transfer (transfer);
if (SerializePrefabIgnoreProperties(transfer))
transfer.Transfer (m_GameObject, "m_GameObject", kHideInEditorMask | kStrongPPtrMask | kIgnoreWithInspectorUndoMask);
}
void Component::CheckConsistency ()
{
Super::CheckConsistency ();
GameObject* go = GetGameObjectPtr ();
if (go)
{
for (int i = 0; i < go->GetComponentCount(); i++)
{
if (&go->GetComponentAtIndex(i) == this)
return;
}
ErrorStringObject (Format("CheckConsistency: GameObject does not reference component %s. Fixing.", GetClassName().c_str()), go);
go->AddComponentInternal (this);
}
// MonoBehaviours are allowed to exists without a game object
if (IsDerivedFrom(ClassID(Behaviour)))
{
return;
}
#if UNITY_EDITOR
if (m_GameObject == NULL)
{
GetCleanupManager ().MarkForDeletion (this, "GameObject pointer is invalid");
}
#endif
}
GameObjectManager* GameObjectManager::s_Instance = NULL;
void GameObjectManager::StaticInitialize()
{
Assert(GameObjectManager::s_Instance == NULL);
GameObjectManager::s_Instance = UNITY_NEW(GameObjectManager,kMemBaseObject);
}
void GameObjectManager::StaticDestroy()
{
Assert(GameObjectManager::s_Instance);
UNITY_DELETE(GameObjectManager::s_Instance,kMemBaseObject);
}
GameObjectManager& GetGameObjectManager()
{
Assert(GameObjectManager::s_Instance);
return *GameObjectManager::s_Instance;
}
IMPLEMENT_OBJECT_SERIALIZE (GameObject)
IMPLEMENT_OBJECT_SERIALIZE (Component)
IMPLEMENT_CLASS_HAS_INIT (GameObject)
IMPLEMENT_CLASS (Component)
INSTANTIATE_TEMPLATE_TRANSFER_EXPORTED(GameObject)
INSTANTIATE_TEMPLATE_TRANSFER_EXPORTED(Component)
}
// Hack to make register class work with name spaces. Optimally IMPLEMENT_CLASS / IMPLEMENT_OBJECT_SERIALIZE
// could be moved out of the namespace but that gives compile errors on gcc
void RegisterClass_Component () { Unity::RegisterClass_Component(); }
void RegisterClass_GameObject () { Unity::RegisterClass_GameObject(); }
|