I want to use a couple of Texts in my scene (to display Name, Lives… etc).I am trying to initialize these texts like this:
private TextMeshProUGUI _HUDtext;
public void InitHUD() {
result=...;
_HUDtext = FindObjectOfType<TextMeshProUGUI>();
setCharacterHUD(result);
setLivesHUD();
}
private void setCharacterHUD(string result)
{
if (_HUDtext.tag == "ScannedCharacter") {
print("1");
_HUDtext.text += "
" + result;
}
}
private void setLivesHUD()
{
if (_HUDtext.tag == "Lives") {
print("2"); // the code will never reach this print
_HUDtext.text += livesNumber.ToString();
}
}
but this will only initialize the text with tag ScannedCharacter
, the code will never enter on 2
. Anyone knows why?
I’ve assumed that this is a script that you’ve attached to each instance of your textmeshpro text (so my answer might need rewording if that’s wrong!) :
The issue here is that FindObjectOfType will look at ALL loaded objects of the type you specify, not just the objects attached to the gameobject this script is on. This would explain why they’re all returning the same text component.
What you probably want to be using it GetComponent as this will look for components that are attached to the same gameobject as the script from which you call it. If the text component is on a gameobject below the one this script is attached to then you can use GetComponentInChildren.
Each of these functions have no set definition regarding which single object they find IF many of them exist - or at least you shouldn’t use these if you think it could return any one of many. So if you’re dealing with multiple text components on or below a gameobject then use GetComponents and then you can either look through that array to find the right one or deal with them all one-by-one.
Let me know if you need any clarification!