Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to...

13
Unity 3D Scripting Intro Introduction to scripting in Unity 3D Mathew Tomberlin March 2015 1 UNITY SCRIPTING

Transcript of Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to...

Page 1: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

!!

Unity 3D Scripting Intro Introduction to scripting in Unity 3D

!Mathew Tomberlin

March 2015

!1UNITY SCRIPTING

Page 2: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

Unity 3D Scripting Intro Introduction to the scripting Unity 3D

!MonoDevelop

Pictured above is Unity 3D’s built-in text editor, MonoDevelop. When you create your first script, you’ll be looking at the same screen in MonoDevelop. The MonoDevelop screen has a lot of options, but we’ll only really be using the main screen, where you see text on the right. !!

!2UNITY SCRIPTING

Page 3: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

!!

Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three languages: Javascript, C# and Boo. Which language you choose is typically a matter of preference, but I’ll be teaching you C#, which is very similar to the Java language. 1. To create a new C# script, right click in the Project View

(the large space below the scene view). You’ll see a menu appear with options for Creating new assets, Importing new assets, etc.

!!!!!!2. Hover over “Create” and from the next menu that appears, click on C# Script. 3. A new C# script will appear in the Project View,

prompting you to enter a name for the script. Name is “Example”. Then double click on the script.

!4. When you double click on the script, MonoDevelop

should open and you should be looking at a new script, as shown at the top of this file.

What Does This Mean? What you’re looking at is the skeleton of a Unity class. Every script you make is a class in Unity. The first two lines, “using UnityEngine;” and “using System.Collections” import certain libraries in to this script so that we can use certain functions and classes from those libraries. For now these two lines aren’t important.

!3UNITY SCRIPTING

Page 4: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

The next line, public class Example : MonoBehaviour {, is important. This line is declaring the contents of this file as a class who’s name is Example. The name of the class within the file must match the name of the script in Unity! So, when you named your C# script Example in Unity, the file was automatically generated with a script named Example. Example : MonoBehaviour is C# way of saying that this class, Example, inherits from another class, called MonoBehaviour, which is the base class for all Game Objects in Unity. We won’t be dealing with this for now, just know that this is how you inherit from another class in C#. Everything following this line is the contents of our class, the code we want our class to execute. You’ll notice that there are two methods (or functions, as I’ll be calling them) within this class, called Start() and Update(). Both of these functions are built in to every single class you create in Unity. There are a number of other built in functions and you can declare your own functions, but for now we’ll be working solely within these functions.

!

!4UNITY SCRIPTING

Page 5: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

The Start() Function The Start() function is the function that is called immediately after you press the play button. This is very useful for setting certain variables to an initial value, such as the health of the player or the position of the player. I’ll demonstrate how the Start() function works. 1. In the MonoDevelop, go to the line immediately following void Start() { 2. Type the following: “Debug.Log(“This is the Start() function running!”); 3. Go to the File menu at the top of the screen and click the Save button.

!

!5UNITY SCRIPTING

Page 6: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

Adding Your Script to a Game Object Now that you have a script with some (extremely simple) behavior, we can test it in Unity. In order to use a script, it must be attached to a Game Object. All scripts must be attached to a Game Object before they will run. In this case, we’ll be attaching the C# script to the Obstacle in our scene, but you could just as easily attach the script to an Empty Game Object. !1. From the Project View, click on your Example C# script and drag it over the

Obstacle object in the Hierarchy. 2. Click on the Obstacle object in the Hierarchy. 3. You can ensure that your Example script is attached to the

Obstacle Game Object by looking for a new component in the Inspector on the right.

4. If you can’t find your Example script in the Inspector panel, another way to add the script to your Game Object is to click on the Add Component button at the bottom of the Inspector panel.

!!!

Testing Your Script Now that your script is attached to a Game Object, you can test the script out in the game. You’ll be viewing its output in the console. !1. To test out the script, you’ll have to view the script’s output in the console. To

view the console while the game is running, click on the “Maximize on Play” button at the top of the Game View so that it is off.

!6UNITY SCRIPTING

Page 7: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

2. Now, when you click the Play button, the game will run in the Game View without maximizing the view.

3. At the very bottom of the screen, you’ll see the most recent output (the only output in this case) to the console. When you play the game, you should see the following at the bottom of the screen:

4. To bring up the full console, just click on the output at the bottom of the screen and the console will open in the Project View.

! So, now you should see a single line of output in the console. This line of output comes from the line we added to the Start() function and is output just after the game starts, when the Obstacle Game Object’s Start() function is called. !

The Debug.Log() Function In the last section, we used a single line of code to show that the Start() function is called just after the game starts. This line of code “called” a function. “Calling a function” means running an “action” which is defined in a certain class. In this case, the action is called Log() and the class where Log() is defined is called Debug. As an example: Debug.Log(“This is a test”) outputs the text “This is a test” to the console. Debug.Log() is extremely useful for testing code and finding/fixing bugs in your code. !

The Update() Function Now that you understand that the Start() function is called just after the game is started, I’ll explain a more useful function called Update(). Update() is another function included in every Game Object. Start() is called only once, when the game is started, but the Update() function is called every single frame that the

!7UNITY SCRIPTING

Page 8: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

game is running, on every Game Object in the game. This makes the Update() function useful for things like moving an object, counting down, changing a variable over time, or anything else that needs to change over time. ! An easy example to show this uses the Debug.Log() statement like we did in the Start() function. !1. Double click on your Example C# script in the Project View. 2. Go to the line following public class Example : Monobehaviour { 3. We want to make a variable to hold a number that will increase for every frame

that the game is running, starting at 0. 4. To do this, type the following: public int frame = 0; 5. Go to the line immediately following void Update() { 6. Whatever code we add to the Update() function will be run every frame that the

game is running. So we want to call the Debug.Log() function and we want it to output the number in the frame variable to the console.

7. To do this, type the following: Debug.Log(frame); frame++; 8. The first line outputs whatever number is in the frame variable to the console.

The second line increases the number in the frame variable by 1.

!9. Go the the File menu at the top of the screen and click the Save button. !

!8UNITY SCRIPTING

Page 9: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

Now, every time the Update() function is called on the Obstacle Game Object, the frame number will be output to the console and that number will be increased by 1. ! The script attached to the Obstacle object is automatically updated to the new, saved version we just made, so all you have to do to test it is click the Play button. At the bottom of the screen, you’ll see the frame number being output to the console. After a second or two of letting the game run, pause the game and then click on the output at the bottom of the screen to bring up the console. You’ll see that every frame that the game is running the number in the frame variable is being increased and output to the console. If you scroll way up to the top of the console, you can also see that, at the very beginning, our Start() function was called and “This is the Start() function running!” was output to the console. !

Moving an Object While it’s great to be able to count in our Update() function, we want to be able to do something a little more worthwhile, like making an object move! In Unity, there are a number of different ways to get an object moving, but I’ll start off by showing you the most simple. We’re going to make the Obstacle object move forward and backward. 1. Right click in the Project View and hover over the Create Menu, then select C#

Script. 2. Name the C# script Movement and double click on it to open it in

MonoDevelop. 3. First of all, we are going to need a couple of variables to define how fast and in

what direction our object should move.

!9UNITY SCRIPTING

Page 10: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

4. Click on the line just after the beginning of our Movement class and add the following two variable declarations:

public float speed = 0.1f; private Vector3 moveVector; 5. The first of these two lines defines a new variable who’s type is float. The type

float is short for floating point number and is exactly the same as type double in Java. It is a type used to store a number with a decimal place, and in this case we’ll be storing the speed at which our object moves every frame.

6. The second of these two lines defines another new variable who’s type is Vector3. A Vector3 is a considerably more complicated variable type than most of the types you’ve learned so far. It is a class which contains three numbers, which correspond to x,y and z. The numbers themselves indicated a certain number of units on one of those three axis. Vector3 variables are often used to indicated a direction in 3D space.

7. Next, we need to set the initial move vector for the object. Knowing that the Start() function is called immediately after the game starts, we should set the initial move vector in the Start() function.

8. Click on the line just after the beginning of our Start() function and add the following line:

moveVector = new Vector3(speed,0,0); !9. This line assigns our moveVector variable a new object of type Vector3, with

the object’s speed as the x value, and 0 as the y and z values. This means when it moves, it will be moving a number of units in the x direction equal to its speed every frame.

10. Now that we have an amount that our object should move (a number of units on the x axis equal to speed), we need to actually get the object moving.

11. Click on the line just after the beginning of the Update() function and add the following line:

transform.Translate(moveVector); !12. First, I’ll describe what a transform is. Every Game Object has a transform

component attached to it automatically, even an Empty Game Object. A transform component describes an object’s position, rotation and scale. When

!10UNITY SCRIPTING

Page 11: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

you drag an object around in the scene view, you’re actually dragging around that Game Object’s transform component.

13. To move an object, you need to call one of the transform component’s functions, called Translate. When we say transform.Translate(), we’re saying “Call the Translate() function on the transform component of the Game Object that this script is attached to, and move the Game Object in a direction” In this case, the direction we want to translate (move) the Game Object is the direction of the Vector3 object in the moveVector variable, or a number of units on the x-axis equal to speed.

14. Now if we attach this script to the Obstacle object and test it, the object will move along the x axis a number of units equal to its speed every frame, forever. What we really want is for the object to move back and forth. To do this, we’re going to add a couple more lines at the beginning of the Update() function, before transform.Translate(moveVector); These lines will determine whether our object has moved too far to the left or too far to the right and flip its direction of movement if it has.

15. We’re going to add an if(){…} else if(){…} statement to determine whether we should change direction. Just after the beginning of the Update() function, add the following:

if(transform.position.x > 2){ moveVector*= -1; } else if(transform.position.x < -2){ moveVector*=-1; } 16. Like I said previously, every Game Object has a transform component which

defines an object’s position, rotation and scale. We can get an object’s x,y and z position to tell if it has moved past a certain point. Using an if statement, we check if the transform’s position on the x axis is greater than 2 (or else if it’s not greater than 2, we check if it is less than -2) and if it is, we multiply our moveVector variable by -1. Multiplying a Vector3 by -1 causes it to flip directions on each of its axis. Since our Vector3 only has a speed along one axis, it flips the sign of that axis, in this case the x-axis.

17. Remember to save your file in MonoDevelop.

!11UNITY SCRIPTING

Page 12: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

18. Back in Unity, drag the Movement C# script from the Project View on to the Obstacle object in the Hierarchy.

19. Click on the Obstacle object in the Hierarchy. 20. In the Inspector Panel, you’ll see both the Example

script and the Movement script attached to the Obstacle object. Right click on the name of the Example script and select Remove Component from the menu.

21. Click on the Play button and you should see the cube moving left and right. If you have a first-person controller in your scene: Watch out! The cube will push you around and may push you off the map.

!!

Scripts as Game Object Components Now that we know how to get an object moving around and how to attach a script to a Game Object, I’ll discuss a simple but extremely useful feature of Unity.

!12UNITY SCRIPTING

Page 13: Unity 3D Scripting Intro · Creating a New C# Script Before we start scripting, we’ll need a to create a new script in the Unity 3D interface. Unity 3D allows you to script in three

1. The Obstacle is moving a little fast, I want to slow it down. You could go in to the script and change the value of the speed variable in the script, but there’s another, easier way to do it from within Unity.

2. Click on the Obstacle object in the Hierarchy and find the Movement script (also known as a component) attached to the Obstacle game object in the Inspector panel.

3. From here, you can see the value of the variable we declared in the script, called Speed. Right now it’s set to 0.1, but we can see the cube is moving a little too fast.

4. Change the value of Speed to 0.05 and start the game. The cube should be moving slower now. This is called “changing a value in the Inspector” instead of “changing a value in script”.

5. In a lot of cases, we can change the value in the Inspector while the game is running and see the change in real-time. In this case, if we had changed the value in the Inspector while the game was running, we’d see no difference because the object’s speed is only applied to moveVector when the game is started.

!Conclusion

Now you know a little more about scripting and getting an object moving in Unity 3D. Getting comfortable with moving objects is essential to designing lots of different kinds of games. Next I’ll go over some more complicated movements, such as using input to move a player and a better way to do cyclical movement, as well as things like adding behavior to tell whether a Game Object has touched something. Stay tuned for our next lesson!

!13UNITY SCRIPTING