- Home /
How to have an instance only reference its parent
I'm trying to make a text box display the value of it's parent objects stats. The text box is attached to a sprite which has an attached script which tracks the stats of the sprite such as HP, damage, etc.
I created a standard singleton (as shown here) in the stat tracking script and reference it in the text box script to show the value of the sprite. This part works fine. However, when I create another sprite from the same prefab, both text boxes show the same value instead of only showing the value of its parent.
So if I have two sprites, one with 10 hp and one with 20 hp, both text boxes show 10hp or 20hp, when one should show 10 and one should show 20. How do I set the text box to only show the value of its parent? Can I still use a singleton for this or do I need another method?
I should also add that I've tried doing this without singletons and so far without any success.
Answer by Mmmpies · Dec 26, 2014 at 04:40 PM
Untested but when you add a child object to a parent its assigned a numbe child 0, child 1 and so on.
Now we can't see how you're storing the hp number but I'll guess a script called HP that holds a currentHP variable, if so and if the object your want to get the information from was the first child added then something like should work.
Text.text = parent.GetChild(0).GetComponent<HP>().currentHP.ToString();
This is in c#
If the sprite with the script attached is in the child added second change the 0 to 1.
Hope that makes sense but difficult to fit in with your code as you haven't given us an example.
Your answer
Follow this Question
Related Questions
moving child objects in hierarchy and keep stacks/sorting? Help needed 0 Answers
Change an object's grandparent 2 Answers
How do I fix this error when trying to use the Watson SDK for Speech to Text? 0 Answers
Create reference to Hierarchy objects that persists between different scene loads 2 Answers