/
PrefabStage.cs
1958 lines (1669 loc) · 83.4 KB
/
PrefabStage.cs
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using UnityEditor.Callbacks;
using UnityEditor.IMGUI.Controls;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
namespace UnityEditor.Experimental.SceneManagement
{
// For the initial Improved Prefabs release we didn't have time to generalize the stage concept to also work
// for other things than main scenes and Prefabs. But it makes sense to use also for e.g. Avatar Setup.
// Until we have gone through the work of generalizing it by making e.g. Avatar Setup use it too,
// we're not confident that the API is right, hence it's experimental for now.
[Serializable]
public sealed partial class PrefabStage : PreviewSceneStage
{
static class Styles
{
public static GUIContent autoSaveGUIContent = EditorGUIUtility.TrTextContent("Auto Save", "When Auto Save is enabled, every change you make is automatically saved to the Prefab Asset. Disable Auto Save if you experience long import times.");
public static GUIContent saveButtonContent = EditorGUIUtility.TrTextContent("Save");
public static GUIContent checkoutButtonContent = EditorGUIUtility.TrTextContent("Check Out");
public static GUIContent autoSavingBadgeContent = EditorGUIUtility.TrTextContent("Auto Saving...");
public static GUIContent immutablePrefabContent = EditorGUIUtility.TrTextContent("Immutable Prefab");
public static GUIStyle saveToggle;
public static GUIStyle button;
public static GUIStyle savingBadge = "Badge";
public static GUIStyle exposablePopup = "ExposablePopupMenu";
public static GUIStyle exposablePopupItem = "ExposablePopupItem";
public static GUIContent contextLabel = EditorGUIUtility.TrTextContent("Context:");
public static GUIContent[] contextRenderModeTexts = new[] { EditorGUIUtility.TrTextContent("Normal"), EditorGUIUtility.TrTextContent("Gray"), EditorGUIUtility.TrTextContent("Hidden") };
public static StageUtility.ContextRenderMode[] contextRenderModeOptions = new[] { StageUtility.ContextRenderMode.Normal, StageUtility.ContextRenderMode.GreyedOut, StageUtility.ContextRenderMode.Hidden };
public static GUIContent showOverridesLabel = EditorGUIUtility.TrTextContent("Show Overrides", "Visualize overrides from the Prefab instance on the Prefab Asset. Overrides on the root Transform are always visualized.");
static Styles()
{
saveToggle = EditorStyles.toggle;
button = EditorStyles.miniButton;
button.margin.top = button.margin.bottom = 0;
}
}
public enum Mode
{
InIsolation,
InContext
}
public static event Action<PrefabStage> prefabStageOpened;
public static event Action<PrefabStage> prefabStageClosing;
public static event Action<PrefabStage> prefabStageDirtied;
public static event Action<GameObject> prefabSaving;
public static event Action<GameObject> prefabSaved;
internal static event Action<PrefabStage> prefabStageSavedAsNewPrefab;
internal static event Action<PrefabStage> prefabStageReloaded; // Used by tests.
internal static List<PrefabStage> m_AllPrefabStages = new List<PrefabStage>();
static StateCache<PrefabStageHierarchyState> s_StateCache = new StateCache<PrefabStageHierarchyState>("Library/StateCache/PrefabStageHierarchy/");
GameObject m_PrefabContentsRoot; // Prefab asset being edited
string m_PrefabAssetPath;
GameObject m_OpenedFromInstanceRoot;
GameObject m_OpenedFromInstanceObject;
ulong m_FileIdForOpenedFromInstanceObject;
Stage m_ContextStage = null;
Mode m_Mode;
int m_InitialSceneDirtyID;
int m_LastSceneDirtyID;
bool m_IgnoreNextAssetImportedEventForCurrentPrefab;
bool m_PrefabWasChangedOnDisk;
bool m_StageDirtiedFired;
bool m_IsPrefabInImmutableFolder;
bool m_IsPrefabInValidAssetFolder;
HideFlagUtility m_HideFlagUtility;
Texture2D m_PrefabFileIcon;
bool m_TemporarilyDisableAutoSave;
float m_LastSavingDuration = 0f;
Transform m_LastRootTransform;
const float kDurationBeforeShowingSavingBadge = 1.0f;
static ExposablePopupMenu s_ContextRenderModeSelector;
Hash128 m_LastPrefabSourceFileHash;
bool m_NeedsReloadingWhenReturningToStage;
bool m_IsAssetMissing;
[System.Serializable]
struct PatchedProperty
{
public PropertyModification modification;
public UnityEngine.Object targetInContent;
}
List<PatchedProperty> m_PatchedProperties;
bool m_AnalyticsDidUserModify;
bool m_AnalyticsDidUserSave;
internal static PrefabStage CreatePrefabStage(string prefabAssetPath, GameObject openedFromInstanceObject, PrefabStage.Mode prefabStageMode, Stage contextStage)
{
PrefabStage prefabStage = CreateInstance<PrefabStage>();
prefabStage.Init(prefabAssetPath, openedFromInstanceObject, prefabStageMode, contextStage);
return prefabStage;
}
// Used for tests, if nothing else.
internal static ReadOnlyCollection<PrefabStage> allPrefabStages { get { return m_AllPrefabStages.AsReadOnly(); } }
private PrefabStage()
{
}
void SetOpenedFromInstanceObject(GameObject go)
{
if (go != null)
{
if (!PrefabUtility.IsPartOfPrefabInstance(go))
throw new ArgumentException("GameObject must be part of a Prefab instance, or null.", nameof(go));
m_OpenedFromInstanceObject = go;
m_OpenedFromInstanceRoot = PrefabUtility.GetNearestPrefabInstanceRoot(go);
m_FileIdForOpenedFromInstanceObject = Unsupported.GetOrGenerateFileIDHint(go);
}
else
{
m_OpenedFromInstanceObject = null;
m_OpenedFromInstanceRoot = null;
m_FileIdForOpenedFromInstanceObject = 0;
}
}
void Init(string prefabAssetPath, GameObject openedFromInstanceGameObject, PrefabStage.Mode prefabStageMode, Stage contextStage)
{
m_PrefabAssetPath = prefabAssetPath;
CachePrefabFolderInfo();
SetOpenedFromInstanceObject(openedFromInstanceGameObject);
if (prefabStageMode == PrefabStage.Mode.InContext)
m_ContextStage = contextStage;
m_Mode = prefabStageMode;
}
void ReconstructDataIfNeeded()
{
bool needsReconstruction = m_OpenedFromInstanceObject == null && m_FileIdForOpenedFromInstanceObject != 0;
if (!needsReconstruction)
return;
// The previous PrefabStage can have been reloaded which means we need to update our reference to m_OpenedFromInstanceObject
// to the newly loaded GameObject (the old GameObject was deleted as part of reloading the PrefabStage).
var history = StageNavigationManager.instance.stageHistory;
int index = history.IndexOf(this);
int previousIndex = index - 1;
var previousStage = history[previousIndex];
var prevPrefabStage = previousStage as PrefabStage;
if (prevPrefabStage)
{
var go = PrefabStageUtility.FindFirstGameObjectThatMatchesFileID(prevPrefabStage.prefabContentsRoot.transform, m_FileIdForOpenedFromInstanceObject, true);
if (go != null)
{
SetOpenedFromInstanceObject(go);
}
else
{
Debug.LogError("Could not find GameObject with fileID " + m_FileIdForOpenedFromInstanceObject + " in PrefabStage for: " + prevPrefabStage.assetPath);
}
}
}
internal bool analyticsDidUserModify { get { return m_AnalyticsDidUserModify; } }
internal bool analyticsDidUserSave { get { return m_AnalyticsDidUserSave; } }
static class Icons
{
public static Texture2D prefabVariantIcon = EditorGUIUtility.LoadIconRequired("PrefabVariant Icon");
public static Texture2D prefabIcon = EditorGUIUtility.LoadIconRequired("Prefab Icon");
}
protected override void OnEnable()
{
base.OnEnable();
PrefabUtility.savingPrefab += OnSavingPrefab;
PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdated;
AssetEvents.assetsChangedOnHDD += OnAssetsChangedOnHDD;
Undo.undoRedoPerformed += UndoRedoPerformed;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
m_AllPrefabStages.Add(this);
}
protected override void OnDisable()
{
base.OnDisable();
PrefabUtility.savingPrefab -= OnSavingPrefab;
PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdated;
AssetEvents.assetsChangedOnHDD -= OnAssetsChangedOnHDD;
Undo.undoRedoPerformed -= UndoRedoPerformed;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
// Also cleanup any potential registered event handlers
EditorApplication.update -= DelayedFraming;
EditorApplication.update -= PerformDelayedAutoSave;
m_AllPrefabStages.Remove(this);
}
public GameObject prefabContentsRoot
{
get
{
if (m_PrefabContentsRoot == null)
throw new InvalidOperationException("Requesting 'prefabContentsRoot' from Awake and OnEnable is not supported"); // The Prefab stage's m_PrefabContentsRoot is not yet set when we call Awake and OnEnable on user scripts when loading a Prefab
return m_PrefabContentsRoot;
}
}
public GameObject openedFromInstanceRoot
{
get { return m_OpenedFromInstanceRoot; }
}
public GameObject openedFromInstanceObject
{
get { return m_OpenedFromInstanceObject; }
}
public Mode mode
{
get { return m_Mode; }
}
bool isCurrentStage
{
get { return StageUtility.GetCurrentStage() == this; }
}
public override ulong GetCombinedSceneCullingMaskForCamera()
{
if (m_Mode == Mode.InIsolation)
{
return GetSceneCullingMask();
}
else if (m_Mode == Mode.InContext)
{
var stageHistory = StageNavigationManager.instance.stageHistory;
if (this == stageHistory.Last())
{
ulong mask = GetSceneCullingMask();
int count = stageHistory.Count;
for (int i = count - 2; i >= 0; i--)
{
var stage = stageHistory[i];
if (stage)
{
mask |= stage.GetSceneCullingMask();
var prefabStage = stage as PrefabStage;
if (prefabStage)
{
if (prefabStage.mode != Mode.InContext)
break;
}
}
}
// Remove the MainStagePrefabInstanceObjectsOpenInPrefabMode bit from the camera's scenecullingmask. By removing that bit we ensure we hide the MainStage Prefab instance
// when editing its Prefab Asset in context. Since the MainStage Prefab instance GameObjects have the MainStagePrefabInstanceObjectsOpenInPrefabMode
// set when as override-scenecullingmask when entering Prefab Mode in Context for MainStage instances.
mask &= ~SceneCullingMasks.MainStagePrefabInstanceObjectsOpenInPrefabMode;
return mask;
}
else
{
Debug.LogError("We should only call GetOverrideSceneCullingMask() for the current stage");
return 0;
}
}
else
{
Debug.LogError("Unhandled PrefabStage.Mode");
return 0;
}
}
internal override Stage GetContextStage()
{
if (m_ContextStage != null)
return m_ContextStage;
return this;
}
internal override Color GetBackgroundColor() { return SceneView.kSceneViewPrefabBackground.Color; }
public bool IsPartOfPrefabContents(GameObject gameObject)
{
if (gameObject == null)
return false;
Transform tr = gameObject.transform;
Transform instanceRootTransform = prefabContentsRoot.transform;
while (tr != null)
{
if (tr == instanceRootTransform)
return true;
tr = tr.parent;
}
return false;
}
public override string assetPath { get { return m_PrefabAssetPath; } }
internal override bool SupportsSaving() { return true; }
internal override bool hasUnsavedChanges { get { return scene.dirtyID != m_InitialSceneDirtyID; } }
internal bool showingSavingLabel
{
get;
private set;
}
internal Texture2D prefabFileIcon
{
get { return m_PrefabFileIcon; }
}
string GetPrefabFileName()
{
return Path.GetFileNameWithoutExtension(m_PrefabAssetPath);
}
internal bool autoSave
{
get { return !m_TemporarilyDisableAutoSave && StageNavigationManager.instance.autoSave; }
set { m_TemporarilyDisableAutoSave = false; StageNavigationManager.instance.autoSave = value; }
}
internal bool temporarilyDisableAutoSave
{
get { return m_TemporarilyDisableAutoSave || isAssetMissing; }
}
internal override bool isValid
{
get { return m_PrefabContentsRoot != null && m_PrefabContentsRoot.scene == scene; }
}
internal override bool isAssetMissing
{
get { return m_IsAssetMissing; }
}
void OnPrefabInstanceUpdated(GameObject instance)
{
if (mode == Mode.InContext && m_OpenedFromInstanceRoot != null)
{
// We check against the outerMostInstanceRoot since that is what will be updated when
// we change that or any nested prefabs. E.g having PrefabA instance (that have nested PrefabB) in the Scene and we can enter
// Prefab Mode in Context for prefabB from the scene. Then adding a child; it will then be instanceA that will need to have
// its objects visibility updated.
var outerMostInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(m_OpenedFromInstanceRoot);
bool canHaveChangedCurrentlyHiddenObjects = outerMostInstanceRoot == instance;
if (canHaveChangedCurrentlyHiddenObjects)
{
SetPrefabInstanceHiddenForInContextEditing(true); // if new GameObjects was added to the instance this will ensure to mark them hidden as well
}
}
}
void SetPrefabInstanceHiddenForInContextEditing(bool hide)
{
// In Playmode all instances have been unpacked so we need to check if the PrefabInstanceHandle have been deleted
if (m_OpenedFromInstanceRoot != null && PrefabUtility.GetPrefabInstanceHandle(m_OpenedFromInstanceRoot) != null)
StageUtility.SetPrefabInstanceHiddenForInContextEditing(m_OpenedFromInstanceRoot, hide);
}
bool LoadStage()
{
ReconstructDataIfNeeded();
string prefabPath = m_PrefabAssetPath;
GameObject openedFromInstanceObject = m_OpenedFromInstanceObject;
Mode prefabStageMode = m_Mode;
Stage contextStage = m_ContextStage;
if (!File.Exists(prefabPath))
{
Debug.LogError("LoadStage with an invalid path: Prefab file not found " + prefabPath);
return false;
}
if (isValid)
Cleanup();
if (prefabStageMode == Mode.InContext && openedFromInstanceObject == null)
{
Debug.LogError("Invalid LoadStage state: InContext is specified but 'openedFromInstance' is null. This is invalid.");
return false;
}
Init(prefabPath, openedFromInstanceObject, prefabStageMode, contextStage);
// Ensure scene is set before calling LoadPrefabIntoPreviewScene() so the user can request the current
// the PrefabStage in their OnEnable and other callbacks (if they use ExecuteInEditMode or ExecuteAlways)
bool isUIPrefab = PrefabStageUtility.IsUIPrefab(m_PrefabAssetPath);
switch (m_Mode)
{
case Mode.InIsolation:
scene = PrefabStageUtility.GetEnvironmentSceneOrEmptyScene(isUIPrefab);
break;
case Mode.InContext:
scene = EditorSceneManager.NewPreviewScene();
break;
default:
Debug.LogError("Unhandled enum");
break;
}
m_PrefabContentsRoot = PrefabStageUtility.LoadPrefabIntoPreviewScene(prefabPath, scene);
if (m_PrefabContentsRoot != null)
{
if (isUIPrefab && m_Mode == Mode.InIsolation)
PrefabStageUtility.HandleReparentingIfNeeded(m_PrefabContentsRoot, true);
m_PrefabFileIcon = DeterminePrefabFileIconFromInstanceRootGameObject();
m_LastRootTransform = m_PrefabContentsRoot.transform;
m_InitialSceneDirtyID = scene.dirtyID;
m_StageDirtiedFired = false;
UpdateEnvironmentHideFlags();
if (m_Mode == Mode.InContext)
{
SetPrefabInstanceHiddenForInContextEditing(true);
Transform instanceParent = openedFromInstanceRoot.transform.parent;
if (instanceParent != null)
{
// Insert dummy parent which ensure Prefab contents is aligned same as Prefab instance.
GameObject dummyParent = new GameObject(PrefabUtility.kDummyPrefabStageRootObjectName);
EditorSceneManager.MoveGameObjectToScene(dummyParent, scene);
dummyParent.transform.SetParent(m_PrefabContentsRoot.transform.parent, false);
// Make Prefab content parent match alignment of Prefab instance parent.
// This code doesn't reliably handle cases where the parent matrix is non-orthogonal.
dummyParent.transform.localScale = instanceParent.lossyScale;
dummyParent.transform.rotation = instanceParent.rotation;
dummyParent.transform.position = instanceParent.position;
RectTransform instanceRectParent = instanceParent as RectTransform;
if (instanceRectParent != null)
{
RectTransform rect = dummyParent.AddComponent<RectTransform>();
rect.sizeDelta = instanceRectParent.rect.size;
rect.pivot = instanceRectParent.pivot;
Canvas dummyCanvas = dummyParent.AddComponent<Canvas>();
Canvas instanceCanvas = openedFromInstanceRoot.GetComponentInParent<Canvas>();
if (instanceCanvas != null)
{
dummyCanvas.sortingOrder = instanceCanvas.sortingOrder;
}
}
m_PrefabContentsRoot.transform.SetParent(dummyParent.transform, false);
}
}
}
else
{
// Invalid setup
Cleanup();
}
return isValid;
}
// Returns true if opened successfully
protected internal override bool OnOpenStage()
{
if (!isCurrentStage)
{
Debug.LogError("Only opening the current PrefabStage is supported. Please report a bug");
return false;
}
if (LoadStage())
{
if (mode == Mode.InContext)
{
RecordPatchedPropertiesForContent();
ApplyPatchedPropertiesToContent();
}
prefabStageOpened?.Invoke(this);
// Update environment scene objects after the 'prefabStageOpened' user callback so we can ensure: correct hideflags and
// that our prefab root is not under a prefab instance (which would mark it as an added object).
// Note: The user can have reparented and created new GameObjects in the environment scene during this callback.
EnsureParentOfPrefabRootIsUnpacked();
UpdateEnvironmentHideFlags();
UpdateLastPrefabSourceFileHashIfNeeded();
var sceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows();
foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows)
sceneHierarchyWindow.FrameObject(prefabContentsRoot.GetInstanceID(), false);
return true;
}
return false;
}
protected override void OnCloseStage()
{
if (isValid)
prefabStageClosing?.Invoke(this);
Cleanup();
}
protected internal override void OnReturnToStage()
{
if (m_NeedsReloadingWhenReturningToStage)
{
m_NeedsReloadingWhenReturningToStage = false;
if (m_Mode == Mode.InContext && m_OpenedFromInstanceObject == null)
{
// By clearing the contents root this stage becomes invalid which
// will be handled the StageNavigationManager by returning to the
// main stage
m_PrefabContentsRoot = null;
return;
}
ReloadStage();
}
}
bool HasPatchedPropertyModificationsFor(UnityEngine.Object obj, string partialPropertyName)
{
if (m_PatchedProperties == null)
return false;
foreach (var patchedProperty in m_PatchedProperties)
{
if (patchedProperty.targetInContent == obj && patchedProperty.modification.propertyPath.Contains(partialPropertyName))
return true;
}
return false;
}
internal bool ContainsTransformPrefabPropertyPatchingFor(GameObject[] gameObjects, string partialPropertyName)
{
if (gameObjects == null || gameObjects.Length == 0 || m_PatchedProperties == null)
return false;
for (int i = 0; i < gameObjects.Length; i++)
if (HasPatchedPropertyModificationsFor(gameObjects[i].transform, partialPropertyName))
return true;
return false;
}
void RecordPatchedPropertiesForContent()
{
m_PatchedProperties = new List<PatchedProperty>();
if (openedFromInstanceRoot == null)
return;
if (PrefabUtility.GetPrefabInstanceStatus(openedFromInstanceRoot) != PrefabInstanceStatus.Connected)
return;
Dictionary<ulong, UnityEngine.Object> contentObjectsFromFileID = new Dictionary<ulong, UnityEngine.Object>();
Dictionary<ulong, Transform> instanceTransformsFromFileID = new Dictionary<ulong, Transform>();
TransformVisitor visitor = new TransformVisitor();
visitor.VisitAll(prefabContentsRoot.transform, (transform, dict) => {
contentObjectsFromFileID[Unsupported.GetOrGenerateFileIDHint(transform.gameObject)] = transform.gameObject;
Component[] components = transform.GetComponents<Component>();
for (int i = components.Length - 1; i >= 0; i--)
{
if (components[i] == null)
continue;
contentObjectsFromFileID[Unsupported.GetOrGenerateFileIDHint(components[i])] = components[i];
}
}, null);
visitor.VisitAndAllowEarlyOut(openedFromInstanceRoot.transform, (transform, dict) => {
// If the GameObject is not hidden in the scene, it's not part of the Prefab instance
// that we're hiding because we're opening its Asset. That means it's not an object we
// should use as source for the patching of properties on the Prefab Asset content.
if (!StageUtility.IsPrefabInstanceHiddenForInContextEditing(transform.gameObject))
return false;
Transform assetTransform = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(transform, assetPath);
// Added GameObjects have no corresponding asset object
if (assetTransform != null)
instanceTransformsFromFileID[Unsupported.GetLocalIdentifierInFileForPersistentObject(assetTransform)] = transform;
return true;
}, null);
// Note: openedFromInstance is not necessarily a Prefab root, as it might be a nested Prefab.
List<GameObject> instanceAndCorrespondingObjectChain = new List<GameObject>();
GameObject prefabObject = openedFromInstanceRoot;
while (AssetDatabase.GetAssetPath(prefabObject) != assetPath)
{
Assert.IsTrue(PrefabUtility.IsPartOfPrefabInstance(prefabObject));
instanceAndCorrespondingObjectChain.Add(prefabObject);
prefabObject = PrefabUtility.GetCorrespondingObjectFromSource(prefabObject);
}
bool onlyPatchRootTransform = !s_PatchAllOverriddenProperties.value;
// Run through same objects, but from innermost out so outer overrides are applied last.
for (int i = instanceAndCorrespondingObjectChain.Count - 1; i >= 0; i--)
{
prefabObject = instanceAndCorrespondingObjectChain[i];
PropertyModification[] mods = PrefabUtility.GetPropertyModifications(prefabObject);
UnityEngine.Object lastTarget = null;
UnityEngine.Object lastTargetInContent = null;
SerializedObject lastInstanceTransformSO = null;
foreach (PropertyModification mod in mods)
{
if (mod.target == null)
continue;
if (onlyPatchRootTransform && !(mod.target is Transform))
continue;
UnityEngine.Object targetInContent = null;
SerializedObject instanceTransformSO = null;
// Optimization to avoid doing work to find matching object in Prefab contents
// for a target we already saw. Performs best if modifications are sorted by target.
if (mod.target == lastTarget)
{
targetInContent = lastTargetInContent;
instanceTransformSO = lastInstanceTransformSO;
}
else
{
targetInContent = null;
UnityEngine.Object targetInOpenAsset = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(mod.target, assetPath);
if (targetInOpenAsset != null)
{
ulong fileID = Unsupported.GetLocalIdentifierInFileForPersistentObject(targetInOpenAsset);
contentObjectsFromFileID.TryGetValue(fileID, out targetInContent);
Transform transform;
if (instanceTransformsFromFileID.TryGetValue(fileID, out transform))
{
instanceTransformSO = new SerializedObject(transform);
}
}
lastTarget = mod.target;
lastTargetInContent = targetInContent;
lastInstanceTransformSO = instanceTransformSO;
}
if (targetInContent != null)
{
// Don't patch root name, as Prefab Mode doesn't support changing that.
if (targetInContent == prefabContentsRoot && mod.propertyPath == "m_Name")
continue;
if (onlyPatchRootTransform && targetInContent != prefabContentsRoot.transform)
continue;
if (instanceTransformSO != null)
{
// If properties on a Prefab instance are driven, they are serialized as 0,
// which means their Prefab override values will be 0 as well.
// Patching over values of 0 for Prefab Mode in Context is no good,
// so get the actual current value from the instance instead.
PropertyModification modFromValue = instanceTransformSO.ExtractPropertyModification(mod.propertyPath);
if (modFromValue != null)
mod.value = modFromValue.value;
}
DrivenPropertyManager.TryRegisterProperty(this, targetInContent, mod.propertyPath);
m_PatchedProperties.Add(new PatchedProperty() { modification = mod, targetInContent = targetInContent });
}
}
}
// Apply patched properties from outer stage where applicable.
// This is so that changes that were patched when going in Prefab Mode in Context
// don't suddenly change when digging in deeper into nested Prefab or Variant bases.
var stageHistory = StageNavigationManager.instance.stageHistory;
int selfIndex = stageHistory.IndexOf(this);
if (selfIndex >= 1)
{
PrefabStage previous = stageHistory[selfIndex - 1] as PrefabStage;
if (previous != null && previous.mode == Mode.InContext && previous.m_PatchedProperties != null)
{
List<PatchedProperty> previousPatchedProperties = previous.m_PatchedProperties;
UnityEngine.Object lastTarget = null;
UnityEngine.Object lastTargetInContent = null;
for (int i = previousPatchedProperties.Count - 1; i >= 0; i--)
{
PatchedProperty patch = previousPatchedProperties[i];
PropertyModification mod = patch.modification;
if (mod.target == null)
continue;
UnityEngine.Object targetInContent = null;
if (mod.target == lastTarget)
{
targetInContent = lastTargetInContent;
}
else
{
targetInContent = null;
UnityEngine.Object targetInOpenAsset = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(mod.target, assetPath);
if (targetInOpenAsset != null)
{
ulong fileID = Unsupported.GetLocalIdentifierInFileForPersistentObject(targetInOpenAsset);
contentObjectsFromFileID.TryGetValue(fileID, out targetInContent);
}
lastTarget = mod.target;
lastTargetInContent = targetInContent;
}
if (targetInContent != null)
{
// Don't patch root name, as Prefab Mode doesn't support changing that.
// Root can be a different object than it was in outer Stage, så check again here.
if (targetInContent == prefabContentsRoot && mod.propertyPath == "m_Name")
continue;
// Root can be a different object than it was in outer Stage, så check again here.
if (onlyPatchRootTransform && targetInContent != prefabContentsRoot.transform)
continue;
DrivenPropertyManager.TryRegisterProperty(this, targetInContent, mod.propertyPath);
m_PatchedProperties.Add(new PatchedProperty() { modification = mod, targetInContent = targetInContent });
}
}
}
}
}
void ApplyPatchedPropertiesToContent()
{
if (m_PatchedProperties.Count == 0)
return;
for (int i = m_PatchedProperties.Count - 1; i >= 0; i--)
{
PropertyModification mod = m_PatchedProperties[i].modification;
UnityEngine.Object targetInContent = m_PatchedProperties[i].targetInContent;
mod.ApplyToObject(targetInContent);
// If GameObject.active is an override, applying the value via PropertyModification
// is not sufficient to actually change active state of the object,
// nor is calling AwakeFromLoad(kAnimationAwakeFromLoad) afterwards,
// so explicitly set it here.
GameObject targetGameObject = targetInContent as GameObject;
if (targetGameObject != null && mod.propertyPath == "m_IsActive")
targetGameObject.SetActive(mod.value != "0");
}
StageUtility.CallAwakeFromLoadOnSubHierarchy(m_PrefabContentsRoot);
}
void UndoRedoPerformed()
{
if (m_Mode == Mode.InContext)
{
ApplyPatchedPropertiesToContent();
}
}
void Cleanup()
{
if (m_Mode == Mode.InContext)
{
SetPrefabInstanceHiddenForInContextEditing(false);
}
if (m_PrefabContentsRoot != null && m_PrefabContentsRoot.scene != scene)
{
UnityEngine.Object.DestroyImmediate(m_PrefabContentsRoot);
}
if (scene.IsValid())
PrefabStageUtility.DestroyPreviewScene(scene); // Automatically deletes all GameObjects in scene
m_PrefabContentsRoot = null;
m_OpenedFromInstanceRoot = null;
m_OpenedFromInstanceObject = null;
m_HideFlagUtility = null;
m_PrefabAssetPath = null;
m_InitialSceneDirtyID = 0;
m_StageDirtiedFired = false;
m_LastSceneDirtyID = 0;
m_IgnoreNextAssetImportedEventForCurrentPrefab = false;
m_PrefabWasChangedOnDisk = false;
}
void ReloadStage()
{
if (SceneHierarchy.s_DebugPrefabStage)
Debug.Log("RELOADING Prefab at " + m_PrefabAssetPath);
if (!isCurrentStage)
{
Debug.LogError("Only reloading the current PrefabStage is supported. Please report a bug");
return;
}
var sceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows();
foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows)
SaveHierarchyState(sceneHierarchyWindow);
if (OnOpenStage())
{
foreach (SceneView sceneView in SceneView.sceneViews)
SyncSceneViewToStage(sceneView);
foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows)
{
SyncSceneHierarchyToStage(sceneHierarchyWindow);
LoadHierarchyState(sceneHierarchyWindow);
}
prefabStageReloaded?.Invoke(this);
}
if (SceneHierarchy.s_DebugPrefabStage)
Debug.Log("RELOADING done");
}
internal override void SyncSceneViewToStage(SceneView sceneView)
{
// The reason we need to set customScene even though we also set overrideSceneCullingMask is
// because the RenderSettings of the customScene is used to override lighting settings for this SceneView.
PrefabStage prefabStage = GetContextStage() as PrefabStage;
sceneView.customScene = prefabStage == null ? default(Scene) : prefabStage.scene;
sceneView.customParentForNewGameObjects = prefabContentsRoot.transform;
switch (mode)
{
case PrefabStage.Mode.InIsolation:
sceneView.overrideSceneCullingMask = 0;
break;
case PrefabStage.Mode.InContext:
sceneView.overrideSceneCullingMask = GetCombinedSceneCullingMaskForCamera();
break;
default:
Debug.LogError("Unhandled enum");
break;
}
}
internal override void SyncSceneHierarchyToStage(SceneHierarchyWindow sceneHierarchyWindow)
{
var sceneHierarchy = sceneHierarchyWindow.sceneHierarchy;
sceneHierarchy.customScenes = new[] { scene };
sceneHierarchy.customParentForNewGameObjects = prefabContentsRoot.transform;
sceneHierarchy.SetCustomDragHandler(PrefabModeDraggingHandler);
}
protected internal override void OnFirstTimeOpenStageInSceneView(SceneView sceneView)
{
// Default to scene view lighting if scene itself does not have any lights
if (!HasAnyActiveLights(scene))
sceneView.sceneLighting = false;
// Default to not showing skybox if user did not specify a custom environment scene.
if (string.IsNullOrEmpty(scene.path))
sceneView.sceneViewState.showSkybox = false;
// For UI to frame properly we need to delay one full Update for the layouting to have been processed
EditorApplication.update += DelayedFraming;
}
internal override void OnFirstTimeOpenStageInSceneHierachyWindow(SceneHierarchyWindow sceneHierarchyWindow)
{
var expandedIDs = new List<int>();
AddParentsBelowButIgnoreNestedPrefabsRecursive(prefabContentsRoot.transform, expandedIDs);
expandedIDs.Sort();
sceneHierarchyWindow.sceneHierarchy.treeViewState.expandedIDs = expandedIDs;
}
void AddParentsBelowButIgnoreNestedPrefabsRecursive(Transform transform, List<int> gameObjectInstanceIDs)
{
gameObjectInstanceIDs.Add(transform.gameObject.GetInstanceID());
int count = transform.childCount;
for (int i = 0; i < count; ++i)
{
var child = transform.GetChild(i);
if (child.childCount > 0 && !PrefabUtility.IsAnyPrefabInstanceRoot(child.gameObject))
{
AddParentsBelowButIgnoreNestedPrefabsRecursive(child, gameObjectInstanceIDs);
}
}
}
static DragAndDropVisualMode PrefabModeDraggingHandler(GameObjectTreeViewItem parentItem, GameObjectTreeViewItem targetItem, TreeViewDragging.DropPosition dropPos, bool perform)
{
var prefabStage = StageNavigationManager.instance.currentStage as PrefabStage;
if (prefabStage == null)
throw new InvalidOperationException("PrefabModeDraggingHandler should only be called in Prefab Mode");
// Disallow dropping as sibling to the prefab instance root (In Prefab Mode we only want to show one root).
if (parentItem != null && parentItem.parent == null && dropPos != TreeViewDragging.DropPosition.Upon)
return DragAndDropVisualMode.Rejected;
// Disallow dragging scenes into the hierarchy when it is in Prefab Mode (we do not support multi-scenes for prefabs yet)
foreach (var dragged in DragAndDrop.objectReferences)
{
if (dragged is SceneAsset)
return DragAndDropVisualMode.Rejected;
}
// Check for cyclic nesting (only on perform since it is an expensive operation)
if (perform)
{
var prefabAssetThatIsAddedTo = AssetDatabase.LoadMainAssetAtPath(prefabStage.assetPath);
foreach (var dragged in DragAndDrop.objectReferences)
{
if (dragged is GameObject && EditorUtility.IsPersistent(dragged))
{
var prefabAssetThatWillBeAdded = dragged;
if (PrefabUtility.CheckIfAddingPrefabWouldResultInCyclicNesting(prefabAssetThatIsAddedTo, prefabAssetThatWillBeAdded))
{
PrefabUtility.ShowCyclicNestingWarningDialog();
return DragAndDropVisualMode.Rejected;
}
}
}
}
return DragAndDropVisualMode.None;
}
static bool HasAnyActiveLights(Scene scene)
{
foreach (var gameObject in scene.GetRootGameObjects())
{
if (gameObject.GetComponentsInChildren<Light>(false).Length > 0)
return true;
}
return false;
}
int m_DelayCounter;
void DelayedFraming()
{
if (m_DelayCounter++ == 1)
{
EditorApplication.update -= DelayedFraming;
m_DelayCounter = 0;
// Frame the Prefab
Selection.activeGameObject = prefabContentsRoot;
foreach (SceneView sceneView in SceneView.sceneViews)
sceneView.FrameSelected(false, true);
}
}
internal override string GetErrorMessage()
{
if (m_PrefabContentsRoot == null)
return L10n.Tr("Error: The Prefab contents root has been deleted.\n\nPrefab: ") + m_PrefabAssetPath;
if (m_PrefabContentsRoot.scene != scene)
return L10n.Tr("Error: The root GameObject of the opened Prefab has been moved out of the Prefab Stage scene by a script.\n\nPrefab: ") + m_PrefabAssetPath;
return null;
}
protected internal override GUIContent CreateHeaderContent()
{
var label = Path.GetFileNameWithoutExtension(m_PrefabAssetPath);
var icon = AssetDatabase.GetCachedIcon(m_PrefabAssetPath);
return new GUIContent(label, icon);
}
internal override BreadcrumbBar.Item CreateBreadcrumbItem()
{
GUIContent content = CreateHeaderContent();
var history = StageNavigationManager.instance.stageHistory;
bool isLastCrumb = this == history.Last();
var style = isLastCrumb ? BreadcrumbBar.DefaultStyles.labelBold : BreadcrumbBar.DefaultStyles.label;
var separatorstyle = mode == Mode.InIsolation ? BreadcrumbBar.SeparatorStyle.Line : BreadcrumbBar.SeparatorStyle.Arrow;
if (isAssetMissing)
{
style = isLastCrumb ? BreadcrumbBar.DefaultStyles.labelBoldMissing : BreadcrumbBar.DefaultStyles.labelMissing;
content.tooltip = L10n.Tr("Prefab Asset has been deleted.");
}