[Unity] Resource Manager로 prefab 불러오기

Yerin·2023년 7월 12일
0

Manager로 관리하는 것이 더욱 효율적이다.

이전 코드를 아래와 같이 변경해 준다.

PrefabTest.cs

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrefabTest : MonoBehaviour
{
    GameObject prefab;
    GameObject tank;
    void Start()
    {
        
        
        tank = Managers.Resource.Instantiate("Tank");
        Destroy(tank, 3.0f);
       
    } 
}

ResourceMAnager.cs

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;

public class ResourceManager 
{
    public T Load<T>(string path) where T : Object 
    {
        return Resources.Load<T>(path);
    }

    public GameObject Instantiate(string path, Transform parent = null)
    {
        GameObject prefab = Load<GameObject>($"Prefabs/{path}");
        if (prefab == null)
        {
            Debug.Log($"Failed to load prefab : {path}");
            return null;
        }
        return Object.Instantiate(prefab, parent);
    }

    public void Destroy(GameObject go)
    {
        if (go == null)
            return;

        Object.Destroy(go);
    }    
}
profile
재밌는 코딩 공부

0개의 댓글