Mire Studios is made up of two people who have always enjoyed playing games. We're gamers that make games so you can expect a wide variety of different games from us.

Report RSS Unity Getting Rid Of (Some) Drag And Drop References Part 2

Posted by on

let's pick up from where we left off yesterday. I'm going to assume that you've already read part 1.

So today I'm going to start covering Unity ways to get rid of drag and drop references. These will be very easy for new programmers to understand and will help you get rid of some of those pesky references.

First off we have GetComponent. I'm going to show you how to use this by modifying the code from yesterday. After that, I'll explain what it does.

public class Thing : MonoBehaviour
{
   private OtherThing otherThing;

   private void Awake()
   {
      otherThing = GetComponent<OtherThing>();
   }

   private void Update()
   {
      otherThing.Do();
   }
}

First of all, we made our OtherThing reference private because we no longer need it to be shown in the inspector. In the Awake function (note: Awake is the first Unity function that gets called once on startup) we get a reference to OtherThing by using GetComponent. So what does it do? GetComponent will find the first script of the specified type. In the example OtherThing is our type. If we have an OtherThing script dragged onto the GameObject then it will be found and used a reference. No dragging and dropping required.

Ok, so when do we use this? You can use GetComponent anytime that one of your scripts requires something that is on the same GameObject. Make note of that last part, the same GameObject. GetComponent will not find the reference if it's on another GameObject.

So what if we have multiple? The answer to that is to use GetComponents, with an "s" at the end. That will find all objects of that type on your GameObject. Useful if you have an array or a list that you need to populate.

That's it for this blog post. Tomorrow we'll continue by looking at another way to reduce drag and drop references, tags.

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: