Search Unity

Delegate/Action and Property Setter

Discussion in 'Scripting' started by Hikiko66, Dec 19, 2017.

  1. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304
    A Few questions

    1) How do I get a property setter to listen to an event?
    2) How do I setup another function to listen to a property setter?

    Naturally, when you try to specify a property as a method, it considers it a variable instead.

    I found a way to get the setter to listen to a UI event via CreateDelegate, but it is quite messy, and I assume there is a better way. I'm used to a much more simplified syntax for Actions/Events/Delegates, and pointing to regular methods, so I don't even really understand this. It feels like I have too many Actions/Delegates.
    Even the regular += -= sub unsub throws errors.
    Should I be using Action or UnityAction, or something else?

    Code (csharp):
    1.  
    2. //Get property info required to fetch the setter method
    3. PropertyInfo prop = managerObj.GetType().GetProperty("managerPropertyName");
    4.  
    5. //Create a Reference to the Setter of the property
    6. Action < string > setterReferenceMethod = (Action < string > )
    7. Delegate.CreateDelegate(typeof(Action < string > ), managerObj, prop.GetSetMethod());
    8.  
    9. //Cache the Action as method reference call with a value argument
    10. UnityAction < string > myUAct = delegate {
    11.     setterReferenceMethod(inpTitle.GetComponent < InputField > ().text);
    12. };
    13. //Can use the cache to sub/unsub
    14. inpTitle.GetComponent < InputField > ().onValueChanged.AddListener(myUAct);
    15. inpTitle.GetComponent < InputField > ().onValueChanged.RemoveListener(myUAct);
    16.  
     
    jeffersonrcgouveia likes this.