Basic Scripting
Introduction
This text will introduce you to scripting for your game objects.
General Object Scripting
When you create a script, the below code will be generated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptName: MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
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;
Random int Value from [low, high]:
UnityEngine.Random.Range(lowIntValue, highIntValue);
Random float Value from [low, high]:
UnityEngine.Random.Range(lowFloatValue, highFloatValue);
Vectors Basics
Unity vectors are objects are can be 2D storing x and y values or 3D storing x, y
and z values.
Creating and Initializing a 2D vector:
Vector2 name = new Vector2(x, y);
Creating and Initializing a 3D vector:
Vector2 name = new Vector2(x, y,z);
Accessing a Vector Component:
name.component
Example:
Page 2
position.x;
Vector components cannot be directly affected. To modify a vector, the entire
vector has to be replaced or added to by another vector.
Replacing a Vector2 with a new Vector2:
name = new Vector2(x,y);
Adding to a Vector2:
name += new Vector2(x,y);
Replacing a Vector3 with a new Vector3:
name = new Vector3(x,y,z);
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.
To normalize a Vector2 or Vector3 call its Normalize method:
vectorName.Normalize();
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.
Tracking Elapsed Time
When determining how much time has passed, we will Time.deltaTime multiplied
by 1000 to find the number of milliseconds have elapsed since the last update.
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
x bool activeSelf True when the object is
active in the scene. Active
objects will be seen and
interact with other objects.
Inactive objects are not
seen and do not interact
with other objects.
x GameObject gameObject The current game object.
x x int layer The object’s layer number.
Sprites with a higher layer
number will be drawn on
top of sprites with lower
numbers. A layer be 0,
positive or negative.
x x string name The object’s name.
x Scene scene The scene the object
belongs to.
x x string tag The tag that categories the
object.
x Transform transform Stores the position, scale
and rotation of the object.
GameObject Instance Methods:
Type Method Header Description
void SetActive(bool active) When active is true, the object will be
activated and deactivated when false.
Page 4
Finding other Objects at Runtime
The below GameObject static methods are can be used to retrieve other
GameObjects during runtime.
Type Method Header Description
GameObject Find(string name) Returns the active game object
with provided name or null if no
object is found.
For objects with parents, you
must supply all its parent
names as well, in the format:
“ObjectName\ObjectName\Obje
ctName”.
Example:
“Car\DiverDoor\Window” denotes
that the Window we are looking for
is in the Car object with a direct
parent of DriverDoor.
GameObject[] FindGameObjectsWithTag(str Returns all the active Objects with
ing tag) the given tag, or an empty array if
no objects have the provided tag.
GameObject FindWithTag(string tag) Returns one active object with the
provided tag, null if there are no
active objects with the given tag.
Storing Component References
When you need to access a component of an object multiple times, it is best to
create a variable that references the component. This will make your code more
simple.
Storing a Script Reference:
NameOfComponent variableName =
gameObject.GetComponent<NameOfComponent>();
Accessing Scripts and Attributes
Scripts can be accessed through the use of the GameObject GetComponent
method. Through a script, you have can access all public attributes and methods
of the Script. Remember that only constants should be public, and all
Page 5
changeable attributes should be private. When accessing / modifying
private attributes, you must use getter and setter methods.
Format for Accessing a public Attribute From an Object Script:
gameObject.GetComponent<ScriptName>().attributeName
Format for Accessing a public Method From an Object Script:
gameObject.GetComponent<ScriptName>().MethodName(parameters)
Storing a Script Reference:
ScriptName variableName =
gameObject.GetComponent<ScriptName>();
Scene
Scene Attributes:
Read Write Type Attribute Access Description
Access Access
x string name The name of the scene.
Transform
Used to access / modify the scale, position and rotation of an object.
Transform Attributes:
Read Write Type Attribute Access Description
Access Access
x x Vector3 localPosition The object's position in local
space. The object’s position
in reference to its parent.
x x Vector3 localScale The object's scale in local
space. The object’s scale in
reference to its parent.
x GameObject gameObject The object that owns this
transform.
x x Transform parent The transform of the parent
object.
x x Transform position A vector representing the
position of the object with
Page 6
respect to the world.
x Transform root The topmost transform in
the hierarchy.
Transform Instance Methods:
Type Method Header Description
bool IsChildOf(Transform transform) True if this transform is a child of
the provided transform.
Vector3 InverseTransformPoint(Vector3 Transforms the provided point
position); from world to local space.
Vector3 InverseTransformPoint(float x, float Transforms the point (x, y, z)
y, float z); vector from world to local space.
void SetParent(Transform t) Sets the parent transform.
Vector3 TransformVector(float x, float y, Transforms the provided vector (x,
float z); y, z) from local to world space.
Vector3 TransformPoint(Vector3 position); Transforms the provided point
from local to world space.
Vector3 TransformPoint(float x, float y, float Transforms the provided point (x,
z); y, z) from local to world space.
Vector3 Translate(float x, float y, float z, Moves the object by the given
Space relativeTo = Space.Self); vector. Space is optional and by
default will use Space.Selft
(local). Use Space.World to
translate with respect to the
world.
Setting the Object’s position:
transform.position = new Vector2(x,y);
Or
transform.position = vector2Varaible;
Or
transform.position = new Vector3(x,y,z);
Or
transform.position = vector3Varaible;
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.
Modify an Object’s position with Transform:
transform.Transform(x,y,0);
Or
transform.Transform(new Vector3(x,y,0));
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
Accessing width of a sprite:
GetComponent<SpriteRenderer>().bounds.x
Accessing height of a sprite:
GetComponent<SpriteRenderer>().bounds.y
Flipping the direction of an animation:
If you want your sprite to face in the opposite direction, you will need to access the
SpriteRenderer and set its flipX or flipY property.
GetComponent<SpriteRenderer>().flipX =true;
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.
Input static Methods:
Type Method Header Description
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 GetKey(KeyCode key) True if the keep is in the down state.
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.
bool GetMouseButton(int button) True when the provided mouse button is in
the down state.
Mouse Event Methods:
Type Method Header Description
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.
void onMouseEnter() Occurs when the mouse position starts overlapping an
object’s collider.
void onMouseExit() Occurs when the mouse position starts overlapping an
Page 9
object’s collider.
Mouse Position in World Coordinates
The below command will get the mouse position as a Vector3 in world coordinates:
Camera.main.ScreenToWorldPoint(Input.mousePosition)
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.
Circle casting is drawing an invisible circle that moves in a direction from a
point, tracking what object(s) are hit by it.
Physics2 public static Methods
Method Header Description
RaycastHit2D BoxCast(Vector2 Returns the first object hit by the proved
origin, Vector2 size, float box. The settings are explained below
angle, Vector2 direction, float this chart.
distance = Mathf.Infinity, int
layerMask =
Physics2D.AllLayers, float
minDepth = -Mathf.Infinity,
float maxDepth =
Mathf.Infinity);
RaycastHit2D[] Returns all the objects hit by the proved
BoxCastAll(Vector2 origin, box. The settings are explained below
Vector2 size, float angle, this chart.
Vector2 direction, float
distance = Mathf.Infinity, int
layerMask =
DefaultRaycastLayers, float
minDepth = -Mathf.Infinity,
float maxDepth =
Mathf.Infinity);
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);
RaycastHit2D[] Returns all the objects hit by the proved
CircleCastAll(Vector2 origin, circle. The settings are explained below
float radius, Vector2 this chart.
direction, float distance =
Mathf.Infinity, int layerMask =
DefaultRaycastLayers, float
minDepth = -Mathf.Infinity,
float maxDepth =
Mathf.Infinity);
RaycastHit2D Raycast( Returns the first object hit by the raycast,
Vector2 origin, null if nothing was hit. The settings are
Vector2 direction, explained below this chart.
float distance =Mathf.Infinity,
int layerMask =
DefaultRaycastLayers,
float minDepth =
-Mathf.Infinity,
float maxDepth =
Mathf.Infinity);
RaycastHit2D[] RaycastAll( Returns all the objects hit by the raycast,
Vector2 origin, null if nothing was hit. Hit objects will
Vector2 direction, appear in the list and be ordered by their
float distance = distance from the origin point. The
Mathf.Infinity, settings are explained below this
int layerMask = chart.
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.
Visually Indicating a Raycast
You can’t see ray casts when you are running your game, but there is a Debug
command that will draw a ray on the screen. It is a good idea when using ray
casting to use Debug to give a visual line of your ray cast. The command to draw
a ray on the screen is:
Debug.DrawRay(Vector3 start, Vector3 dir, Color color =
Color.white, float duration = 0.0f, bool depthTest = true);
Draw Ray Parameters:
● start - the point the ray will start from
● dir - the direction of the ray
● color - the color of the ray
○ Example: Color.green
● duration - how long the ray will be visible in seconds
● depthTest - if the line will be obscured by other objects closer to the
camera.
Terms
Term Daccessingefinition
Normalized Vector A vector that has changed to length 1, but maintains its
direction.
Ray Casting Drawing an invisible line in a direction and tracking what
object(s) are hit by the invisible line.
Vector An object that stores either a (x,y) or (x,y,z) value.
Page 13