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 4

Posted by on

This is part 4 our new Unity programmer tutorial/tips. I assume you've read up to part 3. If not, make sure you do so before reading on.

Yesterday, we covered tags and how they can help get rid of drag and drop references. What if we want a reference to a script that there is only one of and don't want to use a tag? We can use FindObjectOfType. Let's see it in action.

public class Thing : MonoBehaviour
{
   private OtherThing otherThing;

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

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

I think this one should be pretty simple to understand. FindObjectOfType will find an Object of the desired type. In this case we want a reference for otherThing.

This seems like it's way easier to use than setting up a tag system right? Well, it is but it has a slight drawback. FindObjectOfType runs slowly. That doesn't mean, however, that you can't use it. That's why it exists in the first place. It's a nice, easy, Unity way of getting a reference to an object without having to drag and drop it in. Also, keep in mind the word "slow" in programing is relative. If it's working and isn't slowing down your application then it's fine and as a beginner it will start making you think of other ways you can do the same thing more efficiently.

Lastly, what if we want an array or list of something? FindObjectsOfType, with an "s", can work just fine.

That's the end of this blog post. Tomorrow, we'll put this all together in a very simple way to help you understand how to use these functions. See you then.

Post a comment

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