Menu
CoddyTech

Awake and Start

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 70 of 85.

Unity calls Awake() as soon as an object is loaded, before its Start(). What makes it useful is the rule across objects: when a scene starts, every object's Awake() runs before any object's Start(). Which object goes first within each round is up to Unity, and you cannot count on it.

This Player script is on two players, P1 (startLives 3) and P2 (startLives 5), and each has the other as its rival:

public int startLives = 3;
public GameObject rival;
int lives;

void Awake()
{
    lives = startLives;   // set up this object
}

void Start()
{
    int theirs = rival.GetComponent<Player>().Lives();   // ask the other one
    Debug.Log(name + " sees a rival with " + theirs + " lives");
}

public int Lives()
{
    return lives;
}

The first version set lives in Start(). Whichever player started first then asked its rival before the rival had set its lives, and logged 0. With the setup in Awake(), both players have their lives before either Start() asks, so P1 logs 5 and P2 logs 3. The habit that follows: set up an object's own fields in Awake(), and talk to other objects in Start().

challenge icon

Challenge

Medium

Fix the hives so neither counts a list that is not made yet.

  1. Add void Awake() to Hive.
  2. Move the bees = new List<GameObject>(); line and the for loop from Start() into Awake().
  3. Leave the two counting lines in Start(): every Awake() runs before any Start().

Press Play: each hive logs its rival's bees, HiveA counts 5 rival bees, with no error. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

public class Hive : MonoBehaviour
{
    public GameObject beePrefab;
    public GameObject rival;
    public int beeCount = 3;
    List<GameObject> bees;

    void Start()
    {
        bees = new List<GameObject>();
        for (int i = 0; i < beeCount; i++)
        {
            Vector3 spot = transform.position + new Vector3(i * 0.6f - 1.2f, 1.5f, 0);
            bees.Add(Instantiate(beePrefab, spot, Quaternion.identity));
        }

        int theirs = rival.GetComponent<Hive>().BeeCount();
        Debug.Log(name + " counts " + theirs + " rival bees");
    }

    public int BeeCount()
    {
        return bees.Count;
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground