GD4 - Basic Scripting (1)
GD4 - Basic Scripting (1)
Introduction
This text will introduce you to scripting for your game objects.
void Awake()
This method is only called once during the life of the script. It is evoked when the
object is initialized or created. Awake is always invoked before start.
void Start()
This method is only called once, during the life of the script. Start is called on the
first frame that the object becomes active.
void Update()
The Update method is invoked at every frame of the game. This method is good
for checking for user inputs.
void FixedUpdated()
The fixedUpdate method is invoked at every physics frame. This method is good
for altering game data, like object positions, scale, direction, rotation, velocity, forces,
etc. This method should be added to most of your scripts.
Page 1
public Attributes
In a script, public attributes will be accessible by other object scripts and their
values can be edited through inspector. Non-constant public attributes violate
the principle of information hiding and should not be used. Make attributes
private, with getters and setters as needed.
private Attributes
In a script, private attributes will be accessible in the script where they were
created.
[SerializeFeild] Attributes
Any attribute that has the [SerializeField] modifier will show up in the Script
component of the inspector and can be modified through Unity. If you want other
scripts to be able to view or modify a [SerializeField] you will need to create a
getter and/or setter.
Random Numbers
Required Import for Random:
using UnityEngine;
Vectors Basics
Unity vectors are objects are can be 2D storing x and y values or 3D storing x, y
and z values.
Example:
Page 2
position.x;
Adding to a Vector2:
name += new Vector2(x,y);
Adding to a Vector3:
name += new Vector3(x,y,z);
You can replace or add to a vector with another vector, it does not have to
be newly created.
A normalized vector is a vector that has changed to length 1, but maintains its
direction.
Delta Time
The number of frames you get per second may very computer to computer or
even fluctuate during a single execution of your game. If you were to move your
character a fixed distance each game update, you may notice your character’s
speed fluctuating during game play.
To resolve this problem, you can multiply any movement, scaling or rotation
values by the ratio stored in Time.deltaTime. This will split up the movement
value over all the updates performed over a second. With a value being split over
many updates, a large value will need to used.
Page 3
Calculating milliseconds that have elapsed since last update:
Time.deletaTime*1000f;
GameObject
All objects in Unity are of type GameObject.
Game Attributes:
Read Write Type Attribute Access Description
Access Access
Page 4
Finding other Objects at Runtime
The below GameObject static methods are can be used to retrieve other
GameObjects during runtime.
Example:
“Car\DiverDoor\Window” denotes
that the Window we are looking for
is in the Car object with a direct
parent of DriverDoor.
Page 5
changeable attributes should be private. When accessing / modifying
private attributes, you must use getter and setter methods.
Scene
Scene Attributes:
Read Write Type Attribute Access Description
Access Access
Transform
Used to access / modify the scale, position and rotation of an object.
Transform Attributes:
Read Write Type Attribute Access Description
Access Access
Page 6
respect to the world.
Page 7
Modify an Object’s position through vector addition:
transform.position += new Vector3(x,y,0);
Or
transform.position += vector3Varaible;
position is a Vector3, so you can only add a Vector 3 to it.
Sprite Renderer
Changing the color of a sprite:
GetComponent<SpriteRenderer>().color = new Color(red, green, blue);
red / green / blue - are values from 0f to 1f
Or
GetComponent<SpriteRenderer>().color = Color.ColorName
KeyCode
This class stores several constants for representing different keyboard keys and
mouse buttons. If you type KeyCode. it will bring up a list of constants for keys
and mouse buttons like: KeyCode.R, KeyCode.UpArrow, KeyCode.Insert, etc.
KeyCode.Mouse0 is the left mouse button, KeyCode.Mouse1 is the middle
mouse button and KeyCode.Mouse3 is the right mouse button. Note: You can
use 0,1,2 in place of KeyCode.Mouse0, KeyCode.Mouse1, KeyCode.Mouse2.
Page 8
Input
The input class has static methods for checking the status of keys and mouse
buttons.
bool GetKeyDown(KeyCode key) True when the provided key went down
during the frame, false otherwise.
bool GetKeyUp(KeyCode key) True when the provided key went up during
the frame, false otherwise.
bool GetMouseButtonDown(int button) True when the provided mouse button went
down during the frame, false otherwise.
bool GetMouseButtonUp(int button) True when the provided mouse button went
down during the frame, false otherwise.
void OnMouseDown() Occurs when the mouse is pressed down on the collider of an
object.
void onMouseUp() Occurs when the mouse is when the mouse goes up, after
being pressed down an object’s collider. The up will be sent
to the object that was originally pressed down on, even if no
longer the release occurred outside the collider of the object.
void onMouseDrag() Occurs when the mouse is when the mouse moves and is still
down, after being pressed down an object’s collider. The drag
will be sent to the object that was originally pressed down on,
even if no longer the release occurred outside the collider of
the object.
Page 9
object’s collider.
Casting
Ray casting is drawing an invisible line in a direction and tracking what object(s)
are hit by the invisible line. The commands for ray casting are in Physics2D
class. Two common reasons for adding more tilemaps, are separating collidable /
non-collidable art and laying art on top of each other.
Box casting is drawing an invisible box that moves in a direction from a point,
tracking what object(s) are hit by it.
Page 10
RaycastHit2D CircleCast(Vector2 Returns the first object hit by the proved
origin, float radius, Vector2 circle. The settings are explained below
direction, float distance = this chart.
Mathf.Infinity, int layerMask =
DefaultRaycastLayers, float
minDepth = -Mathf.Infinity,
float maxDepth =
Mathf.Infinity);
Boxcast parameters:
● origin - the starting position the box will travel from.
● size - the size vector of the box.
● angle - the angle vector of the box, the rotation of the box.
Page 11
● direction - the direction vector for the box to travel.
● distance - the maximum distance that the box will travel.
● layerMask - the layers that collisions should be checked on. To create a mask
based on layer names, use this command:
○ LayerMask.GetMask(LostOfStringValues);
■ Example:LayerMask.GetMask(“Walls”,”Enemies”);
● minDepth - anything with z smaller than this value is ignored for collisions
● maxDepth - anything with z greater than this value is ignored for collisions
Circlecast parameters:
● origin - the starting position the circle will travel from.
● size - the size vector of the circle.
● direction - the direction vector for the circle to travel.
● distance - the maximum distance that the circlewill travel.
● layerMask - the layers that collisions should be checked on. To create a mask
based on layer names, use this command:
○ LayerMask.GetMask(LostOfStringValues);
■ Example:LayerMask.GetMask(“Walls”,”Enemies”);
● minDepth - anything with z smaller than this value is ignored for collisions
● maxDepth - anything with z greater than this value is ignored for collisions
Raycast parameters:
● origin - the position the ray is being drawn from.
● direction - the direction vector of the array.
● distance - the maximum distance that the ray will travel.
● layerMask - the layers that collisions should be checked on. To create a mask
based on layer names, use this command:
○ LayerMask.GetMask(LostOfStringValues);
■ Example:LayerMask.GetMask(“Walls”,”Enemies”);
● minDepth - anything with z smaller than this value is ignored for collisions
● maxDepth - anything with z greater than this value is ignored for collisions
RaycastHit2D
RaycastHit2D stores the result of the raycast collision.
Raycast Properties:
Type Property Description
Collider2D collider The collider hit by the ray.
Page 12
float distance The distance from the ray origin to the impact
point.
Vector2 normal The normal vector of the surface that was hit by
the ray.
Vector2 point The point in world space where the ray hit the
collider’s surface.
RigidBody2D rigidbody The Rigidbody2D attached to the hit object.
Transform transform The Transform of the object that was hit by the
ray.
Normalized Vector A vector that has changed to length 1, but maintains its
direction.
Page 13