unity scripting basics 3
unity scripting basics 3
deltaTime
public static float deltaTime;
Description
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;
void Update() {
transform.Translate(0, 0, translation);
Vector2
Description
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
Variables
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;
using UnityEngine;
using System.Collections;
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;
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;
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 are two functions that are commonly used to change the position and rotation of a
game object.
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.
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;
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);
}
}
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;
void Start ()
{
Debug.Log("Start called.");
}
}
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
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;
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