0% found this document useful (0 votes)
3 views

Beginner Scripting-V2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Beginner Scripting-V2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Setting up Project

3D Project
Import 3D terrain asset for demonstration
Import 3D character
https://assetstore.unity.com/packages/essentials/starter-assets-third-person-character-
controller-196526

1 of 80
Scripts as Behavior Components

• 01. Scripts as Behaviour Components

2 of 80
using UnityEngine;
using System.Collections;

public class ExampleBehaviourScript : MonoBehaviour


{
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
GetComponent<Renderer>().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown(KeyCode.B))
{
GetComponent<Renderer>().material.color = Color.blue;
}
}
}

3 of 80
Data Types

Learn the important di erences between Value and Reference data types, in order to better understand how
variables work.

4 of 80
ff
🎞 10. Data Types
using UnityEngine;
using System.Collections;

public class DatatypeScript : MonoBehaviour


{
void Start ()
{
//Value type variable
Vector3 pos = transform.position;
pos = new Vector3(0, 2, 0);

//Reference type variable


Transform tran = transform;
tran.position = new Vector3(0, 2, 0);
}
}

5 of 80
Variables and Functions
using UnityEngine;
using System.Collections;

public class VariablesAndFunctions : MonoBehaviour


{
int myInt = 5;

void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}

int MultiplyByTwo (int number)


{
int ret;
ret = number * 2;
return ret;
}
}
🎞 02. Variables and Functions

6 of 80
7 of 80
using UnityEngine;
using System.Collections;

public class BasicSyntax : MonoBehaviour


{
void Start ()
{
Debug.Log(transform.position.x);

if(transform.position.y <= 5f)


{
Debug.Log ("I'm about to hit the ground!");
}
}
}

8 of 80
Classes

How to use Classes to store and organize your information, and how to create constructors to work with
parts of your class

🎞 13. Classes

9 of 80
Inventory

using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour


{
public class Stuff
{
public int bullets;
public int grenades;
public int rockets;
public float fuel;

public Stuff(int bul, int gre, int roc)


{
bullets = bul;
grenades = gre;
rockets = roc;
}

public Stuff(int bul, float fu)


{
bullets = bul;
10 of 80
fuel = fu;
}

// Constructor
public Stuff ()
{
bullets = 1;
grenades = 1;
rockets = 1;
}
}

// Creating an Instance (an Object) of the Stuff class


public Stuff myStuff = new Stuff(50, 5, 5);

public Stuff myOtherStuff = new Stuff(50, 1.5f);

void Start()
{
Debug.Log(myStuff.bullets);
}
}

11 of 80
MovementControls

using UnityEngine;
using System.Collections;

public class MovementControls : MonoBehaviour


{
public float speed;
public float turnSpeed;

void Update ()
{
Movement();
}

void Movement ()
{
float forwardMovement = Input.GetAxis("Vertical") * speed *
Time.deltaTime;
float turnMovement = Input.GetAxis("Horizontal") * turnSpeed *
Time.deltaTime;

transform.Translate(Vector3.forward * forwardMovement);

12 of 80
transform.Rotate(Vector3.up * turnMovement);
}
}

Shooting

using UnityEngine;
using System.Collections;

public class Shooting : MonoBehaviour


{
public Rigidbody bulletPrefab;
public Transform firePosition;
public float bulletSpeed;

private Inventory inventory;

void Awake ()
{
inventory = GetComponent<Inventory>();
}

13 of 80
void Update ()
{
Shoot();
}

void Shoot ()
{
if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
{
Rigidbody bulletInstance = Instantiate(bulletPrefab,
firePosition.position, firePosition.rotation) as Rigidbody;
bulletInstance.AddForce(firePosition.forward * bulletSpeed);
inventory.myStuff.bullets--;
}
}
}

SingleCharacterScript

using UnityEngine;
using System.Collections;

public class SingleCharacterScript : MonoBehaviour


14 of 80
{
public class Stuff
{
public int bullets;
public int grenades;
public int rockets;

public Stuff(int bul, int gre, int roc)


{
bullets = bul;
grenades = gre;
rockets = roc;
}
}

public Stuff myStuff = new Stuff(10, 7, 25);


public float speed;
public float turnSpeed;
public Rigidbody bulletPrefab;
public Transform firePosition;
public float bulletSpeed;

void Update ()
{
15 of 80
Movement();
Shoot();
}

void Movement ()
{
float forwardMovement = Input.GetAxis("Vertical") * speed *
Time.deltaTime;
float turnMovement = Input.GetAxis("Horizontal") * turnSpeed *
Time.deltaTime;

transform.Translate(Vector3.forward * forwardMovement);
transform.Rotate(Vector3.up * turnMovement);
}

void Shoot ()
{
if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
{
Rigidbody bulletInstance = Instantiate(bulletPrefab,
firePosition.position, firePosition.rotation) as Rigidbody;
bulletInstance.AddForce(firePosition.forward * bulletSpeed);
myStuff.bullets--;
}
16 of 80
}
}

17 of 80
Scope and Access Modifiers

Understanding variable & function scope and accessibility.

18 of 80
🎞 06. C# Scope and Access Modi ers
AnotherClass

using UnityEngine;
using System.Collections;

public class AnotherClass


{
public int apples;
public int bananas;

private int stapler;


private int sellotape;

public void FruitMachine (int a, int b)


{
int answer;
answer = a + b;
Debug.Log("Fruit total: " + answer);
}

private void OfficeSort (int a, int b)


19 of 80
fi
{
int answer;
answer = a + b;
Debug.Log("Office Supplies total: " + answer);
}
}

Scope And Access Modi ers

using UnityEngine;
using System.Collections;

public class ScopeAndAccessModifiers : MonoBehaviour


{
public int alpha = 5;

private int beta = 0;


private int gamma = 5;

private AnotherClass myOtherClass;

void Start ()
20 of 80
fi
{
alpha = 29;

myOtherClass = new AnotherClass();


myOtherClass.FruitMachine(alpha, myOtherClass.apples);
}

void Example (int pens, int crayons)


{
int answer;
answer = pens * crayons * alpha;
Debug.Log(answer);
}

void Update ()
{
Debug.Log("Alpha is set to: " + alpha);
}
}

21 of 80
GetComponent

How to use the GetComponent function to address properties of other scripts or components.

22 of 80
🎞 21. C# GetComponent in Unity
UsingOtherComponents

using UnityEngine;
using System.Collections;

public class UsingOtherComponents : MonoBehaviour


{
public GameObject otherGameObject;

private AnotherScript anotherScript;


private YetAnotherScript yetAnotherScript;
private BoxCollider boxCol;

void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}

void Start ()
23 of 80
{
boxCol.size = new Vector3(3,3,3);
Debug.Log("The player's score is " + anotherScript.playerScore);
Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths
+ " times");
}
}

AnotherScript
using UnityEngine;
using System.Collections;

public class AnotherScript : MonoBehaviour


{
public int playerScore = 9001;
}

YetAnotherScript

using UnityEngine;
using System.Collections;
24 of 80
public class YetAnotherScript : MonoBehaviour
{
public int numberOfPlayerDeaths = 3;
}

25 of 80
Enabling and Disabling Components

How to enable and disable components via script during runtime

26 of 80
🎞 22. C# Enabling and Disabling Components in Unity
using UnityEngine;
using System.Collections;

public class EnableComponents : MonoBehaviour


{
private Light myLight;

void Start ()
{
myLight = GetComponent<Light>();
}

void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}

27 of 80
Arrays

Using arrays to collect variables together into a more manageable form.

28 of 80
🎞 11. Arrays
using UnityEngine;
using System.Collections;

public class Arrays : MonoBehaviour


{
public GameObject[] players;

void Start ()
{
players = GameObject.FindGameObjectsWithTag("Player");

for(int i = 0; i < players.Length; i++)


{
Debug.Log("Player Number "+i+" is named "+players[i].name);
}
}
}

29 of 80
Awake and Start

Awake and Start, two of Unity's initialization functions


• Awake is called either when an active GameObject that contains the script is initialized when a Scene
loads, or when a previously inactive GameObject is set to active, or after a GameObject created with
Object.Instantiate is initialized. Use Awake to initialize variables or states before the application starts
• Start is called on the frame when a script is enabled just before any of the Update methods are called the
rst time. Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake
is called when the script object is initialised, regardless of whether or not the script is enabled. Start may
not be called on the same frame as Awake if the script is not enabled at initialisation time
• The Awake function is called on all objects in the Scene before any object's Start function is called. This
fact is useful in cases where object A's initialisation code needs to rely on object B's already being
initialised; B's initialisation should be done in Awake, while A's should be done in Start.

🎞 07. C# Awake and Start in Unity


using UnityEngine;
using System.Collections;

public class AwakeAndStart : MonoBehaviour


{
void Awake ()
{
30 of 80
fi
Debug.Log("Awake called.");
}

void Start ()
31 of 80
{
Debug.Log("Start called.");
}
}

32 of 80
Update and FixedUpdate

How to e ect changes every frame with the Update and FixedUpdate functions, and their di erences
• Update is called every frame, if the MonoBehaviour is enabled
• Frame-rate independent MonoBehaviour.FixedUpdate message for physics calculations.
MonoBehaviour.FixedUpdate has the frequency of the physics system; it is called every xed frame-rate
frame. Compute Physics system calculations after FixedUpdate. 0.02 seconds (50 calls per second) is
the default time between calls.
• Use Time. xedDeltaTime to access this value. Alter it by setting it to your preferred value within a script, or,
navigate to Edit > Settings > Time > Fixed Timestep and set it there.
• The FixedUpdate frequency is more or less than Update. If the application runs at 25 frames per second
(fps), Unity calls it approximately 2 per frame, Alternatively, 100 fps causes approximately 2 rendering
frames with 1
• FixedUpdate. Control the required frame rate and Fixed Timestep rate from Time settings. Use
Application.targetFrameRate to set the frame rate

🎞 19. Update And Fixed Update in Unity


Update and FixedUpdate - Code

33 of 80
ff
fi
fi
ff
using UnityEngine;
using System.Collections;

public class UpdateAndFixedUpdate : MonoBehaviour


{
34 of 80
void FixedUpdate ()
{
Debug.Log("FixedUpdate time :" + Time.deltaTime);
}

void Update ()
{
Debug.Log("Update time :" + Time.deltaTime);
}
}

Example 2
public class Background : MonoBehaviour
{
private float updateCount = 0;
private float fixedUpdateCount = 0;
private float updateCountPerSecond = 0;
private float fixedUpdateCountPerSecond = 0;

// Start is called before the first frame update


void Start()
{
Debug.Log("start");
StartCoroutine(Loop());
}

// Update is called once per frame


void Update()
{

35 of 80
updateCount++;
}

void FixedUpdate()
{
fixedUpdateCount++;
}

void OnGUI()
{
GUI.Label(new Rect(10, 70, 100, 20), "Update: " + updateCountPerSecond + " FPS");
GUI.Label(new Rect(10, 90, 100, 20), "FixedUpdate: " + fixedUpdateCountPerSecond + " FPS");
}

IEnumerator Loop(){
while(true){
yield return new WaitForSeconds(1);
updateCountPerSecond = updateCount;
fixedUpdateCountPerSecond = fixedUpdateCount;

updateCount = 0;
fixedUpdateCount = 0;
}
}
}

36 of 80
DeltaTime

It’s the essentially the time between each update or xed update function call.

37 of 80
fi
🎞 23. DeltaTime in Unity
UsingDeltaTimes
///Remember to add Light component to Gameobject first
public class Background : MonoBehaviour
{
public float speed = 8f;
public float countdown = 3.0f;

// Update is called once per frame


void Update()
{
countdown -= Time.deltaTime;
if(countdown <= 0.0f)
{
GetComponent<Light>().enabled = true;
}

if(Input.GetKey(KeyCode.RightArrow)) {
transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
}
if(Input.GetKey(KeyCode.LeftArrow)) {
transform.position -= new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
}
}
}

38 of 80
Vector Maths

We use vectors to de ne meshes, directions…

🎞 20. C# Vector Maths in Unity

39 of 80
fi
GetButton and GetKey

How to get a button or a key for input in a Unity project, and how these axes behave or can be modi ed with
the Unity Input manager

40 of 80

fi
🎞 14. C# GetButton and GetKey in Unity
KeyInput

using UnityEngine;
using System.Collections;

public class KeyInput : MonoBehaviour


{
public GUITexture graphic;
public Texture2D standard;
public Texture2D downgfx;
public Texture2D upgfx;
public Texture2D heldgfx;

void Start()
{
graphic.texture = standard;
}

void Update ()
{
bool down = Input.GetKeyDown(KeyCode.Space);
bool held = Input.GetKey(KeyCode.Space);
bool up = Input.GetKeyUp(KeyCode.Space);

41 of 80
if(down)
{
graphic.texture = downgfx;
}
else if(held)
{
graphic.texture = heldgfx;
}
else if(up)
{
graphic.texture = upgfx;
}
else
{
graphic.texture = standard;
}

guiText.text = " " + down + "\n " + held + "\n " + up;
}
}

ButtonInput

using UnityEngine;
using System.Collections;
42 of 80
public class ButtonInput : MonoBehaviour
{
public GUITexture graphic;
public Texture2D standard;
public Texture2D downgfx;
public Texture2D upgfx;
public Texture2D heldgfx;

void Start()
{
graphic.texture = standard;
}

void Update ()
{
bool down = Input.GetButtonDown("Jump");
bool held = Input.GetButton("Jump");
bool up = Input.GetButtonUp("Jump");

if(down)
{
graphic.texture = downgfx;
}
else if(held)
{
43 of 80
graphic.texture = heldgfx;
}
else if(up)
{
graphic.texture = upgfx;
}
else
{
graphic.texture = standard;
}

guiText.text = " " + down + "\n " + held + "\n " + up;
}
}

44 of 80
OnMouseDown

How to detect mouse clicks on a Collider or GUI element

45 of 80
🎞 17. C# OnMouseDown in Unity

MouseClick

///Remember to add Rigidbody component to Gameobject first


public class Background : MonoBehaviour
{private Rigidbody rb;

private void Awake() {


rb = GetComponent<Rigidbody>();
}

void OnMouseDown ()
{
rb.AddForce(-transform.forward * 500f);
rb.useGravity = true;
}
}

46 of 80
GetAxis

How to "get axis" based input for your games in Unity and how these axes can be modi ed with the Input
manager

47 of 80

fi
🎞 18. C# GetAxis in Unity

Returns the value of the virtual axis identi ed by axisName.


The value will be in the range -1...1 for keyboard and joystick input devices. The meaning of this value
depends on the type of input control, for example with a joystick's horizontal axis a value of 1 means the
stick is pushed all the way to the right and a value of -1 means it's all the way to the left; a value of 0 means
the joystick is in its neutral position.

If the axis is mapped to the mouse, the value is di erent and will not be in the range of -1...1. Instead it'll be
the current mouse delta multiplied by the axis sensitivity. Typically a positive value means the mouse is
moving right/down and a negative value means the mouse is moving left/up.

This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this
value.

To set up your input or view the options for axisName, go to Edit > Project Settings > Input Manager

AxisExample

public class Background : MonoBehaviour{


public float speed = 10.0f;
public float rotationSpeed = 100.0f;

void Update()
48 of 80
fi
ff
{
//Get camera transform
Transform cameraTransform = Camera.main.transform;

// Get the mouse delta. This is not in the range -1...1


float translation = Input.GetAxis("Mouse Y");
float rotation = Input.GetAxis("Mouse X");

// Make it move 10 meters per second instead of 10 meters per frame...


translation *= Time.deltaTime * speed;
rotation *= Time.deltaTime * rotationSpeed;

// Move translation along the object's z-axis


cameraTransform.Translate(0, 0, translation);

// Rotate around our y-axis


cameraTransform.Rotate(0, rotation, 0);
}
}

AxisRawExample

using UnityEngine;
using System.Collections;

public class AxisRawExample : MonoBehaviour


{
public float range;
49 of 80
public GUIText textOutput;

void Update ()
{
float h = Input.GetAxisRaw("Horizontal");
float xPos = h * range;

transform.position = new Vector3(xPos, 2f, 0);


textOutput.text = "Value Returned: "+h.ToString("F2");
}
}

50 of 80
Instantiate

How to use Instantiate to create clones of a Prefab during runtime

51 of 80
🎞 12. C# Instantiate in Unity
Using Instantiate

//1. Create and connect prefab to this script first


//2. Use Instantiate
public class Background : MonoBehaviour
{
public GameObject playerPrefab;
// Update is called once per frame
void Update()
{
//Check fire key down
if (Input.GetKeyDown(KeyCode.Space))
{
//Radomly position around this object
Vector3 pos = new Vector3(Random.Range(-1, 1), Random.Range(2, 10), Random.Range(-1,
1));
//Get the rigidbody component
GameObject newObj = Instantiate(playerPrefab, pos, Quaternion.identity);
//Add force to the object
newObj.GetComponent<Rigidbody>().AddForce(-pos * 10);
}
}
}

52 of 80
Destroy

How to use the Destroy() function to remove GameObjects and Components at runtime.

53 of 80
🎞 15. C# Destroy in Unity
//1. Create and connect prefab to this script first
//2. Use Instantiate
public class Background : MonoBehaviour
{
public GameObject playerPrefab;
// Update is called once per frame
void Update()
{
//Check fire key down
if (Input.GetKeyDown(KeyCode.Space))
{
//Radomly position around this object
Vector3 pos = new Vector3(Random.Range(-1, 1), Random.Range(2, 10),
Random.Range(-1, 1));
//Get the rigidbody component
GameObject newObj = Instantiate(playerPrefab, pos, Quaternion.identity);
//Add force to the object
newObj.GetComponent<Rigidbody>().AddForce(-pos * 10);

Destroy(newObj, 5);

//or use Coroutine


//StartCoroutine(DestroyObject(newObj));
}
}

//Create coroutine to destroy object after 5 seconds


IEnumerator DestroyObject(GameObject obj)
{
yield return new WaitForSeconds(5);
Destroy(obj);
}
54 of 80
}

DestroyComponent

using UnityEngine;
using System.Collections;

public class DestroyComponent : MonoBehaviour


{
void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy(GetComponent<MeshRenderer>());
}
}
}

55 of 80
Activating GameObjects

Handling the active status of GameObjects in the scene, both independently and within Hierarchies, using
SetActive and activeSelf / activeInHierarchy

🎞 24. Activating GameObjects in Unity

56 of 80
GameObject.activeSelf : This returns the local active state of this GameObject, which is set using
GameObject.SetActive. Note that a GameObject may be inactive because a parent is not active, even if this
returns true
GameObject.activeInHierarchy: De nes whether the GameObject is active in the Scene. This lets you
know whether a GameObject is active in the game. That is the case if its GameObject.activeSelf property is
enabled, as well as that of all its parents.

ActiveObjects

using UnityEngine;
using System.Collections;

public class ActiveObjects : MonoBehaviour


{
void Start ()
{
gameObject.SetActive(false);
}
}

CheckState
57 of 80
fi
using UnityEngine;
using System.Collections;

public class CheckState : MonoBehaviour


{
public GameObject myObject;

void Start ()
{
Debug.Log("Active Self: " + myObject.activeSelf);
Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
}
}

58 of 80
Translate and Rotate

Using the two transform functions Translate and Rotate to e ect a non-rigidbody object's position and
rotation

59 of 80
ff
🎞 25. Translate and Rotate in Unity
TransformFunctions

using UnityEngine;
using System.Collections;

public class TransformFunctions : MonoBehaviour


{
public float moveSpeed = 10f;
public float turnSpeed = 50f;

void Update ()
{
if(Input.GetKey(KeyCode.UpArrow))
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);

if(Input.GetKey(KeyCode.DownArrow))
transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);

if(Input.GetKey(KeyCode.LeftArrow))
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);

if(Input.GetKey(KeyCode.RightArrow))
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
60 of 80
}
}

61 of 80
Look At

How to make a game object's transform face another's by using the LookAt function.

🎞 26. C# LookAt in Unity

62 of 80
CameraLookAt

//Create player GameObject and set it first as property


public class Camera : MonoBehaviour
{
public GameObject player;

// Update is called once per frame


void Update()
{
transform.LookAt(player.transform);
}
}

63 of 80
Linear Interpolation

When making games it can sometimes be useful to linearly interpolate between two values. This is done with
a function called Lerp.

Linearly interpolating is nding a value that is some percentage between two given values

For example, we could linearly interpolate between the numbers 3 and 5 by 50% to get the number 4.
This is because 4 is 50% of the way between 3 and 5.

In Unity there are several Lerp functions that can be used for different types. For the example we have
just used, the equivalent would be the Mathf.Lerp function and would look like this:

// In this case, result = 4


float result = Mathf.Lerp (3f, 5f, 0.5f);

If it was 0, the function would return the ‘from’ value and if it was 1 the function would return the ‘to’
value

Other examples of Lerp functions include Color.Lerp and Vector3.Lerp. These work in exactly the
same way as Mathf.Lerp but the ‘from’ and ‘to’ values are of type Color and Vector3 respectively

Vector3 from = new Vector3 (1f, 2f, 3f);


Vector3 to = new Vector3 (5f, 6f, 7f);
64 of 80
fi
// Here result = (4, 5, 6)
Vector3 result = Vector3.Lerp (from, to, 0.75f);

In this case the result is (4, 5, 6) because 4 is 75% of the way between 1 and 5; 5 is 75% of the way
between 2 and 6 and 6 is 75% of the way between 3 and 7.

65 of 80
Conventions and Syntax

Learn about some basic conventions and syntax of writing code - dot operators, semi-colons, indentation
and commenting.

🎞 03. Conventions and Syntax

66 of 80
C# If Statements

🎞 04. C# If Statements

67 of 80
using UnityEngine;
using System.Collections;

public class IfStatements : MonoBehaviour


{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;

void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();

coffeeTemperature -= Time.deltaTime * 5f;


}

void TemperatureTest ()
{
// If the coffee's temperature is greater than the hottest drinking temperature...
if(coffeeTemperature > hotLimitTemperature)
{
// ... do this.

68 of 80
print("Coffee is too hot.");
}
// If it isn't, but the coffee temperature is less than the coldest drinking temperature...
else if(coffeeTemperature < coldLimitTemperature)
{
// ... do this.
print("Coffee is too cold.");
}
// If it is neither of those then...
else
{
// ... do this.
print("Coffee is just right.");
}
}
}

69 of 80
Loops

How to use the For, While, Do-While, and For Each Loops to repeat actions in code.

🎞 05. C# Loops in Unity.mp4

70 of 80
ForLoop

using UnityEngine;
using System.Collections;

public class ForLoop : MonoBehaviour


{
int numEnemies = 3;

void Start ()
{
for(int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
}

WhileLoop

using UnityEngine;
using System.Collections;

71 of 80
public class WhileLoop : MonoBehaviour
{
int cupsInTheSink = 4;

void Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
}

DoWhileLoop

using UnityEngine;
using System.Collections;

public class DoWhileLoop : MonoBehaviour


{
void Start()
{
bool shouldContinue = false;
72 of 80
do
{
print ("Hello World");

}while(shouldContinue == true);
}
}

ForeachLoop

using UnityEngine;
using System.Collections;

public class ForeachLoop : MonoBehaviour


{
void Start ()
{
string[] strings = new string[3];

strings[0] = "First string";


strings[1] = "Second string";
strings[2] = "Third string";

foreach(string item in strings)


73 of 80
{
print (item);
}
}
}

74 of 80
Switch Statements

Switch statements act like streamline conditionals. They are useful for when you want to compare a single
variable against a series of constants

75 of 80
🎞 08. C# Switch Statements
ConversationScript

using UnityEngine;
using System.Collections;

public class ConversationScript : MonoBehaviour


{
public int intelligence = 5;

void Greet()
{
switch (intelligence)
{
case 5:
print ("Why hello there good sir! Let me teach you about
Trigonometry!");
break;
case 4:
print ("Hello and good day!");
break;
case 3:
print ("Whadya want?");
break;
76 of 80
case 2:
print ("Grog SMASH!");
break;
case 1:
print ("Ulg, glib, Pblblblblb");
break;
default:
print ("Incorrect intelligence level.");
break;
}
}
}

77 of 80
Enumerations

Enumerations allow you to create a collection of related constants.

78 of 80
🎞 09. C# Enumerations
EnumScript

using UnityEngine;
using System.Collections;

public class EnumScript : MonoBehaviour


{
enum Direction {North, East, South, West};

void Start ()
{
Direction myDirection;

myDirection = Direction.North;
}

Direction ReverseDirection (Direction dir)


{
if(dir == Direction.North)
dir = Direction.South;
else if(dir == Direction.South)
dir = Direction.North;
else if(dir == Direction.East)
dir = Direction.West;
79 of 80
else if(dir == Direction.West)
dir = Direction.East;

return dir;
}
}

80 of 80

You might also like