brendoblog

Learning Unity - Create with Code (Part 3)

Compared to the first project in the Create with Code course, the second project actually involves a fair amount of code! First, let's take a look at the finished product...

Project 2 Youtube Thumbnail

As we can see, we have more functionality here: there's a player character who moves around, a game world that spawns in "enemies," and a means for the player to spawn a projectile to attack their enemies. There's even a rudimentary end point, where the console output displays "GAME OVER" if the player lets an enemy past. So how do we do this?

How Unity Does Code #

Unity developers are able to manipulate their game objects using "scripts" built in C#. If that sounds a bit odd, it did to me, too; C# isn't where my mind goes when I think of scripting languages. That said, I'm grateful for it. I'm more-or-less familiar with C#'s Java-like syntax, and its extensive use of objects makes it easy to visualize the code of a game where one object is frequently interacting with another. Consider this simple method created to handle what happens when a cookie collides with an animal:

private void OnTriggerEnter(Collider other)
{
     Destroy(gameObject);
     Destroy(other.gameObject);
}

Let's go through what we're doing here:

private void OnTriggerEnter(Collider other)

For this line, we create our method. We're really using a method "OnTriggerEnter" method that is inherited by all Unity scripts (from the MonoBehaviour class) by default. Unity calls this function any time two colliders impact each other, and here we override it to make this function do what we want. We also take in an element "other," which in this case is the "other" object that collided with this one.

Destroy(gameObject);
Destroy(other.gameObject);

These two lines define the desired behavior. In this case, we're calling Unity's Destroy() method to destroy two game objects. But how does Unity know which objects to destroy? The key part of this logic is that this script is applied directly to an object as a component:

Components of Moose prefab, with collision-related elements highlighted.

Here we set up a basic collider component for our object, which marks the boundaries of the object for the purposes of OnTriggerEnter. We've also attached our script directly to the object as a component as well!

This means, when we refer to gameObject in our script as we do above, Unity knows that we're referring to the gameObject to which this script is applied. And, when we refer to other.gameObject, we're referring to (that's right) the other game object! In practice, the player sees that as the moose getting hit by a cookie and both objects disappear.

That Wasn't So Bad, Was It? #

Unity comes out of the box with lots of powerful tools to manipulate objects, and a decent chunk of the learning curve is figuring out which tools we have available to us in the tool box to build what we need.