Awake and Start
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 55 of 67.
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
MediumTwo beehives, HiveA and HiveB, run the same Hive script. Each hive spawns its bees (3 and 5, from beeCount) into a list, then logs how many bees its rival has: HiveA counts 5 rival bees and HiveB counts 3 rival bees.
Press Play: one hive stops with a NullReferenceException, because it asks for its rival's list before the rival has made it. Fix the script so that every hive has its list and its bees before any hive counts its rival's. Keep the counting where it is. 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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star10The Script Lifecycle
Awake and StartUpdate and LateUpdateOnEnable and OnDisableThe Lifecycle OrderRecap: Lifecycle Logger5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon