BUG -> Health and Score are swapped

Hey I have an interesting bug, I have hooked up my Health and Score display scripts to the corresponding HealthText and ScoreText, however when clicking play they are reversed (The score text populates health and the health text populates score). I am assuming either occured when duplicating the text or the FindObjectOfType is simply grabbing the first Text reference it finds (as opposed to itself).

I suspect the latter and wanted to ask how you can explicitly program which Text to reference with FindObjectOfType

Is there a concept of “this” in C# / Unity?

Hi,

Your assumption is correct. Do not use FindObjectOfType if there are multiple objects of the type and if you need an reference of a component on a specific game object.

Unfortunately, that’s a bit of a problem in Unity. One approach is to add an individual script to the game object with the Text component, e.g. HealthDisplay to the game object with the health display text, and ScoreDisplay to the game object with the score display text. Both classes call GetComponent to look for a Text component on a specific game object. Alternatively, you could assign the reference manually. Look [SerializeField] up in the API if you don’t know it yet.

this. :wink:

However, it depends on which other programming languages you know. this does not have the same meaning in every programming language. In C#, it refers to the “current” instance.

I ended up using serializefield and attaching it manually but I feel there should be a way of doing it programatically

So thats what I currently have. A healthText with script HealthDisplay attached and a scoreText with script ScoreDisplay. The HealthDisplay script even though its attached to the healthText is updating the scoreText field. Should this not be happening? i.e. the Scope of FindObjectOfType is limited to the GameObject its script is attached to?

Oh I see what I did. I used FindObjectOfType instead of GetComponent :man_facepalming:

Thanks that makes way more sense to just call gameObject.GetComponent

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms