Unity中Prefab存在却向列表加载空GameObject问题
Unity中Resources.Load加载Prefab为空的问题解决
我在编写Unity C#代码时,期望程序运行时将指定Prefab添加到列表中,代码无报错,但实际添加的是空GameObject,尽管已指定了具体的Prefab。
问题代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class HomeScreen : MonoBehaviour { public List<GameObject> myCollection; public int money = 1000; [SerializeField] public TMPro.TextMeshProUGUI currentMoney; // Start is called before the first frame update void Start() { myCollection.Add(Resources.Load<GameObject>("Assets/Resources/dogPrize.prefab")); } void Update() { currentMoney.text = "Money: $" + money.ToString(); } public void buyScreen() { SceneManager.LoadScene(sceneName:"Buy Screen"); } }
实际输出

Prefab存放位置

预期结果

问题原因与解决办法
- 核心错误:
Resources.Load的路径规则是不需要包含Assets/Resources/前缀,也不需要带.prefab后缀。你写的完整路径会让Unity无法定位到资源,返回null,导致列表添加空对象。 - 修复后的Start方法:
void Start() { GameObject dogPrefab = Resources.Load<GameObject>("dogPrize"); if (dogPrefab != null) { myCollection.Add(dogPrefab); } else { Debug.LogError("无法加载dogPrize预制体,请检查资源是否在Resources文件夹下,路径是否正确"); } }
- 额外提示:
- 确保Prefab确实放在
Assets/Resources目录下,Unity的Resources.Load只会识别该目录内的资源。 - 添加空值判断可以提前发现加载失败的问题,避免后续逻辑出现异常。
- 确保Prefab确实放在
内容的提问来源于stack exchange,提问作者Noodle
相关产品推荐
相关产品推荐

