What is the difference between using GetComponent<> and GameObject.FindObjectOfType<>

Is there a specific situation to use GetComponent<> rather than GameObject.FindObjectOfType<>, or can these 2 statements be used interchangeably?

If anyone knows, please let me know.

1 Like

GetComponent<> is used to refer to another component (e.g. a Transform, a Rigidbody, an AudioSource, etc.) on the same GameObject as the script.

GameObject.FindObjectOfType<> is used to refer to a different GameObject in the scene.

2 Likes

I see that this is also covered in the next section.

While on this, how would you call a script that is not on any GameObject in the scene? Or would you have to create a Gameobject to which the called script is attached?

You don’t necessarily have to, but I’d say it usually makes sense to create a GameObject and attach a Monobehaviour to it. Otherwise, you can create normal C# classes and call them like in this example:
Simple class:

using UnityEngine;

public class MyClass
{
    int myInt = 5;

    public void printMyInt()
    {
        Debug.Log("Here is the value of myInt: " + myInt);
    }
}

Called from here:

using UnityEngine;

public class Test : MonoBehaviour
{
    MyClass myClass = new MyClass();

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            myClass.printMyInt();
        }
    }
}

Note that in this case you need to create an object of type MyClass with the new keyword. Otherwise you could make the printMyInt method static, in which case you could call it without creating an instance, like so:

MyClass.printMyInt();

This is what utility classes are (like Mathf, Input, etc.), basically a bunch of static functions you can call when you need them.

1 Like

Eureka…Great explanation. Thank you very much Sebastian.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms