Unity: How to get a script from a GameObject

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


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.

Subscribe for Email Updates

* indicates required