Awake와 Start
Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 85개 중 70번째.
Unity는 객체가 로드되는 즉시, 해당 객체의 Start()보다 먼저 Awake()를 호출합니다. 이 메서드가 유용한 이유는 객체 간에 적용되는 규칙 때문입니다. 씬이 시작되면 모든 객체의 Awake()가 어떤 객체의 Start()보다도 먼저 실행됩니다. 각 단계에서 어떤 객체가 먼저 실행될지는 Unity가 정하며, 이를 확신할 수는 없습니다.
이 Player 스크립트는 두 플레이어 P1(startLives 3)과 P2(startLives 5)에 적용되어 있으며, 각 플레이어의 rival은 다른 플레이어입니다:
public int startLives = 3;
public GameObject rival;
int lives;
void Awake()
{
lives = startLives; // 이 객체를 초기화한다
}
void Start()
{
int theirs = rival.GetComponent<Player>().Lives(); // 다른 객체에 물어본다
Debug.Log(name + " sees a rival with " + theirs + " lives");
}
public int Lives()
{
return lives;
}첫 번째 버전에서는 lives를 Start()에서 설정했습니다. 먼저 시작한 플레이어는 라이벌이 생명 수를 설정하기도 전에 라이벌에게 물어보았고, 0을 출력했습니다. Awake()에서 설정하면 어느 한쪽이 Start()에서 물어보기 전에 두 플레이어 모두 생명 수를 설정하므로 P1은 5를, P2는 3을 출력합니다. 여기서 익힐 습관은 객체 자신의 필드는 Awake()에서 설정하고, 다른 객체와는 Start()에서 상호작용하는 것입니다.
챌린지
중급아직 만들어지지 않은 목록을 어느 쪽도 세지 않도록 벌집을 수정하세요.
Hive에void Awake()를 추가하세요.bees = new List<GameObject>();줄과for루프를Start()에서Awake()로 옮기세요.Start()에는 개수를 세는 두 줄을 그대로 두세요. 모든Awake()가Start()보다 먼저 실행됩니다.
‘플레이’를 누르세요. 각 벌집이 상대 벌집의 벌 수를 로그에 기록하고, 오류 없이 HiveA가 상대 벌 5마리를 셉니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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;
}
}
Unity 스크립팅 기초의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드