You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity泛型类中使用Resources.Load加载ScriptableObject的问题

泛型资源加载类适配Unity ScriptableObject的解决方案

你需要给泛型类的T添加类型约束,因为Unity的Resources.Load<T>()方法要求T必须是UnityEngine.Object的子类(你的armorData、weaponData等ScriptableObject都满足这个条件)。原代码没有约束,导致编译器无法确认T和UnityEngine.Object的继承关系,所以会报错。

修改后的完整代码

using UnityEngine;
using System.Collections.Generic;
using System.IO;

public class ResourceCollector<T> where T : UnityEngine.Object
{
    public List<T> LoadPlayerResources(SaveDataStructure savedPlayerStats, List<string> savedCollection, string folderPath)
    {
        List<T> itemResources = new List<T>();

        foreach (var itemName in savedCollection)
        {
            T itemDataFromResources = LoadFromResource(folderPath, itemName);
            // 可选:添加空值检查,避免加载失败的资源加入列表
            if (itemDataFromResources != null)
            {
                itemResources.Add(itemDataFromResources);
            }
        }

        return itemResources;
    }

    public T LoadFromResource(string path, string itemName)
    {
        return Resources.Load<T>(Path.Combine(path, itemName));
    }
}

关键修改点

  • 在类的泛型声明后添加where T : UnityEngine.Object,明确T必须继承自Unity的Object类型,让编译器认可Resources.Load<T>()的返回值可以直接转换为T
  • 可选添加空值判断,防止加载不存在的资源时将null添加到结果列表中

内容的提问来源于stack exchange,提问作者Alice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:07:03