GetComponents
Coddy Unity 여정의 Unity 게임 아키텍처 섹션에 포함된 레슨. 64개 중 9번째.
GetComponent<T>()는 첫 번째 일치 항목을 반환합니다. GetComponents<T>()는 해당 객체의 모든 일치 항목을 배열로 반환하고, GetComponentsInChildren<T>()는 해당 객체와 그 아래에 있는 모든 항목 중 일치하는 항목을 반환합니다. T로 인터페이스를 지정하면, 한 번의 호출로 클래스와 관계없이 특정 기능을 수행할 수 있는 모든 부분을 가져옵니다. 여기서 공장 기계들은 Factory 객체의 자식이며, 전원으로 작동하는 각 부분은 IPowered를 구현합니다:
public interface IPowered
{
void SetPower(bool on);
}public class Generator : MonoBehaviour
{
public GameObject factory;
public void Switch(bool on)
{
IPowered[] parts = factory.GetComponentsInChildren<IPowered>();
foreach (IPowered part in parts)
{
part.SetPower(on);
}
Debug.Log(parts.Length + " parts powered");
}
}Lamp는 Light를 켜고, Fan은 회전을 시작하고, Conveyor는 움직이기 시작하며, 각각 자체 SetPower에서 이를 처리합니다. 한 객체에 Lamp와 Fan이 있는 기계는 두 번 집계됩니다. 각 구성 요소가 별도의 일치 항목이기 때문입니다. Generator는 이들의 이름을 전혀 지정하지 않으므로, 나중에 Factory 아래에 추가된 IPowered를 구현하는 Siren도 다음 Switch 호출에서 켜집니다.
GetComponentsInChildren은 메서드를 호출한 객체도 포함하며, true를 전달하지 않으면 비활성화된 자식은 건너뜁니다: GetComponentsInChildren<IPowered>(true). GetComponents는 해당 객체 하나만 살펴보므로, 하나의 문에 나란히 있는 조명과 부저 같은 부분에 적합합니다.
챌린지
쉬움로봇의 모든 부분이 피격에 반응하게 하세요.
IHitReaction.cs에서public interface IHitReaction을 선언하고void React(int damage);를 작성하세요.Flash,Recoil,Sparks가 이를 구현하도록 하세요. 각 메서드의 이름을public void React(int damage)로 바꾸세요.- Recoil은
0.5f * damage만큼 뒤로 이동하고, Sparks는damage개만큼 불꽃을 던집니다. TakeDamage에서 모든GetComponentsInChildren<IHitReaction>()에React(amount)를 호출한 다음,Reactions: 3(반응의 개수)를 기록하세요.
‘플레이’를 누르고 Space를 누른 다음 클릭하세요. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
public class Health : MonoBehaviour
{
public int hp = 10;
public void TakeDamage(int amount)
{
hp -= amount;
GetComponentInChildren<Flash>().Show();
}
}
Unity 게임 아키텍처의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드