SetFieldValue.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. using System;
  3. using System.Reflection;
  4. namespace BehaviorDesigner.Runtime.Tasks
  5. {
  6. [TaskDescription("Sets the field to the value specified. Returns success if the field was set.")]
  7. [TaskCategory("Reflection")]
  8. [TaskIcon("{SkinColor}ReflectionIcon.png")]
  9. public class SetFieldValue : Action
  10. {
  11. [Tooltip("The GameObject to set the field on")]
  12. public SharedGameObject targetGameObject;
  13. [Tooltip("The component to set the field on")]
  14. public SharedString componentName;
  15. [Tooltip("The name of the field")]
  16. public SharedString fieldName;
  17. [Tooltip("The value to set")]
  18. public SharedVariable fieldValue;
  19. public override TaskStatus OnUpdate()
  20. {
  21. if (fieldValue == null) {
  22. Debug.LogWarning("Unable to get field - field value is null");
  23. return TaskStatus.Failure;
  24. }
  25. var type = TaskUtility.GetTypeWithinAssembly(componentName.Value);
  26. if (type == null) {
  27. Debug.LogWarning("Unable to set 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 set 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. field.SetValue(component, fieldValue.GetValue());
  39. return TaskStatus.Success;
  40. }
  41. public override void OnReset()
  42. {
  43. targetGameObject = null;
  44. componentName = null;
  45. fieldName = null;
  46. fieldValue = null;
  47. }
  48. }
  49. }