728x90

GetComponent

GetComponent 함수를 사용하여 다른 스크립트 또는 컴포넌트의 프로퍼티를 지정하는 방법을 알아봅니다.

가급적이면 Awake(), Start()에 한번만 호출하는 것이 좋다.

UsingOtherComponents

using UnityEngine;
using System.Collections;

public class UsingOtherComponents : MonoBehaviour
{
    public GameObject otherGameObject;


    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

using UnityEngine;
using System.Collections;

public class AnotherScript : MonoBehaviour
{
    public int playerScore = 9001;
}

YetAnotherScript

using UnityEngine;
using System.Collections;

public class YetAnotherScript : MonoBehaviour
{
    public int numberOfPlayerDeaths = 3;
}

참고 : 유니티 튜토리얼

728x90

'게임엔진 > Unity' 카테고리의 다른 글

Unity - Class  (0) 2024.07.02
Unity - 데이터 유형  (0) 2024.07.02
Unity - OnMouseDown  (0) 2024.07.02
Unity - GetAxis  (0) 2024.07.02
Unity - 선형 보간  (0) 2024.07.02

+ Recent posts