GetFieldValue.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using UnityEngine;
  2. using System;
  3. using System.Reflection;
  4. namespace BehaviorDesigner.Runtime.Tasks
  5. {
  6. [TaskDescription("Gets the value from the field specified. Returns success if the field was retrieved.")]
  7. [TaskCategory("Reflection")]
  8. [TaskIcon("{SkinColor}ReflectionIcon.png")]
  9. public class GetFieldValue : Action
  10. {
  11. [Tooltip("The GameObject to get the field on")]
  12. public SharedGameObject targetGameObject;
  13. [Tooltip("The component to get the field on")]
  14. public SharedString componentName;
  15. [Tooltip("The name of the field")]
  16. public SharedString fieldName;
  17. [Tooltip("The value of the field")]
  18. [RequiredField]
  19. public SharedVariable fieldValue;
  20. public override TaskStatus OnUpdate()
  21. {
  22. if (fieldValue == null) {
  23. Debug.LogWarning("Unable to get field - field value is null");
  24. return TaskStatus.Failure;
  25. }
  26. var type = TaskUtility.GetTypeWithinAssembly(componentName.Value);
  27. if (type == null) {
  28. Debug.LogWarning("Unable to get field - type is null");
  29. return TaskStatus.Failure;
  30. }
  31. var component = GetDefaultGameObject(targetGameObject.Value).GetComponent(type);
  32. if (component == null) {
  33. Debug.LogWarning("Unable to get the field with component " + componentName.Value);
  34. return TaskStatus.Failure;
  35. }
  36. // If you are receiving a compiler error on the Windows Store platform see this topic:
  37. // https://www.opsive.com/support/documentation/behavior-designer/installation/
  38. var field = component.GetType().GetField(fieldName.Value);
  39. fieldValue.SetValue(field.GetValue(component));
  40. return TaskStatus.Success;
  41. }
  42. public override void OnReset()
  43. {
  44. targetGameObject = null;
  45. componentName = null;
  46. fieldName = null;
  47. fieldValue = null;
  48. }
  49. }
  50. }