GameObject and Lifecycle - Cheat Sheet

GameObject Basics
NameDescriptionCode Example
CreateCreates a new GameObject. You can create an empty GameObject or use primitives like cubes, spheres, etc. This is useful for adding new elements to your scene programmatically.
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(0, 0, 0);
cube.name = "MyCube";
FindSearches for a GameObject by name or tag. Use sparingly as it can be slow in large scenes. Prefer assigning references in the Inspector when possible.
GameObject player = GameObject.FindWithTag("Player");
if (player != null)
{
    Debug.Log("Found player at: " + player.transform.position);
}
DestroyRemoves a GameObject from the scene. You can specify a delay for the destruction. This is useful for creating effects like explosions that linger before disappearing.
public GameObject explosionEffect;

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Enemy"))
    {
        GameObject effect = Instantiate(explosionEffect, transform.position, Quaternion.identity);
        Destroy(effect, 2f); // Destroy after 2 seconds
        Destroy(gameObject); // Destroy this object immediately
    }
}
InstantiateCreates a copy of a prefab or existing GameObject. This is commonly used for spawning entities like enemies, projectiles, or collectibles during gameplay.
public GameObject enemyPrefab;
public int numberOfEnemies = 5;

void SpawnEnemies()
{
    for (int i = 0; i < numberOfEnemies; i++)
    {
        Vector3 randomPosition = new Vector3(Random.Range(-10f, 10f), 0, Random.Range(-10f, 10f));
        Instantiate(enemyPrefab, randomPosition, Quaternion.identity);
    }
}
SetActiveActivates or deactivates a GameObject. This is useful for implementing object pooling, toggling UI elements, or temporarily disabling game elements without destroying them.
public GameObject pauseMenu;

void TogglePauseMenu()
{
    bool isActive = pauseMenu.activeSelf;
    pauseMenu.SetActive(!isActive);
    Time.timeScale = isActive ? 1f : 0f; // Pause/unpause the game
}
Components
NameDescriptionCode Example
AddAdds a new component to a GameObject. This allows you to extend the functionality of GameObjects dynamically during runtime.
void AddPhysicsToPlayer()
{
    Rigidbody rb = gameObject.AddComponent<Rigidbody>();
    rb.mass = 1.5f;
    rb.drag = 0.5f;
    Debug.Log("Added Rigidbody to player");
}
GetRetrieves a component attached to the GameObject. This is a fundamental operation for interacting with different aspects of a GameObject.
void AdjustCollider()
{
    Collider col = gameObject.GetComponent<Collider>();
    if (col != null && col is BoxCollider boxCollider)
    {
        boxCollider.size = new Vector3(2f, 1f, 2f);
        boxCollider.center = Vector3.up * 0.5f;
    }
}
RemoveRemoves a component from a GameObject. This can be useful for changing the behavior of objects during gameplay or for cleanup purposes.
void DisableAudio()
{
    AudioSource audioSource = gameObject.GetComponent<AudioSource>();
    if (audioSource != null)
    {
        audioSource.Stop();
        Destroy(audioSource);
        Debug.Log("Removed AudioSource component");
    }
}
CheckChecks if a GameObject has a specific component. This method is more efficient than GetComponent when you only need to check for the presence of a component.
void CheckAndEnableLighting()
{
    if (gameObject.TryGetComponent<Light>(out Light light))
    {
        light.enabled = true;
        light.intensity = 1.5f;
        Debug.Log("Enabled and adjusted Light component");
    }
    else
    {
        Debug.Log("No Light component found");
    }
}
Get ChildrenRetrieves components from all child GameObjects. This is useful for operations that need to affect all children of an object, like changing materials or adjusting renderers.
void SetChildrenMaterial(Material newMaterial)
{
    Renderer[] childRenderers = gameObject.GetComponentsInChildren<Renderer>();
    foreach (Renderer renderer in childRenderers)
    {
        renderer.material = newMaterial;
    }
    Debug.Log($"Updated material for {childRenderers.Length} child renderers");
}
Transform
NameDescriptionCode Example
PositionManipulates the position of a GameObject in world space (transform.position) or local space (transform.localPosition). Essential for moving objects in your game.
void MoveObject()
{
    // Move in world space
    transform.position += Vector3.forward * Time.deltaTime;

    // Set local position relative to parent
    transform.localPosition = new Vector3(2f, 0f, 0f);
}
RotationControls the rotation of a GameObject in world space (transform.rotation) or local space (transform.localRotation). Used for orienting objects in your scene.
void RotateObject()
{
    // Rotate around the y-axis in world space
    transform.rotation *= Quaternion.Euler(0f, 30f * Time.deltaTime, 0f);

    // Set local rotation relative to parent
    transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
}
ScaleAdjusts the scale of a GameObject. This affects the size of the object and its children. Useful for visual effects or dynamic resizing of objects.
void ScaleObject()
{
    // Double the size of the object
    transform.localScale = Vector3.one * 2f;

    // Scale non-uniformly
    transform.localScale = new Vector3(1f, 2f, 1f);
}
ParentSets or changes the parent of a GameObject. This is crucial for organizing your scene hierarchy and creating complex object relationships.
public Transform newParent;

void ChangeParent()
{
    // Set a new parent
    transform.SetParent(newParent);

    // Remove parent (set to root)
    transform.SetParent(null);

    // Set parent and keep world position
    transform.SetParent(newParent, worldPositionStays: true);
}
ChildrenAccesses or manipulates child objects of a GameObject. Useful for traversing hierarchies or performing operations on groups of related objects.
void ManageChildren()
{
    // Get the number of children
    int childCount = transform.childCount;

    // Access a specific child
    Transform firstChild = transform.GetChild(0);

    // Iterate through all children
    for (int i = 0; i < transform.childCount; i++)
    {
        Transform child = transform.GetChild(i);
        Debug.Log($"Child {i}: {child.name}");
    }
}
Lifecycle Methods
NameDescriptionCode Example
AwakeCalled when the script instance is being loaded. Use this for initialization steps that need to happen before Start and don't depend on other objects.
private int initialHealth;

void Awake()
{
    initialHealth = 100;
    Debug.Log($"Awake: Set initial health to {initialHealth}");
}
OnEnableCalled when the object becomes enabled and active. Useful for setting up event subscriptions or reactivating behaviors when an object is re-enabled.
void OnEnable()
{
    GameEvents.onGameStart += HandleGameStart;
    Debug.Log("OnEnable: Subscribed to game start event");
}

void OnDisable()
{
    GameEvents.onGameStart -= HandleGameStart;
}
StartCalled before the first frame update, after Awake. Use this for initialization that requires other objects to be set up first.
private Player player;

void Start()
{
    player = GameObject.FindWithTag("Player").GetComponent<Player>();
    transform.position = player.transform.position + Vector3.up * 2f;
    Debug.Log("Start: Positioned object above player");
}
UpdateCalled once per frame. Use this for frame-based game logic, input handling, and smooth movements.
void Update()
{
    // Rotate the object continuously
    transform.Rotate(Vector3.up, 30f * Time.deltaTime);

    // Check for input
    if (Input.GetButtonDown("Fire1"))
    {
        FireWeapon();
    }
}
FixedUpdateCalled at fixed time intervals, ideal for physics calculations as it's independent of frame rate.
public float moveSpeed = 5f;
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
    rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
LateUpdateCalled after all Update functions have been called. Useful for camera follow scripts or final position adjustments.
public Transform target;
public Vector3 offset;

void LateUpdate()
{
    if (target != null)
    {
        transform.position = target.position + offset;
        transform.LookAt(target);
    }
}
OnDisableCalled when the behaviour becomes disabled or inactive. Use this for cleanup, like unsubscribing from events.
void OnDisable()
{
    GameEvents.onGameOver -= HandleGameOver;
    Debug.Log("OnDisable: Unsubscribed from game over event");
}
OnDestroyCalled when the MonoBehaviour will be destroyed. Use this for final cleanup operations.
void OnDestroy()
{
    // Save player data
    PlayerPrefs.SetInt("PlayerScore", currentScore);
    PlayerPrefs.Save();
    Debug.Log("OnDestroy: Saved player score");
}
Physics Callbacks
NameDescriptionCode Example
OnCollisionEnterCalled when this collider/rigidbody begins touching another. Use this to detect impacts and trigger appropriate responses.
void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Enemy"))
    {
        TakeDamage(10);
        Debug.Log($"Collided with enemy: {collision.gameObject.name}");
    }
}
OnCollisionStayCalled once per frame for every collider/rigidbody in contact. Useful for continuous effects while objects are touching.
void OnCollisionStay(Collision collision)
{
    if (collision.gameObject.CompareTag("FireZone"))
    {
        TakeDamageOverTime(1);
        Debug.Log("Taking continuous damage in fire zone");
    }
}
OnCollisionExitCalled when this collider/rigidbody stops touching another. Use this to end effects that were active during contact.
void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.CompareTag("SpeedBoost"))
    {
        EndSpeedBoost();
        Debug.Log("Exited speed boost zone");
    }
}
OnTriggerEnterCalled when the Collider enters a trigger. Ideal for detecting when objects enter specific areas without physical collision.
void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Pickup"))
    {
        CollectItem(other.gameObject);
        Debug.Log($"Collected item: {other.gameObject.name}");
    }
}
OnTriggerStayCalled every frame for all triggers that are in contact. Use this for continuous effects in trigger zones.
void OnTriggerStay(Collider other)
{
    if (other.CompareTag("HealingZone"))
    {
        Heal(1);
        Debug.Log("Healing while in healing zone");
    }
}
OnTriggerExitCalled when the Collider has stopped touching the trigger. Use this to end effects that were active in the trigger zone.
void OnTriggerExit(Collider other)
{
    if (other.CompareTag("SafeZone"))
    {
        EnableVulnerability();
        Debug.Log("Left safe zone, now vulnerable");
    }
}
Coroutines
NameDescriptionCode Example
StartBegins a coroutine. Coroutines are useful for spreading tasks across several frames or introducing time-based logic.
private IEnumerator FadeOutCoroutine;

void StartFade()
{
    if (FadeOutCoroutine != null)
    {
        StopCoroutine(FadeOutCoroutine);
    }
    FadeOutCoroutine = FadeOut(1f);
    StartCoroutine(FadeOutCoroutine);
}

IEnumerator FadeOut(float duration)
{
    float elapsedTime = 0f;
    while (elapsedTime < duration)
    {
        float alpha = Mathf.Lerp(1f, 0f, elapsedTime / duration);
        SetAlpha(alpha);
        elapsedTime += Time.deltaTime;
        yield return null;
    }
    SetAlpha(0f);
}
StopStops a running coroutine. This is useful for cancelling ongoing effects or animations.
private Coroutine healOverTimeCoroutine;

void StartHealing()
{
    if (healOverTimeCoroutine != null)
    {
        StopCoroutine(healOverTimeCoroutine);
    }
    healOverTimeCoroutine = StartCoroutine(HealOverTime());
}

void StopHealing()
{
    if (healOverTimeCoroutine != null)
    {
        StopCoroutine(healOverTimeCoroutine);
        healOverTimeCoroutine = null;
        Debug.Log("Stopped healing coroutine");
    }
}

IEnumerator HealOverTime()
{
    while (true)
    {
        yield return new WaitForSeconds(1f);
        Heal(5);
    }
}
YieldPauses the coroutine execution. You can yield for a specific time, until the next frame, or until a condition is met.
IEnumerator PerformSequence()
{
    Debug.Log("Starting sequence");
    yield return new WaitForSeconds(2f);
    Debug.Log("2 seconds have passed");
    
    yield return null; // Wait for the next frame
    Debug.Log("Next frame");
    
    yield return new WaitForEndOfFrame();
    Debug.Log("End of frame");
}
WaitUntilSuspends the coroutine execution until a condition is met. This is useful for creating state-based behaviors.
private bool isPlayerReady = false;

IEnumerator StartGameWhenReady()
{
    Debug.Log("Waiting for player to be ready");
    yield return new WaitUntil(() => isPlayerReady);
    Debug.Log("Player is ready, starting game");
    StartGame();
}

void OnPlayerReady()
{
    isPlayerReady = true;
}
WaitWhileSuspends the coroutine execution while a condition is true. This can be used to create loops or delay actions until a state changes.
private bool isLoading = true;

IEnumerator LoadGameData()
{
    StartLoading();
    yield return new WaitWhile(() => isLoading);
    Debug.Log("Loading complete, initializing game");
    InitializeGame();
}

void OnDataLoaded()
{
    isLoading = false;
}