- 같은 클래스의 매서드는 Awake / Start / Update 에 넣어 실행할 수 있다.

매서드 Start에 넣어서 호출하기

 

App에 필드 변수로 public Controler controler; 를 선언해 GameObject인 Controler를 필드에 넣는다. 안넣으면 NullRefer.. 오류남

 

콘솔창에 출력된 컨트롤러 위치:와 같음 확인 / 변수의 접근 한정자를 private로 설정하면 protection level 오류 난다.

 

 

  • App
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class App : MonoBehaviour
{
   public Controler controler;

    void Start()
    {
       // controler = controler.GetComponent<Controler>();
        Vector2 vector2 = controler.transform.position;
        int b = controler.a;

        Debug.Log($"컨트롤러 위치: {vector2}");
        Debug.Log($"컨트롤러 a: {b}");
    }
}

 

  • Controler
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controler : MonoBehaviour
{
    public int a;

    private void Start()
    {
        Control(); // 아래 있는 매서드
    }

    void Control() // 접근_한정자를 지정하지 않으면 private 라 같은 클래스 안에서만 사용 가능
    {
        Debug.Log($"<color=yellow>게임 오브젝트 Controler의</color>\n
        <color=skyblue>컴포넌트 Controler 클래스의</color>\n
        <color=red>매서드 Control을</color>\n 
        Controler Start 매서드에 넣어 호출됨");
    }
}

 

 

- 다른 클래스의 컴포넌트는 필드 변수로 등록 > 컴포넌트 호출

 

  • APP
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.VisualScripting;
using UnityEngine;

public class App : MonoBehaviour
{
   public Controler controler; // 컴포넌트로 삽입한 게임 오브젝트인 스크립트 클래스 호출

    void Start()
    {
        controler.Control(); // 스크립트 클래스가 갖고 있는 매서드 호출
    }
}

 

  • Controler
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controler : MonoBehaviour
{
    public int a;

   public void Control()
    {
        Debug.Log($"<color=yellow>게임 오브젝트 Controler의</color>\n" +
            $"<color=skyblue>컴포넌트 Controler 클래스의</color>\n" +
            $"매서드 Control을\n<color=red>App에서 controler.Control();로 호출함</color>");
    }
}

 

+ Recent posts