1 - GetComponent
설명
[GetComponent]는 기존에 존재하던 class를 Game Object에 '구성 요소'로써, 참조를 통한 접근이 가능하게 하는 keyword이다.
예시 (Unity3D Tutorial)
링크 = GetComponent - Unity Learn
UsingOtherComponents.cs
// UsingOtherComponents
private AnotherScript anotherScript;
private YetAnotherScript yetAnotherScript;
private BoxCollider boxCol;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}
void Start ()
{
boxCol.size = new Vector3(3,3,3);
Debug.Log("The player's score is " + anotherScript.playerScore);
Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
}
}
AnotherScript.cs
// AnotherScript
using UnityEngine;
using System.Collections;
public class AnotherScript : MonoBehaviour
{
public int playerScore = 9001;
}
YetAnotherScript.cs
// YerAnotherScript.cs
using UnityEngine;
using System.Collections;
public class YetAnotherScript : MonoBehaviour
{
public int numberOfPlayerDeaths = 3;
}
"Unity에서 Script는 사용자 지정 컴포넌트(Custom Component)로 간주되며, 동일 Game Object나 심지어 다른 Game Object에 첨부된 Script를 이용해야 하는 경우도 있습니다."
"이 예제에서는 [AnotherScript.cs]와 [YetAnotherScript.cs]는 모두 그 안에 공개 변수가 있습니다."
"우리는 [UsingOtherComponents.cs]에서 이 변수들에 영향을 주려고 합니다."
"[UsingOtherComponents.cs]에는 3개의 변수가 있습니다. 하나는 [otherGameObject]를 저장하고 2개는 다른 Script의 레퍼런스를 저장합니다."
"다른 Script의 Reference는 그 형식이 Script의 이름인 변수에 불과합니다. 실제로 참조하고 있는 것은 Script에 정의된 Class의 Instance이기 때문이죠."
"각진 괄호(<>)는 Type을 매개변수로 받기 위한 용도인데, 예제에서는 형식이 [AnotherScript]입니다. 또한 [GetComponent]를 호출해 [otherGameObject] 등 Reference가 있는 다른 Game Object의 Component를 Address할 수 있습니다."
"[GetComponent]는 호출된 Game Object에 지정된 모든 형식의 컴포넌트 레퍼런스를 반환합니다."
예제에서는 Sphere라는 Game Object에 [UsingOtherComponents.cs]와 [AnotherScript.cs]를 추가했고, Cude라는 Game Object에는 [YetAnotherScript.cs]를 추가하였습니다.
따라서 Sphere을 클릭하면 Unity3D Inspector 창에서 [AnotherScript.cs]에 존재하는 변수인, Player Score을 직접 입력, 수정할 수 있습니다.
그러나 [YetAnotherScript.cs]의 변수인 numberOfPlayerDeaths를 입력, 수정하기 위해서는 Cube의 Unity3D Inspector 창으로 가야합니다.