Scripts As Behaviour Components
Scripts As Behaviour Components
using UnityEngine;
using System.Collections;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
/*Hi there!
* this is two lines!
* */
Debug.Log(transform.position.x);
IF Statements
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.
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.");
}
}
}
Loops
For loop:
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;
void Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
}
DoWhileLoop
using UnityEngine;
using System.Collections;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
}
Foreach Loop
using UnityEngine;
using System.Collections;
void Start ()
{
alpha = 29;
AnotherClass
using UnityEngine;
using System.Collections;
void Start ()
{
Debug.Log("Start called.");
}
}
void Update ()
{
Debug.Log("Update time :" + Time.deltaTime);
}
}
void Start ()
{
myLight = GetComponent<Light>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.Space))
{
myLight.enabled = !myLight.enabled;
}
}
}
Activating GameObjects
ActiveObjects
using UnityEngine;
using System.Collections;
CheckState
using UnityEngine;
using System.Collections;
void Start ()
{
Debug.Log("Active Self: " + myObject.activeSelf);
Debug.Log("Active in Hierarchy" +
myObject.activeInHierarchy);
}
}
Translate and Rotate
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);
}
}
Look At
CameraLookAt
using UnityEngine;
using System.Collections;
void Update ()
{
transform.LookAt(target);
}
}
Linear Interpolation
2
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 finding 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);
The Mathf.Lerp function takes 3 float parameters: one representing the value to
interpolate from; another representing the value to interpolate to and a final float
representing how far to interpolate. In this case, the interpolation value is 0.5 which
means 50%. 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. The third parameter in each case is still a float
representing how much to interpolate. The result of these functions is finding a
colour that is some blend of two given colours and a vector that is some percentage
of the way between the two given vectors.
Under some circumstances Lerp functions can be used to smooth a value over time.
Consider the following piece of code:
void Update ()
{
light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f);
}
If the intensity of the light starts off at 0 then after the first update it will be set to 4.
The next frame it will be set to 6, then to 7, then to 7.5 and so on. Thus over several
frames, the lights intensity will tend towards 8 but the rate of its change will slow as it
approaches its target. Note that this happens over the course of several frames. If
we wanted this to not be frame rate dependent then we could use the following code:
Destroy
DestroyBasic
using UnityEngine;
using System.Collections;
DestroyOther
using UnityEngine;
using System.Collections;
void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy(other);
}
}
}
DestroyComponent
using UnityEngine;
using System.Collections;
void Start()
{
graphic.sprite = standard;
}
void Update()
{
bool down = Input.GetKeyDown(KeyCode.Space);
bool held = Input.GetKey(KeyCode.Space);
bool up = Input.GetKeyUp(KeyCode.Space);
if(down)
{
graphic.sprite = downgfx;
}
else if (held)
{
graphic.sprite = heldgfx;
}
else if (up)
{
graphic.sprite = upgfx;
}
else
{
graphic.sprite = standard;
}
ButtonInput
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
void Start()
{
graphic.sprite = standard;
}
void Update()
{
bool down = Input.GetButtonDown("Jump");
bool held = Input.GetButton("Jump");
bool up = Input.GetButtonUp("Jump");
if(down)
{
graphic.sprite = downgfx;
}
else if (held)
{
graphic.sprite = heldgfx;
}
else if (up)
{
graphic.sprite = upgfx;
}
else
{
graphic.sprite = standard;
}
GetAxis
AxisExample
using UnityEngine;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
void Update ()
{
float h = Input.GetAxis("Horizontal");
float xPos = h * range;
AxisRawExample
using UnityEngine;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
void Update ()
{
float h = Input.GetAxisRaw("Horizontal");
float xPos = h * range;
DualAxisExample
using UnityEngine;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
void Update ()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float xPos = h * hRange;
float yPos = v * vRange;
OnMouseDown
MouseClick
using UnityEngine;
using System.Collections;
void OnMouseDown ()
{
rb.AddForce(-transform.forward * 500f);
rb.useGravity = true;
}
}
GetComponent
UsingOtherComponents
using UnityEngine;
using System.Collections;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript =
otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}
void Start ()
{
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;
DeltaTime
UsingDeltaTimes
using UnityEngine;
using System.Collections;
public class UsingDeltaTime : MonoBehaviour
{
public float speed = 8f;
public float countdown = 3.0f;
void Update ()
{
countdown -= Time.deltaTime;
if(countdown <= 0.0f)
light.enabled = true;
if(Input.GetKey(KeyCode.RightArrow))
transform.position += new Vector3(speed *
Time.deltaTime, 0.0f, 0.0f);
}
}
Data Types
DatatypeScript
using UnityEngine;
using System.Collections;
SingleCharacterScript
using UnityEngine;
using System.Collections;
void Update ()
{
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--;
}
}
}
Inventory
using UnityEngine;
using System.Collections;
// Constructor
public Stuff ()
{
bullets = 1;
grenades = 1;
rockets = 1;
}
}
void Start()
{
Debug.Log(myStuff.bullets);
}
}
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);
transform.Rotate(Vector3.up * turnMovement);
}
}
Shooting
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour
{
public Rigidbody bulletPrefab;
public Transform firePosition;
public float bulletSpeed;
void Awake ()
{
inventory = GetComponent<Inventory>();
}
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--;
}
}
}
Instantiate
UsingInstantiate
using UnityEngine;
using System.Collections;
RocketDestruction
using UnityEngine;
using System.Collections;
void Start ()
{
players = GameObject.FindGameObjectsWithTag("Player");
Invoke
InvokeScript
using UnityEngine;
using System.Collections;
void Start()
{
Invoke ("SpawnObject", 2);
}
void SpawnObject()
{
Instantiate(target, new Vector3(0, 2, 0),
Quaternion.identity);
}
}
InvokeRepeating
using UnityEngine;
using System.Collections;
void SpawnObject()
{
float x = Random.Range(-2.0f, 2.0f);
float z = Random.Range(-2.0f, 2.0f);
Instantiate(target, new Vector3(x, 2, z),
Quaternion.identity);
}
}
Enumerations
EnumScript
using UnityEngine;
using System.Collections;
void Start ()
{
Direction myDirection;
myDirection = Direction.North;
}
return dir;
}
}
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;
case 2:
print ("Grog SMASH!");
break;
case 1:
print ("Ulg, glib, Pblblblblb");
break;
default:
print ("Incorrect intelligence level.");
break;
}
}
}