- Home /
String to Text Mesh Problem
I need help in projecting the health values which is in the playerMovement script to another game object which has a TextMesh. Health values is working fine, I have tested in GUI. But am not sure how to use that health values and pass it to the TextMesh [separate game object.]
playerMovement Script:
{
public int health;
void Start()
{ health = 100;
myTransform = transform;
myText = GetComponent<TextMesh>();
}
void FixedUpdate()
{
myText.GetComponent<TextMesh>().text = health.ToString();
}
public void DecreaseHealth(int n)
{
health-=n;
if(health<=0)Destroy(gameObject);
}
}
Well, first off, I believe doing myText.GetComponent() again in FixedUpdate is redundant.
You would get the desired result with just myText.text = health.toString();
that being said, i don't believe the problem lies there.
--Edit : Is your Text$$anonymous$$esh a component of the same game object attached with the script ?
Hi there, Thanks. Textmesh component is been attached to a different game object.
Answer by Chris_Dlala · Aug 15, 2014 at 09:50 PM
The quickest and easiest way to create an association between a script and a component is to add a [SerializedField] private
or public
field and drag in the component/object in the inspector.
[SerializedField] private TextMesh myText;
void FixedUpdate()
{
myText.text = health.ToString();
}
Other than that, @Jokim was right and calling GetComponent() every fixedUpdate is not a good idea, and you've already got the reference from Start.
You don't show what type of object myText
is. If it is a component or GameObject, make sure that the TextMesh is on the same object (in the same inspector as myText). If it is lower down the hierarchy you may want to use GetComponentInChildren()
. I hope that helps =D
Hi there, Thanks. I do researched about this fixed update, it seems as calling the text mesh via this method is expensive method. However, can you explain me the use for serialized field?
The Serialized field tag was just for the private declaration. As you probably already know, declaring a variable public in unity makes it show up in the inspector, and sometimes, you don't really want it to be public, but still want to show it up. The solution is to Add the [SerializedField] before (or above) the private field.
Thanks a lot for investing your time to help me out. I will check the unity file and also am planning to implement jump in that ball. So that can be done through this existing method right? Am little confused as it does not have gravity and if it is in top side of the tunnel how can i make an inexpensive system to implement jump?
Your answer
Follow this Question
Related Questions
Taking a hit 3 Answers
GUI SCREW UPS! 1 Answer
Deduct health on collision 2 Answers
Restart with GUIText 2 Answers
Gui Health Display Help! 1 Answer