Unity

수업 내용 복습 5

psb08 2025. 3. 18. 08:41
728x90

MethodInfoClass.cs

using System;
using System.Reflection;
using UnityEngine;

namespace ReflectTest.CreateInstance
{
    class Profile2
    {
        public string Name { get; set; }
        public string Phone { get; set; }

        public void Print()
        {
            Debug.Log($"{Name}, {Phone}");
        }
        
    }

    public class MethodInfoClass : MonoBehaviour
    {
        private void Start()
        {
            DebugPrint();
        }

        [ContextMenu("DebugPrint")]
        private void DebugPrint()
        {
            Type type = typeof(Profile2);
            Profile2 profile2 = (Profile2)Activator.CreateInstance(type);
            profile2.Name = "홍OO";
            profile2.Phone = "010 - 1234 - 0000";
            
            MethodInfo method = type.GetMethod("Print");
            method.Invoke(profile2, null);
        }
        
    }   
}

class Profile2를 생성하고, string 형식으로 Name과 Phone을 프로퍼티로 만들었습니다.

 

그 다음 Print 메서드를 통해 Name과 Phone을 출력하도록 만들었습니다.

 

DebugPrint 메서드에서

Type에 Profile2로 받고, CreateInstance로 생성해줍니다.

이름을 "홍OO"으로 바꾸고, Phone을 010 - 1234 - 0000으로 동적 할당 해줍니다.

 

MethodInfo를 통해 GetMethod로 아까 만든 Print를 호출할 수 있습니다.

맨 마지막 줄에 method.Invoke로 호출합니다.

 

[ContextMenu]를 통해 메뉴를 생성해서 테스트 할 수 있게 만들었습니다.

이름 그대로 DebugPrint가 생깁니다.

클릭 시 Print 메서드가 잘 호출됩니다.

728x90

'Unity' 카테고리의 다른 글

수업 내용 복습 7  (0) 2025.03.29
수업 내용 복습 6  (0) 2025.03.29
수업 내용 복습 4  (0) 2025.03.17
수업 내용 복습 3  (0) 2025.03.16
수업 내용 복습 2  (0) 2025.03.10