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 5

Posted by on

I'm going to assume you've read up to part 4 of the this tutorial/tips series. If not, make sure to do so before reading on.

So let's make a quick, simple, and slightly contrived example on how to put together the things we've learned. Let's assume we have a Player script and an Inventory script. We want the Player script to open up the Inventory when pressing the "I" key on the keyboard. That will call the Inventory.Open() method and, well, open the Inventory.

Create two empty GameObjects in your scene. Name one Player and name the other Inventory. Then, create two scripts with the same names as above. Attach each script to the GameObject object of the same and name and that's it.

public class Player : MonoBehaviour
{
   private Inventory inventory;

   private void Awake()
   {
      // way to get reference 1
      inventory = FindObjectOfType<Inventory>();

      // way to get reference 2
      inventory = GameObject.FindWithTag("Inventory").
      GetComponent<Inventory>();
   }

   private void Update()
   {
      if(Input.GetKeyDown(KeyCode.I))
      {
         inventory.Open();
      }
   }
}

I included two different ways of getting a reference to the inventory script in the Awake method. Obviously you would only need one or the other. I won't go over them because they have been covered in the previous tutorials/tips. As you can see, we can get a reference to our inventory without having to drag anything in the inspector.

Let's take a look at the Inventory script

public class Inventory : MonoBehaviour
{
   public void Open()
   {
      Debug.Log("Opened the inventory without a drag and
      drop reference, awesome"); 
   }
}

Obviously not what we'd want an Inventory to actually do but it gives you the idea. Instead of declaring a public Inventory reference on the Player script and then having to drag and drop the script in the inspector. We instead have Unity methods do the work for us.

That's it for this tutorial/tips series. I may create some more in the future but only if you guys liked this series. Let me know in the comments, or, feel free to send an email to mirestudios@gmail.com either way works. I'll see you guys around.

Post a comment

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