Search Unity

Set property when an event triggers?

Discussion in 'Scripting' started by Shack_Man, Feb 17, 2021.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    Say I have a class that has a property, a float called health. It has a setter.

    Code (CSharp):
    1.     public float Health
    2.     {
    3.         set
    4.         {
    5.             health = value;
    6.         }
    7.     }

    Either in this class or I guess anywhere else, there is an event that sends out a float:

    Code (CSharp):
    1. public event Action<float> EventWithFloat;


    Can I somehow hook up calling the setter of the property to be called when that event is triggered? Without writing an extra method (that calls the property).

    So something like EventClass.EventWithFloat += Health;

    Thanks
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    There may be a way on higher levels of C# but I'm not aware of those.

    You can always just wrap it with a lambda:

    Code (csharp):
    1. EventWithFloat += (x) => { Health = x; };
     
    Shack_Man likes this.
  3. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    Awesome, that looks great. I saw a line similar to that in the official oculus quest scripts, there it looked like they stripped the variable from an event to subscribe a function to it that doesn't have any parameters.

    Once again thanks for help!
     
    Kurt-Dekker likes this.