Reflection 을 이용한 유니티에서 실행 시 버튼 동적 생성
.NET Reflection
.NET 객체의 클래스, 메소드, 프로퍼티등의 정보를 런타임중에 알아내는 기능을 제공
해당 기능 중 Type.GetMethods 메서드를 이용하여 유니티에서 동적으로 버튼을 생성해 보겠다.
static class
편의를 위해 util class 를 static 으로 선언
using System.Reflection;
public static class Utils
{
// 반환형은 MethodInfo[] 여러 class 를 사용하기 위해 제네릭으로 구현
public static MethodInfo[] GetFunctions<T>()
{
return typeof(T).GetMethods();
}
}
TestModules class
테스트를 위해 임의로 클래스 생성
using UnityEngine;
using UnityEngine.UI;
// 테스트용 클래스
public class TestModules : MonoBehaviour
{
// 부모가 될 canvas
[SerializeField]
private Transform TestCanvas;
// 복사용 prefab 버튼
[SerializeField]
private Button TestButton;
private void Awake()
{
// 버튼의 간격을 띄워주기 위한 변수
int yAcc = 0;
// 방금 작성한 Utils class 에서 GetFunctions 메소드를 호출
var GetFunctions = Utils.GetFunctions<ProductionEffect>();
// GetFunctions 을 순환
foreach (var function in GetFunctions)
{
// return 값이 void 형 이면
if(function.ReturnParameter.ToString() == "Void")
{
// 부모 캔버스 밑에 버튼 생성
var button = Instantiate(TestButton, TestCanvas.transform);
// 버튼의 이름을 메소드의 이름으로 지정
button.transform.GetChild(0).GetComponent<Text>().text = function.Name;
// 포지션 지정
Vector3 postion = button.transform.GetComponent<RectTransform>().localPosition;
button.transform.GetComponent<RectTransform>().localPosition = new Vector3(postion.x, postion.y + button.transform.GetComponent<RectTransform>().sizeDelta.y * yAcc, postion.z);
// 생성한 버튼에 불러온 method 를 이벤트로 지정
button.onClick.AddListener(() =>
{
function.Invoke(null, null);
});
}
yAcc++;
}
}
}
ProductionEffect class
단순한 UI 효과를 모아둔 class 이다. 이 부분은 자유롭게 작성하면 될 듯
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class ProductionEffect
{
public static void FadeIn()
{
DataManager.Instance.Screen.GetComponent<RawImage>().DOFade(0, 1);
}
public static void FadeOut()
{
DataManager.Instance.Screen.GetComponent<RawImage>().DOFade(1, 1);
}
public static void Slide()
{
var screen = DataManager.Instance.Screen.GetComponent<RectTransform>();
float leftValue = 2560;
screen.SetLeft(leftValue);
DOTween.To(
() => leftValue,
(left) =>
{
screen.SetLeft(left);
}
, 0, 3
);
}
public static void Hide()
{
var screen = DataManager.Instance.Screen;
screen.gameObject.SetActive(false);
}
public static void Show()
{
var screen = DataManager.Instance.Screen;
screen.gameObject.SetActive(true);
}
}
결과
실행 전
실행 전 이라 버튼이 생성이 안 되어있다.
실행 후
실행을 하면 우측 하단에 버튼이 동적으로 생성된 것을 볼 수 있다!
지적, 피드백은 언제나 환영입니다.
Author And Source
이 문제에 관하여(Reflection 을 이용한 유니티에서 실행 시 버튼 동적 생성), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kimchan7415/Reflection-을-이용한-유니티에서-실행-시-버튼-동적-생성저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)