How can I reference a script within a parent

Currently i made a small script to test functionality in another script called Health …this script resides within an EmptyGameobject named Health as well …if that makes sense…(Player/Health/Health)…Now the big problem is that this script is a players health in a multiplayer game …so its going to be instantiated allot with the same name,so i cant use the transform.find function because it wouldn’t know which to access…how can I reference the specific script called Health within the parent?


using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
	void OnGUI() {
	Transform HealthTransform;	
	HealthTransform = transform.FindChild("Health");
    Health health = HealthTransform.GetComponent<Health>();
		if (GUI.Button(new Rect(Screen.width / 1.5f,Screen.height/4,100,25),"Regain Health")) {
		if (GUI.Button(new Rect(Screen.width / 1.5f,Screen.height/4 + Screen.height/10,100,25),"Take Damage")) {
		if (GUI.Button(new Rect(Screen.width / 1.5f,Screen.height/4 + Screen.height/10 * 2,100,25),"Add Heart")) {

Some options:

  • Change your code so that the Health script is attached to the parent rather than a child object. You can then use GetComponent().
  • If the health script is part of a prefab, then declare a public variable of type ‘Health’ in script attached to the parent and drag and drop the child health game object onto the variable. When you instantiate the prefab, the link will get created as well.
  • There are a variety of ways to walk the hierarchy and find a component. One simple one is Component.GetComponentInChildren().

The best idea is to implement some kind of a manager class. Then you can register a player in it upon instantiation with some id (int or whatever). Also consider giving them different names then Find will work just fine. Another solution might be adding either another script on each player (along with Health) or just add a field id to the Health script. Then you also can identify required objects. Basically all these solutions just focus on creating something to identify objects.

I think you should rename the player and not the health.

Each time a new player is created, give him a number (like “player1”, “Player2” etc).

But you should probably rename the health like so: “Health/subHealth” or something, this is mostly for your ease of use.

But reagredless of the names, if your script sits on your player, then all you need to do is:

HealthTransform = transform.Find("Health/subHealth");

What you said here:

i cant use the transform.find function because it wouldn’t know which to access

Is not correct.

From the docs:


Finds a child by name and returns it.

meaning it will reference the child of the gameobject calling it and no other childs.