Call a method whenever the assigned variable gets altered

Hello! I am working with damage numbers (and health pickups) to be shown on screen. I have the code working to show me the number with a juicy random instantiate and a delayed fade. So, I don’t need any help with the text mesh instantiation itself. What I want to know, is if I can call my “TakeDamage()” method, which contains my DamageNumber text mesh assignment every time the enemy takes any form of damage? The last sentence would logically be something like:

//Whenever curhp gets reduced, call TakeDamage();

here is some visual aiding code to help you understand what I’m looking for:

    public float curhp;
	public float hpLost;

      void Update () {
         //if curhp altered: call TakeDamage()
         //the variable "hpLost" is assigned damage through other scripts,
         //in case you were wondering
      }

      void TakeDamage() {
		objectSpeed = 60f;
		Vector2 randomDirection = Random.insideUnitCircle * objectSpeed;
		GameObject dicks = Instantiate(textMeshObject,transform.position,Quaternion.identity) as GameObject;
		
		TextMesh text = (TextMesh)dicks.GetComponent(typeof(TextMesh));
		text.text = "-" + hpLost.ToString();
		dicks.rigidbody2D.AddRelativeForce(randomDirection);
	}

You can use Properties or “Getters and Setters” to achieve this.

The syntax is as follows:

    private float curhp;
    
    //Curhp is a basic property
    public float Curhp
    {
        get
        {
            //Some other code
            return curhp;
        }
        set
        {
            TakeDamage();
            curhp = value;
        }
    }

For your scenario I think you would only want to call TakeDamage in the set.

References:

http://unity3d.com/learn/tutorials/modules/intermediate/scripting/properties

Create a variable called lasthp, and give it the value of carhop at the end of every update. You can then use it to check to see if curhp has changed since the last frame. (I’m also assuming you have a way of updating “curshp” as I didn’t notice it in your code.

Like such:


public float curhp;
public float lasthp;
public float hpLost;

void Update ()
{
   if(curhp < lasthp)
      TakeDamage();

   lasthp = curhp
}

//Rest of your code here from example