Access a script on a child on another gameobject in C#?
I'm trying to access a variable in a script which is located on a child on another gameobject. I've looked at both Transform.Find and GetcomponentsinChildren but I can't seem to get it to work. In the example below I'm trying to acces the float "bossHealth" which is located on a child of the Gameobject Boss (Clone). I first check whether the object exists or not before trying to set the bossHealth float to the local bossHealthGet float.
public Component bossScript;
private float bossHealthGet;
void OnGUI(){
if(GameObject.Find("Boss(Clone)") != null){
bossScript = GetComponentsInChildren<Boss_FloatingBehaviour>();
bossHealthGet = bossScript.bossHealth;}
}
Answer by cjdev · Sep 15, 2015 at 08:11 PM
The problem is when you call GetComponentsInChildren you're getting the Components of the GameObject the current script is attached to rather than the boss object you want to get them (or rather it) from. There is also a couple things about your code structure that might slow down your game due to performance reasons, the biggest being the cost of GameObject.Find, especially having it run every frame in OnGui. If you absolutely need to run it in realtime (as in your boss is instantiated sometime after Start) then try using a tag to look up the GameObject as it's a lot faster. Also, while bossScript is a Component it's type is the name of the class, Boss_FloatingBehaviour. If you were to use the Component type in the variable like that you would first have to cast it to it's type before using it.
To show what the code might look like with some fixes:
private GameObject boss;
private Boss_FloatingBehaviour bossScript;
private float bossHealthGet;
void OnGui()
{
//Having GameObject.FindObjectWithTag("Boss") would be faster here
boss = GameObject.Find("Boss(Clone)");
if (boss != null)
{
bossScript = boss.GetComponentInChildren<Boss_FloatingBehaviour>();
bossHealthGet = bossScript.bossHealth;
}
}
Answer by Suddoha · Sep 15, 2015 at 03:54 PM
The script shouldn't even compile as Unity's type Component doesn't have any clue about the methods and variables which are declared in your class. Your bossScript variable needs to be of type Boss_FloatingBehaviour.
Also, please don't put that into the OnGUI function. It's called way too often, usually even more often than Update and that's already a place where frequent calls of GameObject.Find and similar methods should be avoided.
Find the object once (in Start for example) or make a public variable with the type being GameObject or Boss_FloatingBehaviour and assign it via the inspector. Updating the variable can be done in Update or with some other mechanism.
Your answer
Follow this Question
Related Questions
Tag control 0 Answers
Value doesn't change in game when updated. 2 Answers
How do I shorten a gameObject.GetComponent 1 Answer
Adding components vs child 0 Answers