Unity and GetComponent

One of the first tricky things I found when getting started with Unity, was communicating information from one place to another. There are a few different ways to do this, and each one works slightly differently.

Firstly we can just refer from one script to another directly, by declaring an instance of it, and calling into it’s public methods.

This doesn’t really help when we’re talking about an object though, so for that we can use something like FindObjectOfType.

This is a little bit better, but probably won’t work well if we need a specific instance of an object. For that we will have to use something like GetComponent.

As you can see, we already need a handle on the object in question, from which we can access it’s Transform component (the only component all unity Objects require). The way that Unity works though, we can’t directly access any other components besides the Transform component, so we have to run GetComponent from the Transform, to find the Script component and run a method from there.

I find this implementation a little bit messy, and it’s hard to figure out at first if you don’t know where to look. The best resource to figure this stuff out is to look up a tutorial, because this is far from the only way to look up other objects, and you will often have a much harder time if you’re not using the one that is best suited for your situation.