AR Design
UBC EML collab with UBC SALA - visualizing IoT data in AR
SceneComponentAttribute.cs
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3 
4 using System;
5 using System.Reflection;
6 using UnityEngine;
7 #if UNITY_EDITOR
8 using UnityEditor;
9 #endif
10 
11 namespace HoloToolkit.Unity
12 {
13  // Displays a drop-down menu of Component objects that are limited to the scene (no prefabs)
14  [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
16  {
17  public string CustomLabel { get; private set; }
18 
19  public SceneComponentAttribute(string customLabel = null)
20  {
21  CustomLabel = customLabel;
22  }
23 
24 #if UNITY_EDITOR
25  public override void DrawEditor(UnityEngine.Object target, FieldInfo field, SerializedProperty property)
26  {
27  Component fieldValue = field.GetValue(target) as Component;
28  fieldValue = SceneObjectField(
29  SplitCamelCase(field.Name),
30  fieldValue,
31  field.FieldType);
32  field.SetValue(target, fieldValue);
33  }
34 
35  public override void DrawEditor(UnityEngine.Object target, PropertyInfo prop)
36  {
37  Component propValue = prop.GetValue(target, null) as Component;
38  propValue = SceneObjectField(
39  SplitCamelCase(prop.Name),
40  propValue,
41  prop.PropertyType);
42  prop.SetValue(target, propValue, null);
43  }
44 
45  public static Component SceneObjectField(string label, Component sceneObject, Type componentType)
46  {
47 
48  EditorGUILayout.BeginHorizontal();
49  if (string.IsNullOrEmpty(label))
50  {
51  sceneObject = (Component)EditorGUILayout.ObjectField(sceneObject, componentType, true);
52  }
53  else
54  {
55  sceneObject = (Component)EditorGUILayout.ObjectField(label, sceneObject, componentType, true);
56  }
57  if (sceneObject != null && sceneObject.gameObject.scene.name == null)
58  {
59  // Don't allow objects that aren't in the scene!
60  sceneObject = null;
61  }
62 
63  UnityEngine.Object[] objectsInScene = GameObject.FindObjectsOfType(componentType);
64  int selectedIndex = 0;
65  string[] displayedOptions = new string[objectsInScene.Length + 1];
66  displayedOptions[0] = "(None)";
67  for (int i = 0; i < objectsInScene.Length; i++)
68  {
69  displayedOptions[i + 1] = objectsInScene[i].name;
70  if (objectsInScene[i] == sceneObject)
71  {
72  selectedIndex = i + 1;
73  }
74  }
75  selectedIndex = EditorGUILayout.Popup(selectedIndex, displayedOptions);
76  if (selectedIndex == 0)
77  {
78  sceneObject = null;
79  }
80  else
81  {
82  sceneObject = (Component)objectsInScene[selectedIndex - 1];
83  }
84  EditorGUILayout.EndHorizontal();
85  return sceneObject;
86  }
87 #endif
88 
89  }
90 }