CompareFieldValue.cs 2.2 KB

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