- Home /
Calling a script from other GameObject after finding it using OverlapSphere
I've just started scripting in Unity C#, and I am having problems calling a method on a gameobject from within another script on a different gameobject. Searched Google and these forums, but to be honest I'm not sure what I should be looking for in the first place.
I've got the player, a "Mother" of sorts, that can check the surrounding area for children that should then start following the mother character. When this call is made, CallChildren() is called. In CallChildren, I go through all found colliders in the sphere, and if the tag matches with "child" I try to call for a method (setFollowing()) inside a script that is assigned to that gameobject.
void CallChildren (Vector3 center, float radius) {
Collider[] hitColliders = Physics.OverlapSphere(center, radius);
int i = 0;
while (i < hitColliders.Length) {
print (hitColliders[i].gameObject.transform.name);
if (hitColliders[i].gameObject.transform.tag == "child") {
print ("Found a child!");
GameObject foundCollider = hitColliders[i].gameObject;
foundCollider.setFollowing(); // This is not working!
}
I am getting this error:
Assets/Scripts/Player/Script_Player_Controls.cs(98,47): error CS1061:
`Type
UnityEngine.GameObject' does not contain a definition for setFollowing' and no extension method
setFollowing' of type `UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?)
How can I call for the method I need to make the child object follow my player character? I guess GetComponent has something to do with this, but I have no idea how to use it here.
Answer by Stevenwithaph · Jul 29, 2013 at 05:14 PM
You're right about using GetComponent
foundCollider.GetComponent<ClassName>.setFollowing();
and replace ClassName with whatever the class name is for the children.
Thanks for the answer!
I tried this:
foundCollider.GetComponent<Script_Child_Follow>.startFollowing();
but got this error on the modified line: Assets/Scripts/Player/Script_Player_Controls.cs(98,47): error CS0119: Expression denotes a method group', where a
variable', value' or
type' was expected
Am I doing something wrong here?
foundCollider.GetComponent<Script_Child_Follow>().startFollowing();
You missed the () after <Script_Child_Follow>
since GetComponent is a generic method so it still requires the ().
Ah, that did it. I just copied and pasted the line in Steven's answer, and it didn't seem to have the () included. It's working now, thank you for the answers!
Your answer
![](https://koobas.hobune.stream/wayback/20220613111125im_/https://answers.unity.com/themes/thub/images/avi.jpg)