유니티
유니티에서 monobehaviour를 상속받는 클래스는
게임 오브젝트에 컴포넌트로 부착할 수 있다.
개발 규모가 커질수록 하나의 클래스에서 모든 동작을 구현하기 버겁기 때문에
필연적으로 클래스를 나누게 된다.
부모 클래스가 mono클래스 일 때 상속받는 자식이 start, onenable, awake 등
mono클래스의 이벤트를 사용하는 방법을 알아보자.
using UnityEngine;
public class Parent : MonoBehaviour
{
protected virtual void Start()
{
this.transform.position = Vector3.zero;
Debug.Log(this.transform.position);
// 시작할 때 위치를 초기화 한다.
}
}
클래스 Parent 모습
Start 함수에서 본인의 위치를 초기화시킨다.
virtual 키워드를 붙이면 자식이 override 해서 사용할 수 있다.
using UnityEngine;
public class Child : Parent
{
protected override void Start()
{
base.Start();
this.transform.position = Vector3.forward;
Debug.Log(this.transform.position);
// Z축으로 1만큼 이동한다.
}
}
Parent 클래스를 상속받은 Child 클래스
base 키워드는 상속시킨 직계부모를 뜻한다.
부모의 Start 이벤트를 먼저 실행시킨 후
본인의 위치를 Z 축으로 1만큼 이동한다.
Child 클래스는 Mono를 상속한 Parent를 상속했으므로
게임 오브젝트에 컴포넌트로 부착이 가능하다.
이대로 실행하면 부모의 Start부터 실행되어 위치를 초기화 한 뒤,
Z 축으로 1만큼 이동한 것을 확인할 수 있다.
using UnityEngine;
public class SecondChild : Child
{
protected override void Start()
{
base.Start();
this.transform.position = Vector3.left;
Debug.Log(this.transform.position);
}
}
Child를 다시 한번 상속해도 Start 이벤트를 override 할 수 있다.
큐브에 Child 클래스가 아닌, SecondChild 클래스를 컴포넌트로 추가하고 실행하면
Parent, Child, SecondChild 순서대로 Start 함수가 실행된다.
using UnityEngine;
public class Child : Parent
{
protected override void Start()
{
// base.Start();
this.transform.position = Vector3.forward;
Debug.Log(this.transform.position);
// Z축으로 1만큼 이동한다.
}
}
SecondChild 클래스를 큐브에 컴포넌트로 부착한 채로
Child클래스의 base.Start()를 주석처리하면
실행 순서는 Child, SecondChild가 된다.
SecondChild의 base는 Child
Child의 base는 Parent이기에
Parent의 Start 이벤트는 실행되지 않는다.
서로 다른 게임 오브젝트이지만
생성할 때 공통적으로 해야 하는 것이 있을 때 사용하면 좋다.
'개발 공식 > Unity' 카테고리의 다른 글
Unity URP Overlay Camera 한 화면에 두 개의 카메라 (1) | 2022.11.29 |
---|---|
unity transform rotation Rotate RotateAround (0) | 2022.11.22 |
[Unity/UI] 텍스트 배경크기조절하는법("Parent has a type of layout group" error) (0) | 2022.01.27 |
댓글