GameObjects, Components, and the MonoBehaviour Lifecycle
In Unity, everything in a scene is a GameObject, an empty container that gets its behavior from attached Components. A MonoBehaviour script is a component that hooks into Unity's lifecycle.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
void Start()
{
Debug.Log($"{gameObject.name} spawned");
}
void Update()
{
float move = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(move, 0, 0);
}
}
The lifecycle
Awake()runs once, beforeStart(), even on a disabled component, use it to cache references.Start()runs once, after everyAwake()has run, right before the first frame.Update()runs every frame, useTime.deltaTimeso movement stays framerate-independent.FixedUpdate()runs on a fixed timestep, use it for physics (Rigidbodyforces).
Getting components
GetComponent<T>() looks up another component attached to the same GameObject:
Rigidbody rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * 10f);