0

I have Unit gameObject which contains 2 subOnjects in it: Monster and HealthBar. Now Health has float - max_Health which I want to access using onTriggerEnter.

print(co.transform.GetChild(1)); 

Gives me "HealthBar" Which means I get correct subobject but now how can I get meaning of its float variable "max_Health" ?

I've tryied this:

print(co.transform.GetChild(1).transform.Find("max_Health"));

But got Null. That's wrong. How can I get it ?

print(co.transform.GetChild(1).Find("max_Health")); not working

print(co.transform.GetChild(1).Find("float max_Health")); not working.

What else can be done ??????

UPDATE

GameObject GG = GameObject.Find("GameObject co.transform.GetChild(1)");
Health bScript = GG.GetComponent<Health>();
print(bScript.max_Health);

gives me error

NullReferenceException: Object reference not set to an instance of an object
Tower.OnTriggerEnter (UnityEngine.Collider co) (at Assets/Scripts/Tower.cs:23)
David
  • 4,332
  • 13
  • 54
  • 93
  • 2
    Possible duplicate of [How to access a variable from another script in another gameobject through GetComponent?](http://stackoverflow.com/questions/26551575/how-to-access-a-variable-from-another-script-in-another-gameobject-through-getco) – Serlite Mar 01 '16 at 17:53
  • Tried that link. Didn't help – David Mar 01 '16 at 18:01
  • Your question does not show that you tried. I don't see GetComponent anywhere in your question. That is the correct way to do this, update your question to show what you tried with `GetComponent()`. – Scott Chamberlain Mar 01 '16 at 18:15
  • Probably I'm close but doing something wrong. As you can see I'm not pro with coding :) Can you check my last update ? – David Mar 01 '16 at 18:38
  • 1
    You shouldn't be using `Find()` at all in this case, if you can already access the GameObject's transform with `co.transform.GetChild(1)`. Just use `GetComponent()` with the results of `GetChild(1)`, like so: `co.transform.GetChild(1).GetComponent()` This will give you a reference to the `Health` script component on the child, so you can access any (public) variables/methods you have there. – Serlite Mar 01 '16 at 19:14
  • That worked thanks!!! – David Mar 01 '16 at 19:33
  • Great! If possible, could you click the Close link (it should be underneath the question) and mark the question to be closed on account of the aforementioned duplicate? Closing as duplicate can be very helpful for future readers, as it serves as a signpost towards solutions to common problems. – Serlite Mar 01 '16 at 19:41
  • Sure, will do! Thanks again! – David Mar 01 '16 at 19:42
  • hi @david could you click either Close or Delete on this question to close out the question and help keep the QA tidy, thanks – Fattie Mar 02 '16 at 13:42
  • Joe, I did hit close as Serlite told me. – David Mar 04 '16 at 21:32

0 Answers0