- Home /
How to initialize non-static field damage into string?
So I have a public int damage that I want to put into a string:
public int damage; public string dmgmsg = damage.ToString() + " hawks";
However I get this error message towards damage:
A field initializer cannot reference the nonstatic field, method, or property 'EnemyHealth.health'
My goal is to have a popup in game that displays enemy damage when attacked. I already set up the popup through TextMesh and it works perfectly with their text. I want to be able to change the text when the EnemyHealth.damage value changes, however. Is there a way to do this?
Answer by exploringunity · Jun 04, 2020 at 08:02 PM
Hey @ internallyx,
You can use the Start
lifecycle method to initialize your fields.
Example:
public class YourComponent : MonoBehaviour
{
public int damage; // I'm assuming you set this field in the Inspector
string dmgmsg;
void Start() {
dmgmsg = damage.ToString() + " hawks";
}
}
You can read more about the Start method here in the official Unity docs.
Answer by andrew-lukasik · Jun 04, 2020 at 08:15 PM
use OnValidate for initializing serialized fields:
#if UNITY_EDITOR
void OnValidate ()
{
dmgmsg = $"{damage} hawks";
}
#endif
Alternatively you can make it a property (method without arguments) i.e:
public string dmgmsg => $"{damage} hawks";
but it will allocate memory every time it's accessed, so OnValidate is better when string doesn't changes.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to count the number of strings in a string class? 2 Answers
Does Unity have a "Nice Name" method? 1 Answer
Most efficient way to convert string[] to int [] in C#? 2 Answers