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

unity scripting basics 3

The document provides an overview of key Unity concepts, including the use of Time.deltaTime for frame rate independence in movement, the Vector2 structure for 2D vectors, and methods for accessing components and managing game object states. It explains the differences between Awake, Start, Update, FixedUpdate, and LateUpdate functions, emphasizing their roles in the Unity script lifecycle. Additionally, it covers input handling through GetKey and GetButton methods, and the importance of using Time.deltaTime for consistent gameplay experiences across varying frame rates.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unity scripting basics 3

The document provides an overview of key Unity concepts, including the use of Time.deltaTime for frame rate independence in movement, the Vector2 structure for 2D vectors, and methods for accessing components and managing game object states. It explains the differences between Awake, Start, Update, FixedUpdate, and LateUpdate functions, emphasizing their roles in the Unity script lifecycle. Additionally, it covers input handling through GetKey and GetButton methods, and the importance of using Time.deltaTime for consistent gameplay experiences across varying frame rates.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Time.

deltaTime
public static float deltaTime;
Description

Use this function to make your game frame rate independent.

Delta means difference between two values. The Delta time property of The Time classes essentially the
time between each update or a fixed update function call. This can be used to smooth out the values used
for movement and other incremental calculation. The time between frames is not constant.

If you add or subtract to a value, every frame chances. you should multiply with Time.deltaTime. When
you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per
second instead of 10 meters per frame.

When called from inside MonoBehaviour's FixedUpdate, returns the fixed framerate delta time.

using UnityEngine;

using System.Collections;

public class ExampleClass : MonoBehaviour {

void Update() {

float translation = Time.deltaTime * 10;

transform.Translate(0, 0, translation);

Vector2
Description

Representation of 2D vectors and points.

This structure is used in some places to represent 2D positions and vectors (e.g. texture coordinates in
a Mesh or texture offsets in Material). In the majority of other cases a Vector3 is used.

Constructors
Vector2 Constructs a new vector with given x, y components.

Static Variables

down Shorthand for writing Vector2(0, -1).

left Shorthand for writing Vector2(-1, 0).

one Shorthand for writing Vector2(1, 1).

right Shorthand for writing Vector2(1, 0).

up Shorthand for writing Vector2(0, 1).

zero Shorthand for writing Vector2(0, 0).

Variables

x X component of the vector.

y Y component of the vector.

GetComponent
One recurrent issue when starting with Unity is how to access the members in one script from another
script. When developing a program, variables are stored in the memory at different locations. If for
instances two objects hold the same script with the same variable names, the compiler would not be able
to figure out which one we are referring to. To prevent this issue, each object in memory cannot see other
objects. It is then necessary to tell one object where the variable it needs is in memory. There are various
way to access variables,

1. GetComponent,
2. SendMessage
3. Static variables
private Transform myTransform = null;
private Rigidbody rigidbody = null;

private void Start()


{
this.myTransform = this.gameObject.GetComponent<Transform>();
this.rigidbody = this.gameObject.GetComponent<Rigidbody>();
}

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;
}
}
}

Activating GameObjects
To activate or deactivate an object via scripting, you can use the SetActive function.
This will switch your object on or off in terms of it being active in the scene.

using UnityEngine;
using System.Collections;

public class ActiveObjects : MonoBehaviour


{
void Start ()
{
gameObject.SetActive(false);
}
}
Here Start function that contains gameaObject.SetActive(false). And you can see that my game object is
currently active. If I press play, the object is deactivated. However, when working with hierarchies of
objects, its important to know that a parent object can be deactivated which will stop a child object being
active in the scene. This is so that you can disable individual objects. But maintain control over groups of
them using the parent object.

To check if an object is active within the scene or in a hierarchy, you can query using the Active Self and
Active in Hierarchy states.

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);
}
}

It should also be noted that when a child object is inactive because its parent is inactive,
using Set Active to True will not make that child object active. It can only become active again once its
parent is made active.

Translate and Rotate

Translate and Rotate are two functions that are commonly used to change the position and rotation of a
game object.

Public class TransformFunction : MonoBehaviour

void update()
{
Transform.Translate(new Vector3(0,0,1));
}

Here the argument of Translate takes a Vector3. This example simply translates down the Z axis. Here
we've used zero for X and Y. It's gonna move by one, every frame,
because it's inside Update.
If we press PLAY, it moves very quickly because it's updating every frame.

By using Translate operation, that means multiply it by Time.deltaTime.

Public class TransformFunction : MonoBehaviour


{
Public float moveSpeed = 10f;
void update()
{
Transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}

This means that it will be moved in meters per second, rather than meters per frame.
Then, instead of saying Vector3(0,0,1) we can use Vector3.forward, And we can then multiply by another
value which we can establish as a separate variable. That way we can control it by adjusting the variable
inside the inspector.

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);
}
}

GetButton and GetKey

In unity GetKey or GetButton are ways of receiving input from keys or joystick buttons
via unity's input class. The core differences between the two is that GetKey specifically names keys for
you using key codes.
The space bar is represented by key code.space. This works just fine for keyboard

if(Input.GetKey(KeyCode.Space))
{
//do somthing
}

function Update () {
if (Input.GetKey (KeyCode.Space))
Debug.Log ("space key is being held down");
}
Here is a list of useful KeyCodes:
KeyCode.Mouse0
KeyCode.Mouse1
KeyCode.Space
KeyCode.Tab
KeyCode.UpArrow
KeyCode.DownArrow
KeyCode.LeftArrow
KeyCode.RightArrow
GetButton / GetButtonDown/ GetButtonUp
The ‘get button’ functions work similarly to the ‘get key’ functions,except you cannot use KeyCodes,
rather you are required to set your own buttons in the input manager. This is the recommended by Unity
and can be quite powerful as it allows developers to map custom joystick / D-pad buttons.

function Update () {

if (Input.GetButtonDown ("Jump"))
Debug.Log ("space bar was pressed");
}
To access the input manager go to Edit > Settings > Input.
Awake and Start
Awake is called when the script instance is being loaded.

Awake is used to initialize any variables or game state before the game starts. Awake is
called only once during the lifetime of the script instance. Awake is always called before
any Start functions. This allows you to order initialization of scripts.

using UnityEngine;
using System.Collections;

public class AwakeAndStart : MonoBehaviour


{
void Awake ()
{
Debug.Log("Awake called.");
}

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

Difference between Start() and Awake() in Unity

Start
Start function is called only if the script component is enabled.
Start and Awake both are only called once in a lifetime.
Start function is called up after Awake and it execute after the first frame Update.
Below is an example showing start function in unity C# :-

1. using UnityEngine;
2. using System.Collections;
3.
4. public class ExampleClass : MonoBehaviour {
5. private GameObject object;
6. void Start()
7. {
8. object = GameObject.FindWithTag("TestPlayer");
9. }
10. }

Awake
Awake function called when the script instance is being loaded.
As we stated above Awake is also called only once during the lifetime of the script
instance.
Awake allows you to order initialization of scripts.
Below is an example showing Awake function in unity C# :-

1. using UnityEngine;
2. using System.Collections;
3.
4. public class ExampleClass : MonoBehaviour
5. {
6. private GameObject object;
7. void Awake()
8. {
9. object = GameObject.FindWithTag("TestPlayer");
10. }
11. }

Update
Update is called once per frame from every script in which it is defined. Calling
of Update function is dependent on the frame rate; for high frame rate the time
interval will be low but for the low frame rate the time interval will be high.

The time interval to call update is not fixed; it depends on how much time
required to complete the individual frame. If a frame takes longer/shorter time
to process as compared to the other one then the update time interval becomes
different for frames.

In unity, Time.deltaTime will provide you time in seconds to complete the last
frame. This can be used to make your game frame independent.

using UnityEngine;
1
2public class UpdateDemo : MonoBehaviour {
3 // Update is called once per frame
4 void Update () {
5 Debug.Log ("Update is called at: " + Time.deltaTime);
6 }
7}
8

Update is commonly used for:


 Moving Game Objects (Non-Physics): While moving a GameObject,
multiply your movement values by Time.deltaTime to make it frame
rate independent.
 Receiving user inputs like mouse down or key press.
 Implementing Simple timers

FixedUpdate
 FixedUpdate is independent from the frame rate. The time interval is to
call FixedUpdate is constant; as it is called on a reliable timer.
 FixedUpdate can be called multiple times per frame if frame rate is low or
it may not be called per frame if the frame rate will be high. So, it is quite
possible that FixedUpdate will be called more than Update.
 When Time.deltaTime will be called from FixedUpdate, it will return the
constant time interval.There is no need to multiply your values to
Time.deltaTime inside the FixedUpdate.

using UnityEngine;

public class UpdateDemo : Mon


/ / FixedUpdate is called ind

1using UnityEngine;
2
3public class UpdateDemo : MonoBehaviour {
4 // FixedUpdate is called independent of frame rate
5 void FixedUpdate()
6 {
7 Debug.Log ("Fixed Update is called at: " + Time.deltaTime);
8 }
9}

All the physics related calculations and updates are called immediately
after FixedUpdate. So, its good to handle all physics related calculation inside
FixedUpdate.
LateUpdate
LateUpdate is also called per frame. It is called after all other Update functions.
Time.deltaTime will provide the time interval for the LateUpdate.

1using UnityEngine;
2
3public class UpdateDemo : MonoBehaviour {
4 // LateUpdate is called after all other Update Functions
5 // called once per frame
6 void LateUpdate () {
7 Debug.Log ("Late Update is called at: " + Time.deltaTime);
8 }
9}

This is useful to ensure all other Update related calculation is complete and
other dependent calculation can be called. For example, if you need to integrate
a third-person camera to follow any object; then it should be implemented inside
the LateUpdate. It is make sure that camera will track the object after its
movement and rotation update.

Execution order
Execution order of above event function in the script life-cycle is: FixedUpdate -
> Update -> LateUpdate

You might also like