- Home /
Unable to call another gameObject's script
I have some objects instantiated, I call on one of these object and try to access it's script but unity can't seems to find it.
The object has the script A. and one of the function is
class A(){
public void b(){
......
}
}
so I do,
class{
GameObject temp;
temp = ........, successfully retrieved the gameObject I want to work on,
temp.gameObject.GetComponents<A>().b(); //this doesnt work.
}
gives me the following error:
Assets/Scripts/colliders/LeftCollider.cs(42,88): error CS1061: Type A[]' does not contain a definition for
b' and no extension method hit' of type
A[]' could be found (are you missing a using directive or an assembly reference?)
I stripped down the code for simplicity. I've tried temp.GetComponents().b();//still no go, the logic behind this is that temp is already a gameObject.
I've also tried temp.gameObject.GetComponents;//monodevelope doesn't show red, but still get a compile error
Answer by MKayJay · Jul 06, 2014 at 03:32 PM
I think the problem is that you are using GetComponents (with an s) and not GetComponent.
Answer by Nick4 · Jul 06, 2014 at 03:35 PM
To access a specific method of a class you should use GetComponent() method not GetComponents(). Because GetComponents() returns an array of components of Type.
Answer by Kolodej · Jul 06, 2014 at 03:16 PM
Hi, class A must inherit from MonoBehaviour
class A : MonoBehaviour {
public B() { Debug.Log("Im doing B"); }
}
Answer by Kiwasi · Jul 06, 2014 at 02:31 AM
Those two little [] in the error message give the game away. Whatever code you are using to set temp is returning an array of GameObjects, not a single GameObject. In order to solve you can change the temp function to provide a single GameObject, or you can refer to individual GameObject using an index.
but game objects were stored in a queue, not a list. And when I destroy temp, it only destroy that objects, not all the objects.