Game Engine/Unity

[Unity] 런타임에 Resources 폴더에서 바로 리소스 로드하기

양양줘 2025. 4. 8. 10:46

Unity에서 실행시간에 게임 오브젝트를 만들고 싶을 때

보통 컴포넌트에 미리 GameObject를 할당해두고

스크립트 내에서 해당 오브젝트를 Instantiate한다.

 

하지만 이럴 경우

프리팹을 외부에서 지정하지 않으면 동작하지 않기 때문에

할당 누락으로 인한 오류 발생 가능성이 높고

코드의 재사용성이 낮다.

 

유니티에서 기본적으로 제공되는 지정 폴더(Asset, Package 등) 인

Resources에 사용할 리소스를 넣어두면

따로 프리팹을 할당하지 않아도

런타임에 바로 리소스를 로드하는게 가능하다.

 

로드는 무조건 Resources폴더에 있는 데이터만 가능하기 때문에

Resources폴더에 넣어두어야 한다.

 

Resources.Load<GameObject>("리소스명")

Resources.Load<GameObject>("경로/리소스명")

 

 

📌 사용 가능한 대표적인 데이타 타입

데이터 타입 설명
GameObject 프리팹, 씬 오브젝트
Texture2D 2D 텍스처 이미지
Sprite 2D 스프라이트
AudioClip 오디오 파일
Material 머티리얼
TextAsset 텍스트 파일 (JSON, XML, TXT 등)
Shader 셰이더
AnimationClip 애니메이션 클립
RuntimeAnimatorController 애니메이터 컨트롤러
Font 폰트
VideoClip 비디오 클립
ScriptableObject 커스텀 데이터

 

📌 Resources 폴더에 있는 프리팹 로드하기

// Resources의 오브젝트 로드하여 생성하기
GameObject go = GameObject.Instantiate( Resources.Load<GameObject>("CubePrefab") );

// 여러번 생성하고 싶은 경우
GameObject prefab = Resources.Load<GameObject>("CubePrefab");
GameObject cube1 = Instantiate(prefab);
GameObject cube2 = Instantiate(prefab);
GameObject cube3 = Instantiate(prefab);

 

 

📌 Resources 폴더에 있는 다양한 타입의 리소스 로드하기

using UnityEngine;
using UnityEngine.UI;

public class ResourceLoader : MonoBehaviour
{
    public Image imageComponent;
    public AudioSource audioSource;
    public Renderer targetRenderer;
    public Animator animator;

    void Start()
    {
        // 1. GameObject 프리팹 로드 및 생성
        GameObject prefab = Resources.Load<GameObject>("Prefabs/Enemy");
        if (prefab != null)
            Instantiate(prefab, Vector3.zero, Quaternion.identity);

        // 2. Sprite 로드하여 이미지에 적용
        Sprite icon = Resources.Load<Sprite>("Sprites/ItemIcon");
        if (icon != null && imageComponent != null)
            imageComponent.sprite = icon;

        // 3. AudioClip 로드 후 재생
        AudioClip clip = Resources.Load<AudioClip>("Audio/JumpSound");
        if (clip != null && audioSource != null)
            audioSource.PlayOneShot(clip);

        // 4. 텍스트 데이터 로드 (예: JSON)
        TextAsset json = Resources.Load<TextAsset>("Data/Config");
        if (json != null)
            Debug.Log("Loaded JSON: " + json.text);

        // 5. Material 로드 및 적용
        Material mat = Resources.Load<Material>("Materials/GlowMaterial");
        if (mat != null && targetRenderer != null)
            targetRenderer.material = mat;

        // 6. Shader 로드 및 머티리얼에 적용
        Shader shader = Resources.Load<Shader>("Shaders/Outline");
        if (shader != null && targetRenderer != null)
            targetRenderer.material.shader = shader;

        // 7. ScriptableObject 로드 (예제용)
        MyGameConfig config = Resources.Load<MyGameConfig>("Configs/GameSettings");
        if (config != null)
            Debug.Log("Loaded config value: " + config.someValue);

        // 8. Animator Controller 로드
        RuntimeAnimatorController controller = Resources.Load<RuntimeAnimatorController>("Animators/PlayerAnimator");
        if (controller != null && animator != null)
            animator.runtimeAnimatorController = controller;
    }
}

 

 

 

에셋이 너무 많을경우 프리팹 할당을 놓치는 경우가 있는데

유용하게 사용할 수 있을 것 같다.

 

하지만 나는

오브젝트에 붙인 컴포넌트의 인스펙터로

구성 내용을 확인하는 습관이 있기 때문에

적절히 잘 섞어서 사용할 것 같다.

 

 


 

wooj22 - Overview

🎮 Game Programmer. wooj22 has 14 repositories available. Follow their code on GitHub.

github.com

 

양우정

 

www.youtube.com