Scripting 101
*************
.. |b| raw:: html
Transform
=========
.. |barre| raw:: html
transform.position.x
.. warning:: Writing *transform.position = P;* is ok. But it is not allowed to set only one parameter: |barre| = 4
Coordinates
-----------
World
^^^^^
.. list-table::
:widths: 40 60
:header-rows: 0
* - |b| Vector3 P = transform.position;
- Get position
* - |b| float x = transform.position.x;
- Get X-coordinate
* - |b| transform.position = P;
- Set position
* - |b| transform.rotation = Quaternion.Euler(0f, 90f, 0f);
- Rotation relative to the world axis
Local
^^^^^
.. list-table::
:widths: 100
:header-rows: 0
* - |b| Vector3 P = transform.localPosition;
* - |b| transform.localrotation =
Moving
------
World
^^^^^
.. list-table::
:widths: 40 60
:header-rows: 0
* - |b| transform.Translate(dirVector3)
- Translate by a given vector
* - |b| transform.Translate(x, y, z)
- Translate by x, y, z values
* - |b| transform.Rotate(rotAngle3);
- Rotate using a Vector3 angle
* - |b| transform.Rotate(rx, ry, rz);
- Rotate using individual angles on each axis
Local
^^^^^
.. list-table::
:widths: 100
:header-rows: 0
* - |b| transform.Translate(dirVector3, Space.Self)
* - |b| transform.Rotate(rotAngle3, Space.Self);
Built-In Properties
===================
There are predefined properties and methods that are automatically available in a MonoBehaviour script.
Since they are not explicitly defined in the code, this can lead to some confusion.
.. list-table::
:widths: 20 20 60
* - |b| gameObject
- GameObject
- The current GameObject this script is attached to
* - |b| transform
- Transform
- The transform of the current gameObject
* - |b| tag
- string
- The tag of the GameObject
* - |b| name
- string
- The name of the GameObject
* - |b| Instantiate(Class,pos,rot);
- given Class
- Create new gameObject in the scene
.. warning: The keyword this is a reference to the script (GameComponent)
Lifecycle Methods
=================
MonoBehavior functions automatically called by Unity
.. list-table::
:widths: 40 60
* - |b| Start()
- Used to initialize objects, variables, or references before the first frame update.
* - |b| Update()
- Every frame, handles non-physics updates: user input, animations and logic
* - |b| FixedUpdate()
- At fixed intervals (0.02s), used for physics-related logic and Rigidbody interactions
* - |b| void OnTriggerEnter(Collider other)
- Detect an object entering the collider set in trigger mode
* - |b| void OnTriggerExit(Collider other)
-
* - |b| void OnMouseOver()
- Mouse pointer passes over the object
* - |b| void OnMouseDown()
- Mouse click on the object
Useful helper class
===================
Some utility classes, imported by *using UnityEngine*, may be handy:
.. list-table::
:header-rows: 0
:widths: 25 15 60
* - |b| Debug.Log(..)
- Debug
- Display logs, warnings, and errors
* - |b| Mathf.Abs(..)
- Mathf
- Mathematical functions: sin, cos, clamp, lerp, etc.
* - |b| Random.Range(0, 3)
- Random (int)
- Integer random value among 0, 1, 2
* - |b| Random.Range(0f, 3f)
- Random (float)
- Float random value like 0.4, 2.5...
* - |b| Time.time
- Time
- Time since the start of the scene
* - |b| Time.deltaTime
-
- Time passed since the last frame
* - |b| Input.GetKey(..)
- Input
- Reading keyboard
* - |b| Input.mousePosition
-
- Reading mouse
* - |b| Input.GetAxis("Horizontal")
-
- Reading joystick
* - |b| SceneManager.LoadScene(..)
- SceneManagement
- Load or add a scene
* - |b| PlayerPrefs.Set/Get
- PlayerPrefs
- Persistent data storage
* - |b| Physics.Raycast(ray, ..)
- Physics
- Raycasting technique
* - |b| Selection.activeGameObject
- Selection
- current selected gameObject in the scene view
Hierarchy
=========
GameObject
----------
All parent/child relationship are stored in the *transform* parameter of a gameobject:
.. list-table::
:header-rows: 0
:widths: 40 60
* - |b| GameObject obj = GameObject.Find('Name');
- find an object by name
* - |b| GameObject parent = obj.transform.parent.gameObject;
- select its parent gameObject
* - |b| foreach (Transform T in obj.transform) { }
- parse its child gameObject
* - |b| newobj.transform.SetParent(parentTransform)
- set parent of a new object
Component
---------
.. list-table::
:header-rows: 0
:widths: 40 60
* - |b| g.GetComponent()
- Find a specific component of a GameObject
Misc
====
Raycasting
----------
.. code-block::
RaycastHit hit;
if (Physics.Raycast(position, vecDir, out hit, maxDist)) // throw a ray
{
GameObject touchedObject = hit.collider.gameObject;
Debug.Log("Hit: " + touchedObject.name);
}
Add a function in the Editor
----------------------------
.. code-block::
using UnityEngine;
using UnityEditor;
public class NameOfMyClass
{
[MenuItem("Tools/Generate 32 Materials")] // new entry in the Tools menu
public static void Go() {...}
}
Coroutine
---------
A coroutine if a function running asynchronously - use only for small process.
.. code-block::
public class test : MonoBehaviour
{
void Start()
{
StartCoroutine(MyCoroutine()); // Start the coroutine when the scene starts
}
IEnumerator MyCoroutine()
{
Debug.Log("Start");
yield return new WaitForSeconds(3f); // Wait for 3 seconds
Debug.Log("3 seconds later...");
}
Lerp
----
Lerp stands for: Linear interpolation - Useful for animation:
.. code-block::
// rotate smoothly
Quaternion targetRotation = Quaternion.Euler(0f, 180f, 0f);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime);