Beginner Scripting-V2
Beginner Scripting-V2
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
2 of 80
using UnityEngine;
using System.Collections;
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;
5 of 80
Variables and Functions
using UnityEngine;
using System.Collections;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
6 of 80
7 of 80
using UnityEngine;
using System.Collections;
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;
// Constructor
public Stuff ()
{
bullets = 1;
grenades = 1;
rockets = 1;
}
}
void Start()
{
Debug.Log(myStuff.bullets);
}
}
11 of 80
MovementControls
using UnityEngine;
using System.Collections;
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;
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;
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
18 of 80
🎞 06. C# Scope and Access Modi ers
AnotherClass
using UnityEngine;
using System.Collections;
using UnityEngine;
using System.Collections;
void Start ()
20 of 80
fi
{
alpha = 29;
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;
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;
YetAnotherScript
using UnityEngine;
using System.Collections;
24 of 80
public class YetAnotherScript : MonoBehaviour
{
public int numberOfPlayerDeaths = 3;
}
25 of 80
Enabling and Disabling Components
26 of 80
🎞 22. C# Enabling and Disabling Components in Unity
using UnityEngine;
using System.Collections;
void Start ()
{
myLight = GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
27 of 80
Arrays
28 of 80
🎞 11. Arrays
using UnityEngine;
using System.Collections;
void Start ()
{
players = GameObject.FindGameObjectsWithTag("Player");
29 of 80
Awake and Start
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
33 of 80
ff
fi
fi
ff
using UnityEngine;
using System.Collections;
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;
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;
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
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;
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
45 of 80
🎞 17. C# OnMouseDown in Unity
MouseClick
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
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
void Update()
48 of 80
fi
ff
{
//Get camera transform
Transform cameraTransform = Camera.main.transform;
AxisRawExample
using UnityEngine;
using System.Collections;
void Update ()
{
float h = Input.GetAxisRaw("Horizontal");
float xPos = h * range;
50 of 80
Instantiate
51 of 80
🎞 12. C# Instantiate in Unity
Using Instantiate
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);
DestroyComponent
using UnityEngine;
using System.Collections;
55 of 80
Activating GameObjects
Handling the active status of GameObjects in the scene, both independently and within Hierarchies, using
SetActive and activeSelf / activeInHierarchy
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;
CheckState
57 of 80
fi
using UnityEngine;
using System.Collections;
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;
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.
62 of 80
CameraLookAt
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:
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
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.
66 of 80
C# If Statements
🎞 04. C# If Statements
67 of 80
using UnityEngine;
using System.Collections;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
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.
70 of 80
ForLoop
using UnityEngine;
using System.Collections;
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;
}while(shouldContinue == true);
}
}
ForeachLoop
using UnityEngine;
using System.Collections;
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;
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
78 of 80
🎞 09. C# Enumerations
EnumScript
using UnityEngine;
using System.Collections;
void Start ()
{
Direction myDirection;
myDirection = Direction.North;
}
return dir;
}
}
80 of 80