프로그래밍/c#

[RequireComponent]C# 유니티

yonan 2020. 8. 23. 13:07

RequireComponent 속성은 요구되는 의존 컴포넌트를 자동으로 추가해줍니다.

RequireComponent를 사용하는 스크립트를 추가하면, 요구되는 컴포너트가 자동으로 해당 게임오브젝트에 추가됩니다. 설정 오류를 피하는 데 유용합니다. 예를 들어, 리지드 바디가 요구되는 스크립트가, 항상 같은 게임오브젝트에 첨부되는 경우. RequireComponent를 사용하면 이 작업이 자동으로 이루어 지기 때문에, 설정에 대한 실수를 할 염려가 없습니다. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added.

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);
	}
}