Unity
[Unity] RequireComponent
bugwasd
2022. 11. 18. 17:40
RequireComponent는 게임 오브젝트에 꼭 필요한 컴포넌트를 스크립트로 작성하여 추가하는 것 입니다
[RequireComponent (typeof (Rigidbody))]
이렇게 작성을 하면 Rigidbody 컴포넌트가 해당 스크립트를 가진 게임 오브젝트에 자동으로 추가됩니다
다음은 예제 코드입니다
using UnityEngine;
// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate() {
rb.AddForce(Vector3.up);
}
}
이제 게임 오브젝트에 위 스크립트를 추가하면, Rigidbody 컴포넌트가 자동으로 추가되는 것을 볼 수 있습니다
이 게임 오브젝트의 Rigidbody 컴포넌트를 Remove Component 하려고 하면 다음과 같이 경고창이 나오는 것을 볼 수 있습니다