Unity: How to get a script from a GameObject

Date: 2020-04-08 | csharp | gameobject | unity |

DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)

problem

I'm building my new mobile game, coffeedash, and need to get a script from a GameObject in my scene. How can I get a script off a GameObject in Unity?

solution

To get a script off a GameObject, you can use the GetComponent method.

Let's say I have a GameObject in my scene called ExampleObject and then I have a script called ExampleScript attached to it. To get these from my scene in C# code, you could do something like:

public class TutorialClass : MonoBehaviour {
    void Update() {
        var foundObject = GameObject.Find("ExampleObject");
        var foundScript = foundObject.GetComponent<ExampleScript>();

        // do stuff with your object and script
    }
}

Now you likely won't want to keep using the Find and GetComponent functions in Update as that's called on every frame and those are relatively expensive, but hopefully that gets the point across.

Want more like this?

The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.