Resources 类允许您查找和访问资源等对象。
在编辑器中,Resources.FindObjectsOfTypeAll 可用于定位资源和场景对象。
通过 Resources.Load 函数,可访问 Assets 文件夹中处于任意位置的名为“Resources”的文件夹中的所有资源。
可以存在多个“Resources”文件夹,加载对象时,将对每个文件夹进行检查。
在 Unity 中,我们通常不使用路径名称访问资源,而是通过声明一个成员变量来公开对资源的引用,然后在 Inspector 中对其进行分配。
使用该技术时,Unity 在构建玩家时能够自动计算使用的资源。
这从根本上将玩家的大小尽可能地限制为您在构建的游戏中实际使用的资源大小。
当您将资源放入“Resources”文件夹时,则无法实现这一效果,因此“Resources”文件夹中的所有资源都将包含在构建中。
使用路径名称的另一个缺点是,由于脚本会对所使用的资源的放置位置提出特定的硬编码要求,因此会降低代码的重用性。
另一方面,在 Inspector 中使用公开的引用具有自文档化的特点,对脚本用户来说也更加直观易懂。
但是,在某些情况下,通过名称获取资源比在 Inspector 中链接到资源更为方便。
基本上,只要不方便在 Inspector 中为对象分配引用时,
您就应该,例如,在脚本中以程序方式创建游戏对象、将纹理指定给程序生成的网格等。
某些已加载的资源,尤其是纹理,即使在场景中不存在其实例时,也会占用相当多的内存。要在不再需要该资源时回收其内存,可以使用 Resources.UnloadUnusedAssets。
注意:Assets 中的 Resources 文件夹需要在使用前创建。创建新项目时,不会创建该文件夹。
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { void Start() { GameObject go = GameObject.CreatePrimitive(PrimitiveType.Plane); Renderer rend = go.GetComponent<Renderer>(); rend.material.mainTexture = Resources.Load("glass") as Texture; } }
FindObjectsOfTypeAll | 返回所有类型为 T 的对象的列表。 |
Load | 加载存储在 Resources 文件夹中的 path 处的资源。 |
LoadAll | 加载位于 Resources 文件夹中的 path 处的文件夹中的所有资源,或加载位于该处的文件。 |
LoadAsync | 异步加载存储在 Resources 文件夹中的 path 处的资源。 |
UnloadAsset | 从内存中卸载 /assetToUnload/。 |
UnloadUnusedAssets | 卸载未使用的资源。 |
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.