안녕하세요

프로그램 과정에서 막혔던 문제들에 대한 해결책 정리


페이지 목록

2025년 11월 28일 금요일

[유니티][Unity] Instantiate(uiPrefab) 이 화면에 안 나오는 이유

 uiPrefab을 연결 시켜주고 Instantiate(uiPrefab)을 해도 UI가 보이지 않았다.

 이유는 연결하려는 부모 캔버스를 연결해줘야 되기 때문이다.

using UnityEngine;
using UnityEngine.UI; // UI 관련 기능을 사용하려면 이 네임스페이스가 필요합니다.

public class UIManager : MonoBehaviour
{
    // 유니티 인스펙터에서 캔버스 오브젝트를 드래그하여 할당해주세요.
    [SerializeField] private Transform parentCanvasTransform;

    // 인스턴스화할 UI 프리팹 (예: 버튼, 패널 등)
    [SerializeField] private GameObject uiPrefab;

    void Start()
    {
        // Start 시점에 UI 생성 함수 호출 예시
        SpawnUIElement();
    }

    public void SpawnUIElement()
    {
        if (parentCanvasTransform != null && uiPrefab != null)
        {
            // 1. Instantiate() 메서드를 사용하여 프리팹 생성과 동시에 캔버스의 자식으로 설정합니다.
            // 두 번째 매개변수로 부모 Transform을 전달합니다.
            GameObject newUIElement = Instantiate(uiPrefab, parentCanvasTransform);

            // 추가적으로 생성된 UI 요소의 이름이나 위치를 조정할 수 있습니다.
            newUIElement.name = "DynamicUI_Instance";
            // newUIElement.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
        }
        else
        {
            Debug.LogError("Canvas Transform 또는 UI Prefab이 할당되지 않았습니다. 인스펙터를 확인해주세요.");
        }
    }
}

이렇게 parentCanvasTransform을 할당해줘야 한다.

그래서 GameObject newUIElement = Instantiate(uiPrefab, parentCanvvasTransform);

으로 부모 Transform을 전달해주면 화면에 나타나게 된다.


 구글 AI의 도움을 받아 작성하였습니다.

댓글 없음:

댓글 쓰기