- Home /
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);
}
Answer by Serinx · Nov 06, 2014 at 08:28 PM
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
I didn't expect it to be so easy. After doing some "Googleresearch" I stumbled upon the Observer method. Which did not really seem that simple. Overcomplicated considering what I was asking.
I still need to understand the getter and setter a bit better! Thanks for your help, much appreciated.
Answer by timdan · Nov 06, 2014 at 08:46 PM
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
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Variable not showing update in inspector 2 Answers
How to use variable in MailMessage To? 1 Answer
Noob c# question 1 Answer