Home > Software design >  How to use GetComponent for inactive object?
How to use GetComponent for inactive object?

Time:10-03

I'm trying to use GetComponent for inactive gameObject which is called "Character":

 testingCollison test;
    void Start()
    {
      
        GameObject inter = GameObject.Find("Character");
        test = inter.GetComponent<testingCollison>();
}

but it is giving this error:

enter image description here

it is pointing to this line : test = inter.GetComponent<testingCollison>();

I tried replacing GetComponect with GetComponentInChildren as I found it as a solution when I looked up this issue, but it didn't make any difference.

How can I use getComponent of inactive object?

CodePudding user response:

GetComponent works on inactive GameObjects.

The GameObject.Find however can only return active GameObjects. Inactive GameObjects cannot be found.

Possible solutions:

  • Enable the GameObject (so it can found) but disable its components.
  • Pass the GameObject as reference from the editor inspector.
  • Save the GameObject reference in some intermediate active GameObject, and acquire through script.
  • Related