FindObjectsOfType
How do I use Find Objects Of Type
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: PhotonConverter.cs
Copy
18 public static void RunConversion()
19 {
20 //Ask if user has made a backup.
21 int option = EditorUtility.DisplayDialogComplex("Conversion", "Attempt automatic conversion from Unity Networking to Photon Unity Networking \"PUN\"?", "Yes", "No!", "Pick Script Folder");
22 switch (option)
23 {
24 case 0:
25 break;
26 case 1:
27 return;
28 case 2:
29 PickFolderAndConvertScripts();
30 return;
31 default:
32 return;
33 }
34
35 //REAAAALY?
36 bool result = EditorUtility.DisplayDialog("Conversion", "Disclaimer: The code conversion feature is quite crude, but should do it's job well (see the sourcecode). A backup is therefore strongly recommended!", "Yes, I've made a backup: GO", "Abort");
37 if (!result)
38 {
39 return;
40 }
41 Output(EditorApplication.timeSinceStartup + " Started conversion of Unity networking -> Photon");
42
43 //Ask to save current scene (optional)
44 EditorApplication.SaveCurrentSceneIfUserWantsTo();
45
46 EditorUtility.DisplayProgressBar("Converting..", "Starting.", 0);
47
48 //Convert NetworkViews to PhotonViews in Project prefabs
49 //Ask the user if we can move all prefabs to a resources folder
50 bool movePrefabs = EditorUtility.DisplayDialog("Conversion", "Can all prefabs that use a PhotonView be moved to a Resources/ folder? You need this if you use Network.Instantiate.", "Yes", "No");
51
52
53 string[] prefabs = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
54 foreach (string prefab in prefabs)
55 {
56 EditorUtility.DisplayProgressBar("Converting..", "Object:" + prefab, 0.6f);
57
58 Object[] objs = (Object[])AssetDatabase.LoadAllAssetsAtPath(prefab);
59 int converted = 0;
60 foreach (Object obj in objs)
61 {
62 if (obj != null && obj.GetType() == typeof(GameObject))
63 converted += ConvertNetworkView(((GameObject)obj).GetComponents
64 }
65 if (movePrefabs && converted > 0)
66 {
67 //This prefab needs to be under the root of a Resources folder!
68 string path = prefab.Replace("\\", "/");
69 int lastSlash = path.LastIndexOf("/");
70 int resourcesIndex = path.LastIndexOf("/Resources/");
71 if (resourcesIndex != lastSlash - 10)
72 {
73 if (path.Contains("/Resources/"))
74 {
75 Debug.LogWarning("Warning, prefab [" + prefab + "] was already in a resources folder. But has been placed in the root of another one!");
76 }
77 //This prefab NEEDS to be placed under a resources folder
78 string resourcesFolder = path.Substring(0, lastSlash) + "/Resources/";
79 EnsureFolder(resourcesFolder);
80 string newPath = resourcesFolder + path.Substring(lastSlash + 1);
81 string error = AssetDatabase.MoveAsset(prefab, newPath);
82 if (error != "")
83 Debug.LogError(error);
84 Output("Fixed prefab [" + prefab + "] by moving it into a resources folder.");
85 }
86 }
87 }
88
89 //Convert NetworkViews to PhotonViews in scenes
90 string[] sceneFiles = Directory.GetFiles("Assets/", "*.unity", SearchOption.AllDirectories);
91 foreach (string sceneName in sceneFiles)
92 {
93 EditorApplication.OpenScene(sceneName);
94 EditorUtility.DisplayProgressBar("Converting..", "Scene:" + sceneName, 0.2f);
95
96 int converted2 = ConvertNetworkView((NetworkView[])GameObject.FindObjectsOfType(typeof(NetworkView)), true);
97 if (converted2 > 0)
98 {
99 //This will correct all prefabs: The prefabs have gotten new components, but the correct ID's were lost in this case
100 PhotonViewHandler.HierarchyChange(); //TODO: most likely this is triggered on change or on save
101
102 Output("Replaced " + converted2 + " NetworkViews with PhotonViews in scene: " + sceneName);
103 EditorApplication.SaveScene(EditorApplication.currentScene);
104 }
105
106 }
107
108 //Convert C#/JS scripts (API stuff)
109 List
110
111 EditorUtility.DisplayProgressBar("Converting..", "Scripts..", 0.9f);
112 ConvertScripts(scripts);
113
114 Output(EditorApplication.timeSinceStartup + " Completed conversion!");
115 EditorUtility.ClearProgressBar();
116
117 EditorUtility.DisplayDialog("Completed the conversion", "Don't forget to add \"PhotonNetwork.ConnectWithDefaultSettings();\" to connect to the Photon server before using any multiplayer functionality.", "OK");
118 }
File name: PhotonViewHandler.cs
Copy
25 internal static void HierarchyChange()
26 {
27 if (Application.isPlaying)
28 {
29 //Debug.Log("HierarchyChange ignored, while running.");
30 CheckSceneForStuckHandlers = true; // done once AFTER play mode.
31 return;
32 }
33
34 if (CheckSceneForStuckHandlers)
35 {
36 CheckSceneForStuckHandlers = false;
37 PhotonNetwork.InternalCleanPhotonMonoFromSceneIfStuck();
38 }
39
40 HashSet
41 HashSet
42 bool fixedSomeId = false;
43
44 //// the following code would be an option if we only checked scene objects (but we can check all PVs)
45 //PhotonView[] pvObjects = GameObject.FindSceneObjectsOfType(typeof(PhotonView)) as PhotonView[];
46 //Debug.Log("HierarchyChange. PV Count: " + pvObjects.Length);
47
48 string levelName = Application.loadedLevelName;
49 #if UNITY_EDITOR
50 levelName = System.IO.Path.GetFileNameWithoutExtension(EditorApplication.currentScene);
51 #endif
52 int minViewIdInThisScene = PunSceneSettings.MinViewIdForScene(levelName);
53 //Debug.Log("Level '" + Application.loadedLevelName + "' has a minimum ViewId of: " + minViewIdInThisScene);
54
55 PhotonView[] pvObjects = Resources.FindObjectsOfTypeAll(typeof(PhotonView)) as PhotonView[];
56
57 foreach (PhotonView view in pvObjects)
58 {
59 // first pass: fix prefabs to viewID 0 if they got a view number assigned (cause they should not have one!)
60 if (EditorUtility.IsPersistent(view.gameObject))
61 {
62 if (view.viewID != 0 || view.prefixBackup != -1 || view.instantiationId != -1)
63 {
64 Debug.LogWarning("PhotonView on persistent object being fixed (id and prefix must be 0). Was: " + view);
65 view.viewID = 0;
66 view.prefixBackup = -1;
67 view.instantiationId = -1;
68 EditorUtility.SetDirty(view);
69 fixedSomeId = true;
70 }
71 }
72 else
73 {
74 // keep all scene-instanced PVs for later re-check
75 pvInstances.Add(view);
76 }
77 }
78
79 Dictionary
80
81 // second pass: check all used-in-scene viewIDs for duplicate viewIDs (only checking anything non-prefab)
82 // scene-PVs must have user == 0 (scene/room) and a subId != 0
83 foreach (PhotonView view in pvInstances)
84 {
85 if (view.ownerId > 0)
86 {
87 Debug.Log("Re-Setting Owner ID of: " + view);
88 }
89 view.ownerId = 0; // simply make sure no owner is set (cause room always uses 0)
90 view.prefix = -1; // TODO: prefix could be settable via inspector per scene?!
91
92 if (view.viewID != 0)
93 {
94 if (view.viewID < minViewIdInThisScene || usedInstanceViewNumbers.Contains(view.viewID))
95 {
96 view.viewID = 0; // avoid duplicates and negative values by assigning 0 as (temporary) number to be fixed in next pass
97 }
98 else
99 {
100 usedInstanceViewNumbers.Add(view.viewID); // builds a list of currently used viewIDs
101
102 int instId = 0;
103 if (idPerObject.TryGetValue(view.gameObject, out instId))
104 {
105 view.instantiationId = instId;
106 }
107 else
108 {
109 view.instantiationId = view.viewID;
110 idPerObject[view.gameObject] = view.instantiationId;
111 }
112 }
113 }
114
115 }
116
117 // third pass: anything that's now 0 must get a new (not yet used) ID (starting at 0)
118 int lastUsedId = (minViewIdInThisScene > 0) ? minViewIdInThisScene - 1 : 0;
119
120 foreach (PhotonView view in pvInstances)
121 {
122 if (view.viewID == 0)
123 {
124 // Debug.LogWarning("setting scene ID: " + view.gameObject.name + " ID: " + view.subId.ID + " scene ID: " + view.GetSceneID() + " IsPersistent: " + EditorUtility.IsPersistent(view.gameObject) + " IsSceneViewIDFree: " + IsSceneViewIDFree(view.subId.ID, view));
125 int nextViewId = PhotonViewHandler.GetID(lastUsedId, usedInstanceViewNumbers);
126
127 view.viewID = nextViewId;
128
129 int instId = 0;
130 if (idPerObject.TryGetValue(view.gameObject, out instId))
131 {
132 Debug.Log("Set inst ID");
133 view.instantiationId = instId;
134 }
135 else
136 {
137 view.instantiationId = view.viewID;
138 idPerObject[view.gameObject] = nextViewId;
139 }
140
141 //// when using the Editor's serialization (view.subId in this case), this is not needed, it seems
142 //PrefabUtility.RecordPrefabInstancePropertyModifications(view);
143
144 lastUsedId = nextViewId;
145 EditorUtility.SetDirty(view);
146 fixedSomeId = true;
147 }
148 }
149
150
151 if (fixedSomeId)
152 {
153 //Debug.LogWarning("Some subId was adjusted."); // this log is only interesting for Exit Games
154 }
155 }
File name: NetworkingPeer.cs
Copy
2663 public PhotonView GetPhotonView(int viewID)
2664 {
2665 PhotonView result = null;
2666 this.photonViewList.TryGetValue(viewID, out result);
2667
2668 if (result == null)
2669 {
2670 PhotonView[] views = GameObject.FindObjectsOfType(typeof(PhotonView)) as PhotonView[];
2671
2672 foreach (PhotonView view in views)
2673 {
2674 if (view.viewID == viewID)
2675 {
2676 if (view.didAwake)
2677 {
2678 Debug.LogWarning("Had to lookup view that wasn't in photonViewList: " + view);
2679 }
2680 return view;
2681 }
2682 }
2683 }
2684
2685 return result;
2686 }
File name: PhotonNetwork.cs
Copy
479 public static HashSet480 {
481 HashSet
482
483 Component[] targetComponents = (Component[]) GameObject.FindObjectsOfType(type);
484 for (int index = 0; index < targetComponents.Length; index++)
485 {
486 objectsWithComponent.Add(targetComponents[index].gameObject);
487 }
488
489 return objectsWithComponent;
490 }
File name: PhotonNetwork.cs
Copy
974 static PhotonNetwork()
975 {
976 #if UNITY_EDITOR
977 if (!EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode)
978 {
979 //Debug.Log(string.Format("PhotonNetwork.ctor() Not playing {0} {1}", UnityEditor.EditorApplication.isPlaying, UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode));
980 return;
981 }
982
983 // This can happen when you recompile a script IN play made
984 // This helps to surpress some errors, but will not fix breaking
985 PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[];
986 if (photonHandlers != null && photonHandlers.Length > 0)
987 {
988 Debug.LogWarning("Unity recompiled. Connection gets closed and replaced. You can connect as 'new' client.");
989 foreach (PhotonHandler photonHandler in photonHandlers)
990 {
991 //Debug.Log("Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject);
992 photonHandler.gameObject.hideFlags = 0;
993 GameObject.DestroyImmediate(photonHandler.gameObject);
994 Component.DestroyImmediate(photonHandler);
995 }
996 }
997 #endif
998
999 Application.runInBackground = true;
1000
1001 // Set up a MonoBehaviour to run Photon, and hide it
1002 GameObject photonGO = new GameObject();
1003 photonMono = (PhotonHandler)photonGO.AddComponent
1004 photonGO.name = "PhotonMono";
1005 photonGO.hideFlags = HideFlags.HideInHierarchy;
1006
1007
1008 // Set up the NetworkingPeer and use protocol of PhotonServerSettings
1009 networkingPeer = new NetworkingPeer(photonMono, string.Empty, PhotonNetwork.PhotonServerSettings.Protocol);
1010
1011
1012 // Local player
1013 CustomTypes.Register();
1014 }
File name: PhotonNetwork.cs
Copy
1072 public static void InternalCleanPhotonMonoFromSceneIfStuck()
1073 {
1074 PhotonHandler[] photonHandlers = GameObject.FindObjectsOfType(typeof(PhotonHandler)) as PhotonHandler[];
1075 if (photonHandlers != null && photonHandlers.Length > 0)
1076 {
1077 Debug.Log("Cleaning up hidden PhotonHandler instances in scene. Please save it. This is not an issue.");
1078 foreach (PhotonHandler photonHandler in photonHandlers)
1079 {
1080 // Debug.Log("Removing Handler: " + photonHandler + " photonHandler.gameObject: " + photonHandler.gameObject);
1081 photonHandler.gameObject.hideFlags = 0;
1082
1083 if (photonHandler.gameObject != null && photonHandler.gameObject.name == "PhotonMono")
1084 {
1085 GameObject.DestroyImmediate(photonHandler.gameObject);
1086 }
1087
1088 Component.DestroyImmediate(photonHandler);
1089 }
1090 }
1091 }
File name: ShowInfoOfPlayer.cs
Copy
20 void Start()
21 {
22 if (font == null)
23 {
24 #if UNITY_3_5
25 font = (Font)FindObjectsOfTypeIncludingAssets(typeof(Font))[0];
26 #else
27 font = (Font)Resources.FindObjectsOfTypeAll(typeof(Font))[0];
28 #endif
29 Debug.LogWarning("No font defined. Found font: " + font);
30 }
31
32 if (tm == null)
33 {
34 textGo = new GameObject("3d text");
35 //textGo.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
36 textGo.transform.parent = this.gameObject.transform;
37 textGo.transform.localPosition = Vector3.zero;
38
39 MeshRenderer mr = textGo.AddComponent
40 mr.material = font.material;
41 tm = textGo.AddComponent
42 tm.font = font;
43 tm.anchor = TextAnchor.MiddleCenter;
44 if (this.CharacterSize > 0)
45 {
46 tm.characterSize = this.CharacterSize;
47 }
48 }
49 }
FindObjectsOfType 131 lượt xem
Gõ tìm kiếm nhanh...