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 3

Posted by on

Today we'll picking up from part 2. I'm going assume you've read the previous parts. If not, make sure to do so before reading on.

So what if you need a reference to something but it's not on the GameObject? Yesterday we talked about how you can get references on the same GameObject, GetComponent. Well, we could use tags to get references from another GameObject.

To set up a tag, simply find a GameObject in the scene and in the inspector window find the tag dropdown. Unity has a few default tags but you can also add your own. Make sure the tag/s you want are added or you will get in error when trying to find the tag in code.

Let's see an example of how to use it.

public class Thing : MonoBehaviour
{
   public string tagToSearchFor;
   private OtherThing otherThing;

   private void Awake()
   {
      otherThing =
      GameObject.FindGameObjectWithTag(tagToSearchFor).
      GetComponent<OtherThing>();
   }

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

So what are we doing here? We've defined a public string tagToSearchFor. That should be pretty self explanatory. That string value can be set in the inspector just in case we want use this script multiple times for GameObjects with different tags. Next, we call GameObject.FindGameObjectWithTag(tagToSearchFor). This function simply looks for a GameObject of the tag we want. Finally, we have to call GetComponent from the GameObject that has just been found and that will get us our reference for otherThing.

What if we want an array or list of GameObjects with a certain tag? Well, we can use GameObject.FindGameObjectsWithTag. It works the same way but will return an array of GameObject instead of one with the tag you're searching for.

That's it for this blog post. Tomorrow we will look at one more way to get rid of drag and drop references. I'll see you then.

Post a comment

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