[Unity] MonoBehaviour

Yerin·2023년 6월 12일
0

MonoBehaviour를 상속받은 스크립트만이 오브젝트에 첨부될 수 있다.

상속 관계
Object -> Component -> MonoBehaviour

MonoBehaviour 키워드를 사용하여 해당 스크립트를 실행할 경우 아래와 같은 오류가 뜨게된다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Managers : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Managers mg = new Managers();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

=> 일반적인 C# 클래스로 변경.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Managers 
{
    // Start is called before the first frame update
    void Start()
    {
        Managers mg = new Managers();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

❗ Start()와 Update()의 경우 자동으로 호출되는 함수가 아니다.

결국 빈 Object를 만들어 GameManager로 사용한다.
그 결과 MonoBehaviour를 사용할 수 있게 되고 함수 Start()와 Update()가 자동으로 호출된다.

다른 스크립트에서 아래 스크립트로 대체하여 Managers를 호출한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject go = GameObject.Find("@Managers");
        Managers mg = go.GetComponent<Managers>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
profile
재밌는 코딩 공부

0개의 댓글