Unity Tutorials Beta

Learn how to create games in Unity, a powerful and popular game engine.

Introduction to Unity Scripting – Part 1

Scripting is an essential part of making even the simplest of games. These small collections of code work together to do all sorts of things.

4.9/5 8 Ratings

Version

  • C# 7.3, Unity 2019.2, Unity

Scripting is an essential part of making even the simplest of games. These small collections of code work together to do all sorts of things: From moving a character around the screen to keeping track of your inventory. Game developers write scripts in Unity in C#, a powerful object-oriented programming language developed by Microsoft around the year 2000. It has since grown to be one of the most popular programming languages out there. The Unity team chose C# as Unity’s main programming language because it’s well documented, easy to learn and flexible.

Unity has a well-documented API at its core that scripts can communicate with. In this tutorial, you’ll be creating a simple game — starting with a few models, while learning how to use the most important parts of the Unity API. You’ll learn how to create C# scripts that:

  • Create variables that can be changed in the editor.
  • Detect player input and react to it.
  • Use physics to create interactions.
  • Change values over time in several different ways.

Before starting off, make sure you meet the following requirements:

With that out the way, you’re ready to discover the Unity API by making a simple game!

Getting Started

Download the materials for the project using the Download Materials button at the top or bottom of this tutorial, unzip it somewhere and open the starter project inside Unity.

To start off, direct your attention to the Project window and unfold the RW folder. This project comes with a bunch of pre-made assets that you’ll be using to blow life into the game with scripting:

To focus on the scripting, here’s the included asset folders and their content:

  • Materials: A single material that’s shared between all models for optimal performance.
  • Models: Some models that range from a small smoke puff to the big ground model .
  • Music: The background music for the game. The song is Flying Kerfuffle by Kevin MacLeod.
  • Prefabs: A bunch of pre-made prefabs to make it easier to make changes to GameObjects already present in the scenes.
  • Scenes: A Game and a Title scene.
  • Scripts: Empty! Here’s where you’ll place the scripts you’ll be creating.
  • Sounds: A few 8-bit sound effects created using bfxr.
  • Sprites: There’s a single sprite sheet in here for some small UI elements.
  • Textures: A single texture that’s used by the shared material.

Now, open up the Game scene under RW/Scenes if it isn’t opened yet and take a look around in the Scene view.

There are some floating islands with windmills, bridges and a small rail line with a blue hay machine sitting on top. Now, take a glance at the Hierarchy:

Here’s a quick overview of the GameObjects:

  • Music: An audio source playing a happy tune on loop.
  • Main Camera: The camera that points down at the scene to give a good overview.
  • Directional Light: A single light source that emulates a sun.
  • Scenery: This GameObjects hold the ground and the windmills.
  • Hay Machine: This is the blue machine sitting on the rails. It’s made out of a few GameObjects to make it easy to customize later on.

Next, click the play button at the top of the editor and take a look at the Game view to see what happens.

The only signs of life at the moment are the smoke particles flying up from the hay machine. It won’t win any game of the year awards any time soon, but it’s a good foundation to build on. :]

Click the play button again to stop testing the “game”.

Now that you’re familiar with the project, it’s time to get scripting!

Your First Script

Creating new scripts in Unity is quite easy. Right-click the RW/Scripts folder, select Create ► C# Script and name the script Rotate.

Unity now creates and immediately compiles a bare bones MonoBehaviour script.

While the script won’t do anything yet, you can already use it as a component by attaching it to a GameObject. In this case, the Rotate script will turn the wheels of all windmills around.

Components are instances of scripts, meaning that you can add as many of the same component to any GameObject as you like. Any changes made to the script will reflect in all its components.

Unfold Scenery in the Hierarchy to reveal its children. Open Windmill in the prefab editor by clicking the arrow next to its name.

Note: Unity recently updated their prefab system. For an in-depth look at the new system, check out this great tutorial!

Select Wheel, it’s the grandchild of Windmill. Now, click the Add Component button at the bottom of the Inspector, start typing “rotate” until the Rotate component appears in the list and select it.

This will add the Rotate component to the wheels of all windmills.

To edit the script, you’ll need to open it in a code editor like Visual Studio. There are a few ways of opening a script, but the easiest ways are by either finding the source file in the Project window and double-clicking it. Double-clicking the Script field of any component also works:

Use any of the methods above to open the Rotate script in your default code editor. Here’s what that looks like in Visual Studio:

The script itself is a single class that derives from MonoBehaviour, Unity’s base class that all scripts should derive from if they need to be used as components.

MonoBehaviour is part of the UnityEngine namespace and implements a few public methods but — more importantly — a huge list of event functions.

Note: Functions are another name for methods, all of these are subroutines. In OOP languages such as C# you should use the term method, but Unity has chosen to go with function instead when describing most of its built-in methods.

Unity adds the Start and Update methods by default to all new scripts. These are actually event functions, they get called when a specific action triggers them. Here’s a handful of the most common event functions and when they get called:

  • Start: First time the component is initialized.
  • Update: Every frame.
  • OnEnable: When the component is (re)enabled.
  • OnDestroy: When the component is destroyed.

You’ll be using a lot more of them over the course of this tutorial as they’re an essential part of scripting. You can check out the full list of event functions in Unity’s documentation.

Add the following line inside of Update:

transform.Rotate(0, 50 * Time.deltaTime , 0);

This single line that does a constant rotation on the Y-axis over time already shows some of the abilities of the Unity API:

  • transform is an inherited property of MonoBehaviour. It returns the Transform of the GameObject the component gets attached to. The Transform class allows you to read and change a GameObject’s position, rotation and scale.
  • Rotate is one of the public methods of the Transform class, one of its signatures is used here to pass on a rotation in degrees to the X, Y and Z axes respectively.
  • The value passed for the Y-axis is 50 * Time.deltaTime. Time.deltaTime is part of the UnityEngine namespace and returns the time in seconds between the last and the current frame. This value can change values over time independent of framerate. In essence, this prevents stuff from going slow motion on slow machines and into hyper mode on faster ones. Multiplying the value from Time.deltaTime with 50 means that you want the value to increase by 50 per second. In this case that’s a rotation of 50 degrees on the Y-axis over the time span of a second.

As this line has been added to Update, it gets executed every frame while the component is enabled. This results in a smooth, constant rotation.

Note: The Unity editor uses Euler angles to modify the rotation of GameObjects — these are the familiar X, Y and Z axes. The Unity engine actually uses Quaternions internally that consist of X, Y, Z and W values. These values are very hard to interpret and aren’t meant to be used directly. To read more about the difference, take a look at Unity’s documentation on the subject.

Save this script and return to the editor.

You’ll the notice the editor will be unresponsive for a very short time while it’s compiling. You can check when this compilation is happening by looking at the bottom right corner of the editor, there will be a small animated icon:

If you haven’t exited the Prefab editing mode, do so now by clicking the left pointing arrow next to the Windmill prefab in the Hierarchy. You’ll be prompted to Save or Discard your changes. Click Save.

Now, play the scene. You’ll notice the windmill wheels are now slowly turning around, so relaxing.

Now, let’s say you want to tweak how fast the wheels are turning, or you want to add the Rotate component to another GameObject that needs to turn on a different axis. Wouldn’t it be nice if you could change those values in the editor?

That’s where variables come in!

Variables

Variables are containers of data that store information. These can range from the player’s lives and money to a reference to a prefab to spawn into the scene. Once you add these to a script, you can edit their values in the editor.

Open the Rotate script in your favorite code editor and add the following line right above the Start method:

public Vector3 rotationSpeed;

This variable will change how fast and on what axis the rotation happens.

The public access modifier in the context of Unity means that this variable will be exposed to the editor and other classes.
A Vector3 is a struct that stores an X, Y and Z value, a Vector3 can be used to pass on the position, rotation or scale of a GameObject.

Now replace this line:

transform.Rotate(0, 50 * Time.deltaTime , 0);

With the following:

transform.Rotate(rotationSpeed * Time.deltaTime);

The rotation speed now gets fed into the Rotate method using a variable, making it easy to change. Vectors can be multiplied with single value variable types like deltaTime to change all included values of the vector at once. For example, a Vector3 with a value of (X:1, Y:2, Z:3) multiplied with a float with a value of 3 will result in a Vector3 with a value of (X:3, Y:6, Z:9).

Always opt for a variable instead of a “magic number” like the 50 you added in before. Doing so will allow you to change and reuse values without having to open the script.

Now, save the script and return to the editor. Open the Windmill prefab from the Hierarchy as you did before, and select the Wheel grandchild GameObject again.

Take a look at the Inspector, the Rotate component now has a field that you can adjust:

Change the Y value of the Rotation Speed field to 120 and exit the prefab mode by clicking the arrow at the top left of the Hierarchy, saving your changes when prompted.

Now, play the scene. The wheels are rotating like before, albeit a tad faster.

A huge advantage of having variables exposed in the editor is that you can change them while in play mode! Select the wheel of one of the windmills in the Hierarchy and try changing the Rotation Speed. You can slide the Y value from left to right or change the number directly.

Doing so will result in the wheel changing its speed in real time:

Once you stop play mode, any values you’ve set on GameObjects in the Hierarchy will be reset. This is a great way to play around with values and see what works best. You could tweak the height a character jumps, how much health the enemy orcs have or even the layout of UI elements.

Of course — once you have found the values you want — you might want to store these so they get applied each time the game starts. The most robust way to do this is by copying and pasting the values on components and using prefabs.

While still in play mode, change the rotation of one of the wheels to anything you think looks good, 150 on the Y-axis for example. Now right-click the Rotate component around its name in the Inspector, or left-click the options cog in the top right of the component, and select Copy Component. This will copy the component and its values to your clipboard.

Next, stop the play mode. You’ll notice the speed reverts to its former value in Inspector. Right-click the Rotate component’s name and select Paste Component Values, any values you’ve copied are now pasted into the Rotate component.

While this changed the rotation speed for one of the windmills, you want this applied to all of them. To do so, select the grandparent Windmill of the Wheel you’ve altered and select Overrides ► Apply All at the top right of Inspector to apply all changes to the Windmill prefab.

Next up is polling for player input to make the machine move and shoot!

Player Input and Instantiating Prefabs

A game wouldn’t be a game without requiring some level of player input. Scripts can get the state of the keyboard, mouse and any connected gamepads. The first goal is to get that little machine moving on the rails from left to right.

Movement

Create a new C# script in RW/Scripts, name it HayMachine and open it in a code editor.

Add the following variables right above Start:

public float movementSpeed;

This variable will allow you to specify the speed at which the machine can move.

Now, add this method below Update:

private void UpdateMovement()
{
    float horizontalInput = Input.GetAxisRaw("Horizontal"); // 1

    if (horizontalInput < 0) // 2
    {
        transform.Translate(transform.right * -movementSpeed * Time.deltaTime);
    }
    else if (horizontalInput > 0) // 3
    {
        transform.Translate(transform.right * movementSpeed * Time.deltaTime);
    }
}

This piece of code moves the hay machine around using the player’s horizontal input:

  1. Get the raw input of the Horizontal axis using the Input class and store it in horizontalInput. The Input class contains all the methods to poll input devices. GetAxisRaw returns the current value of input as defined in the input manager for the Horizontal axis:

In this case, you can use the left and right arrow keys, the A & D keys or a left analog stick as input.

  1. If horizontalInput is less than 0, that means a left movement on the X-axis was detected. In that case, translate (which means move) the machine to the left at a rate of its movementSpeed per second.
  2. If the horizontalInput is higher than 0 instead, move the machine to the right.

When Unity doesn’t detect any input, horizontalInput will stay at 0 and the machine won’t move.

Now, to call the method you’ve added each frame, add a call to it in Update:

UpdateMovement();

Next, save this script and return to the editor. Select Hay Machine in the Hierarchy and add a Hay Machine component to it.

Set its Movement Speed to 14 and play the scene. Use the arrow keys or A & D to move the machine from left to right. It works!

Oops, you can move the machine outside of the rails and even off-screen, that’s no good. You’ll need to set up some boundaries to stop the machine from moving too far.

Open the HayMachine script again and add this variable below the others:

public float horizontalBoundary = 22;

This variable will be used to limit the movement on the X-axis. It gets assigned 22 as a default value, that will be the initial value that gets filled into the editor as well.

Now, edit UpdateMovement‘s if-else statement so it makes use of the boundary in its checks:

if (horizontalInput < 0 && transform.position.x > -horizontalBoundary) // 1
{
    transform.Translate(transform.right * -movementSpeed * Time.deltaTime);
}
else if (horizontalInput > 0 && transform.position.x < horizontalBoundary) // 2
{
    transform.Translate(transform.right * movementSpeed * Time.deltaTime);
}

Here's what changed:

  1. Not only does the horizontal input needs to be negative before allowing movement to the left, the machine's X position also needs to be higher than the negative value of horizontalBoundary.
  2. To move to the right, the horizontal input needs to be positive and the machine's X position should be lower than horizontalBoundary.

The image below illustrates what goes on more visually:

The white lines on the left and right represent the boundaries, the line going through the machine is its center. Moving the machine in either direction "locks" it once a boundary is reached:

Save the script and return to the editor. Try playing the scene and moving the machine left and right once more. The machine gets stopped once it's moved to one of the edges.
Next, you'll be implementing the shooting of bales of hay!

Creating and Shooting Projectiles

Before you can start launching anything, you'll need to create a GameObject for the hay. Start off by creating a new empty GameObject in the Hierarchy by right-clicking an empty space and selecting Create Empty. This will generate an empty GameObject named "GameObject" at the root of the Hierarchy.

With the empty GameObject still selected, change its name to Hay Bale in the Inspector and reset its Transform component by right-clicking the Transform component and selecting Reset.

Now, add a 3D model to Hay Bale by dragging in the Hay Bale model from RW/Models onto Hay Bale in the Hierarchy. With the Hay Bale model still selected, name it Hay Bale Model and reset its Tranform. You'll now notice the hay firmly planted into the ground in both the Scene and the Game view.

Next, select Hay Bale and add the following components by using the Add Component button:

  • Box Collider
  • Rigidbody
  • Rotate

Now that the hay has the necessary components to use physics and can rotate around as a way of animating, it's time to configure it.

The bale will be shot from the hay machine, flying straight forward without being affected by gravity. Later in this tutorial, once you've added the sheep, they will be used to stop the sheep from hurting themselves.

To start off, check the Is Trigger checkbox on the Box Collider so the bale won't be able to push any rigid bodies around. Next, check the Is Kinematic checkbox on its Rigidbody so the hay won't drop through the ground. Finally, set the Rotation Speed on Rotation to (X:300, Y:50, Z:0).

Save the scene and press the play button. You'll notice the hay is spinning around in place.

To make the hay move forward, you'll need to write another utility script. Create a new C# script in RW/Scripts, name it Move and open it in your code editor.

Add the following variables declarations to the top of the class, right above the Start method:

public Vector3 movementSpeed; //1
public Space space; //2

Here's what they're used for:

  1. The speed in meters per second the attached GameObject will move in on the X, Y and Z axes.
  2. The space the movement will take place in, either World or Self. The World space transforms a GameObject in Unity's world space, ignoring the rotation of the GameObject, while Self considers the rotation of the GameObject in its calculations.

Now, add the following to Update:

transform.Translate(movementSpeed * Time.deltaTime, space);

This is what actually moves the GameObject by using a translation, that's a geometric term that means to transform a point by a distance in a given direction. Basically, it means to move GameObjects in the context of Unity.

The Translate method takes two parameters: The first is the direction and speed, while the second is the space in which the movement happens. The movement is multiplied by Time.deltaTime to perform a smooth movement over an amount of time.

Save this script and return to the editor. Add a Move component to Hay Bale, set its Movement Speed to (X:0, Y:0, Z:20) and leave Space set to World.

Now, play the scene and you'll see the hay bale flying towards the bridges and off the screen, great!

Drag Hay Bale into the RW/Prefabs folder to make it into a prefab and delete the original from the Hierarchy. You'll now be able to reference this prefab to create more whenever you want.

To make the hay machine shoot out the bales, you'll need to do some scripting. Open the HayMachine script and add the following variable declarations right above Start:

public GameObject hayBalePrefab; // 1
public Transform haySpawnpoint; // 2
public float shootInterval; // 3
private float shootTimer; // 4

Here's a brief explanation of the variables:

  1. Reference to the Hay Bale prefab.
  2. The point from which the hay will to be shot.
  3. The smallest amount of time between shots. This prevents the player from being able to spam the shoot button and fill the screen with bales of hay.
  4. A timer that decreases steadily to keep track whether the machine can shoot or not.

Now, add the ShootHay method below UpdateMovement:

private void ShootHay()
{
    Instantiate(hayBalePrefab, haySpawnpoint.position, Quaternion.identity);
}

The Instantiate method creates an instance of a given prefab or GameObject and places it in the scene. It takes three parameters: a prefab or GameObject, a position and a rotation. In this case, the reference to the Hay Bale prefab is used to create an instance with its initial position set to the same as the haySpawnpoint Transform. Quaternion.identity is used for the rotation, this is the default rotation value and is similar to Vector3.Zero as it sets the rotation to (X:0, Y:0, Z:0).

To call the code above, you'll need some code to poll for input. Add the following method just above ShootHay:

private void UpdateShooting()
{
    shootTimer -= Time.deltaTime; // 1

    if (shootTimer <= 0 && Input.GetKey(KeyCode.Space)) // 2
    {
        shootTimer = shootInterval; // 3
        ShootHay(); // 4
    }
}

Here's what this block of code does:

  1. Subtract the time between the previous frame and the current one from shootTimer, this will decrease its value by 1 every second.
  2. If the value of shootTimer is equal to or less than 0 and the space bar is pressed in...
  3. Reset the shoot timer.
  4. Shoot a bale of hay!

Lastly, add this line to Update, right below UpdateMovement();:

UpdateShooting();

This calls the method above every frame.

Now, save this script and return to the editor. Select Hay Machine in the Hierarchy, unfold it by clicking the arrow to its left and take a look at the Inspector.

The new public variables you just added have become fields that can be assigned. Drag Hay Bale from RW\Prefabs onto the Hay Bale Prefab slot, drag Hay Machine's child Hay Spawnpoint onto the Hay Spawnpoint slot and set Shoot Interval to 0.8.

Now, save the scene and click the play button. Move the hay machine around with the arrow keys and shoot some hay using the space bar!

Everything should be working like the GIF above.

You may have noticed the bales never get destroyed and keep flying off endlessly into nothingness.

To fix this, you'll make smart use of triggers, tags and a line or two of code.

Tags and Reacting to Physics

To identify types of GameObjects, you can use tags. Tags are reference words like "Player" or "Collectible" you can assign to GameObjects to easily find them and differentiate them from other GameObjects. You can use any word or short sentence as a tag.

Creating a new tag is pretty easy, select Edit ► Project Settings... in the top menu and open the Tags and Layers tab in the Project Settings window. Now expand the Tags list and you'll notice the project already comes with two tags pre-loaded: DestroyHay and DropSheep.

Click the + button below the Tags list, name the new tag Hay and click the Save button to add this new tag to the list.

With the Hay tag added, close the Project Settings window and select Hay Bale in the RW\Prefabs folder. Open the Tag dropdown right below the name field and select Hay.

Now the difference between the bales of hay and other GameObjects is clear, you can add an area that destroys the hay when it comes into contact with it. Add a new empty GameObject to the Hierarchy and name it Triggers. Reset its Transform and add an empty GameObject as its child. Name this child Hay Destroyer.

Select Hay Destroyer, set its position to (X:0, Y:4, Z:68) and add a Box Collider to it. Check the Is Trigger checkbox on the Box Collider and set its Size to (X:60, Y:8, Z:12). Next, change the tag of Hay Destroyer to DestroyHay. You should now see a huge box-shaped collider appear in the Scene view, right outside of the camera's view.

Now, in order for this trigger to destroy any hay, you'll need to write yet another utility script. Create a new C# script inside RW\Scripts, name it DestroyOnTrigger and open it in a code editor. Remove the Start and Update methods completely and add this variable declaration in their place:

public string tagFilter;

This string will allow you to enter the name of any tag that will destroy this GameObject.

Now, add this method below the variable you just added:

private void OnTriggerEnter(Collider other) // 1
{
    if (other.CompareTag(tagFilter)) // 2
    {
        Destroy(gameObject); // 3
    }
}

Here's what's going on:

  1. OnTriggerEnter is a MonoBehaviour function, it's one of the special methods the Unity engine calls in specific circumstances. In this case, OnTriggerEnter gets called when a GameObject with a Rigidbody and a Collider enters the trigger area of a GameObject.
  2. Check if the GameObject that enters the trigger has the tag defined in tagFilter.
  3. Destroy the GameObject this script is attached to.

Save this script and return to the editor. Time to test it out!

Select Hay Bale in RW\Prefabs, add a Destroy On Trigger component and change Tag Filter to DestroyHay.

Now press the play button and try shooting some hay again. You'll notice any hay that hits the Hay Destroyer instantly gets obliterated.

Now that you have full control over the hay machine and its projectiles, it's time to introduce some fluffy friends.

Sheep Scripting

In the game you're creating, a bunch of sheep are panicking and running towards you, stopping at nothing. Unfortunately for them, that includes the ledge just behind the machine, yikes!

To start off, create a new empty GameObject in the Hierarchy and name it Sheep. Reset its Transform, set its Y rotation to 180 and add both a Box Collider and a Rigidbody. Check the Is Trigger checkbox of the Box Collider and change its Center and Size to (X:0, Y:1.4, Z:-0.3) and (X:2.5, Y:2, Z:4), respectively. Finally, check the Is Kinematic checkbox on the Rigidbody.

The Sheep should now look like this in the Inspector:

Now, drag the Sheep model from RW\Models onto Sheep to give it some visuals. Name the GameObject you just added Sheep Model, reset its Transform and set its X rotation to -90 so its head comes out of the ground.

Much better!

This sheep is now ready to be scripted!

Note: Up until now, you have created generic scripts that can be reused for any GameObject, or even other projects. The script you're about to write is a lot more specific because its interactions are quite unique and will get more complicated over time as you add more features to the game.

Create a new C# script named Sheep in RW\Scripts and open it in a code editor.

To get started, the sheep simply needs to run forward and disappear when it gets hit by a hay bale. Add the following variable declarations right above Start:

public float runSpeed; // 1
public float gotHayDestroyDelay; // 2
private bool hitByHay; // 3

Here's what these are for:

  1. The speed in meter per second that the sheep will run.
  2. The delay in seconds before the sheep gets destroyed after it got hit by hay.
  3. A Boolean that gets set to true once the sheep was hit by hay.

With that out of the way, add this line to Update:

transform.Translate(Vector3.forward * runSpeed * Time.deltaTime);

This makes the sheep run towards its forward vector (the local Z axis) at the speed set in the runSpeed variable.

Next, add this method below Update:

private void HitByHay()
{
    hitByHay = true; // 1
    runSpeed = 0; // 2

    Destroy(gameObject, gotHayDestroyDelay); // 3
}

Here's the gist of this method:

  1. Set hitByHay to true, this will be useful to check if the method was already called, so it doesn't get called twice or more.
  2. Set the running speed to 0, this stops the sheep in its tracks.
  3. You've already seen this method call, but there's an extra parameter this time. The Destroy method accepts a second parameter, the delay in seconds before the GameObject gets destroyed. In this case, the delay variable you added above is used.

The last part is making the sheep react to physics by adding the following code:

private void OnTriggerEnter(Collider other) // 1
{
    if (other.CompareTag("Hay") && !hitByHay) // 2
    {
        Destroy(other.gameObject); // 3
        HitByHay(); // 4
    }
}

Here's what this does:

  1. This method gets called when a trigger enters this GameObject (or vice versa).
  2. If the GameObject that hit this one has the Hay tag assigned and the sheep wasn't hit by hay already...
  3. Destroy the other GameObject (the hay bale).
  4. Call the HitByHay method you added before this one.

That's it for now, save the script and return to the editor. Select Sheep in the Hierarchy and add a Sheep component. Set its Run Speed to 10 and Got Hay Destroy Delay to 1.

Now, play the scene, shoot the sheep and see what happens!

Awesome! The sheep stops moving and disappears like you've scripted it to. What happens if the sheep runs through without you shooting it though? Restart the scene and test that out.

The sheep flies over the edge as if by magic, that's no good! You'll have to create another trigger zone so the Sheep script can detect collisions with it and react accordingly.

Create a new empty GameObject as a child of Triggers, name it Sheep Dropper and reset its Transform. Set its position to (X:0, Y:4, Z:-54) and add a Box Collider with Is Trigger checked and a Size of (X:60, Y:8, Z:12). Now change its Tag to DropSheep and you'll have a nice big trigger behind the hay machine ready to be used.

When the sheep hits this trigger, it should fall down and get destroyed once out of sight. To implement this, you'll need to make some adjustments to the Sheep script. Open it again in a code editor and add the following variable declarations below the existing ones:

public float dropDestroyDelay; // 1
private Collider myCollider; // 2
private Rigidbody myRigidbody; // 3

They speak for themselves, but here's a brief overview:

  1. The time in seconds before the sheep gets destroyed when it's over the edge and starts dropping.
  2. Reference to the sheep's Collider component.
  3. A reference to the sheep's Rigidbody.

Now, assign the needed references by adding this to Start:

myCollider = GetComponent<Collider>();
myRigidbody = GetComponent<Rigidbody>();

This finds and caches the sheep's collider and rigidbody for later use.

Next, the sheep's collider setup needs adjustments so it gets affected by gravity. Add this method to do just that:

private void Drop()
{
    myRigidbody.isKinematic = false; // 1
    myCollider.isTrigger = false; // 2
    Destroy(gameObject, dropDestroyDelay); // 3
}

This method is simple:

  1. Make the sheep's rigidbody non-kinematic so it gets affected by gravity.
  2. Disable the trigger so the sheep becomes a solid object.
  3. Destroy the sheep after the delay specified in dropDestroyDelay.

Now, add the following to OnTriggerEnter, right below the existing if-statement:

else if (other.CompareTag("DropSheep"))
{
    Drop();
}

If the sheep was hit by something other than a hay bale, it checks if the collider it hit has the DropSheep tag assigned; Drop gets called if that's the case.

Now save this script and return to the editor. Select Sheep and change Drop Destroy Delay to 4.

Play the scene again and let the sheep move past the machine to see what happens.

Great! The sheep now falls down to its demise when the player fails to save it. Now that's motivating!

Now that the sheep acts as intended, drag it from the Hierarchy to the RW\Prefabs folder to turn it into a prefab and delete the original from the Hierarchy.

That's it for the first part of this tutorial! Pat yourself on the back, you have learned the basics of how to create scripts to implement gameplay in Unity.

Where to Go From Here?

You can download the finished project by clicking on the Download Materials buttons at the top or bottom of this tutorial.

If you want to know more about Unity's API, check out these handy resources:

Once you're ready to go a step further in scripting with Unity, check out the second part of this tutorial. Here, you'll invite a whole flock of woolly friends and learn how to:

  • Create lists and iterate them.
  • Update UI elements.
  • Use the Event System.
  • Make use of the Singleton pattern.
  • Pass data between scenes to customize a game.

We hope you enjoyed this tutorial, if you have any questions or comments, join the forum discussion below!

Average Rating

4.9/5

Add a rating for this content

8 ratings

Contributors

Comments