리플렉션은 런타임 단계에서 클래스 내부 구조를 메타데이터들을 가져와 사용할 수 있는 라이브러리를 말한다. 리플렉션을 통해, 값을 넣거나, 함수를 실행시키거나, 어떤 타입인지 보호 수준은 어느정도인지를 알아낸다.
단점은 연산량이 많아 성능적으로 불리하며 필요한 부분에서 작게 사용하는 부분은 크게 문제되지 않고 현업에서도 자주 쓰일 수 있다고 하니 알아두는게 좋겠다.
using UnityEngine;
using System;
public class ReflectionExample : MonoBehaviour
{
void Start()
{
GameObject go = new GameObject("MyObject");
Type type = go.GetType();
Debug.Log("Type: " + type.Name); // 출력: Type: GameObject
}
}
using UnityEngine;
using System;
using System.Reflection;
public class ReflectionExample : MonoBehaviour
{
void Start()
{
Type type = typeof(Debug);
MethodInfo method = type.GetMethod("Log", new Type[] { typeof(object) });
if (method != null)
{
method.Invoke(null, new object[] { "Hello, Reflection!" });
}
}
}
using UnityEngine;
using System;
public class ReflectionExample : MonoBehaviour
{
void Start()
{
Type type = typeof(GameObject);
GameObject go = (GameObject)Activator.CreateInstance(type);
go.name = "CreatedWithReflection";
Debug.Log(go.name); // 출력: CreatedWithReflection
}
}