728x90
CreateInstanceTest.cs
using System;
using System.Reflection;
using UnityEngine;
namespace ReflectTest.CreateInstance
{
class Profile
{
public string Name { get; set; }
public string PhoneNum { get; set; }
}
public class CreateInstanceTest : MonoBehaviour
{
private void Start()
{
Type type = typeof(Profile);
object profile = Activator.CreateInstance(type);
PropertyInfo name = type.GetProperty("Name");
PropertyInfo phoneNum = type.GetProperty("PhoneNum");
name.SetValue(profile, "홍길동", null);
phoneNum.SetValue(profile, "010-1234-1234", null);
Debug.Log($"{name.GetValue(profile, null)}, {phoneNum.GetValue(profile, null)}");
}
}
}
리플렉션을 이용해서 동적으로 인스턴스를 만들기 위해 System.Activator 클래스의 도움이 필요합니다.
인스턴스를 만들려는 형식의 Type 객체를 매개변수에 넘기면, CreateInstance 메서드는 입력 받은 형식의 인스턴스를 생성하여 반환합니다.
이 예제 코드에서 SetValue() 메서드와 GetValue() 메서드의 가장 마지막 인수는 인덱서의 인덱스를 위해 사용된다고 합니다. 프로퍼티에서는 인덱서가 필요 없으니 null로 할당한 것입니다.
728x90
'Unity' 카테고리의 다른 글
수업 내용 복습 6 (0) | 2025.03.29 |
---|---|
수업 내용 복습 5 (0) | 2025.03.18 |
수업 내용 복습 3 (0) | 2025.03.16 |
수업 내용 복습 2 (0) | 2025.03.10 |
수업 내용 복습 1 (0) | 2025.03.09 |