ObjectControl.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Reflection;
  3. using UnityEngine;
  4. using Object = UnityEngine.Object;
  5. using UnityEditor.UIElements;
  6. using UnityEngine.UIElements;
  7. namespace UnityEditor.ShaderGraph.Drawing.Controls
  8. {
  9. [AttributeUsage(AttributeTargets.Property)]
  10. class ObjectControlAttribute : Attribute, IControlAttribute
  11. {
  12. string m_Label;
  13. public ObjectControlAttribute(string label = null)
  14. {
  15. m_Label = label;
  16. }
  17. public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
  18. {
  19. return new ObjectControlView(m_Label, node, propertyInfo);
  20. }
  21. }
  22. class ObjectControlView : VisualElement
  23. {
  24. AbstractMaterialNode m_Node;
  25. PropertyInfo m_PropertyInfo;
  26. public ObjectControlView(string label, AbstractMaterialNode node, PropertyInfo propertyInfo)
  27. {
  28. if (!typeof(Object).IsAssignableFrom(propertyInfo.PropertyType))
  29. throw new ArgumentException("Property must be assignable to UnityEngine.Object.");
  30. m_Node = node;
  31. m_PropertyInfo = propertyInfo;
  32. label = label ?? propertyInfo.Name;
  33. if (!string.IsNullOrEmpty(label))
  34. Add(new Label {text = label});
  35. var value = (Object)m_PropertyInfo.GetValue(m_Node, null);
  36. var objectField = new ObjectField { objectType = propertyInfo.PropertyType, value = value };
  37. objectField.RegisterValueChangedCallback(OnValueChanged);
  38. Add(objectField);
  39. }
  40. void OnValueChanged(ChangeEvent<Object> evt)
  41. {
  42. var value = (Object)m_PropertyInfo.GetValue(m_Node, null);
  43. if (evt.newValue != value)
  44. {
  45. m_Node.owner.owner.RegisterCompleteObjectUndo("Change + " + m_Node.name);
  46. m_PropertyInfo.SetValue(m_Node, evt.newValue, null);
  47. }
  48. }
  49. }
  50. }