Unity Resources使用 之 快速学会资源Load加载。Unity 中资源加载使用一般分为 静态加载,Resources 和 AssetBundle,每种方法都有搁置的优缺点;本节讲解怎么使用 Resources 方法加载资源,具体如下
工具/原料
Unity
Resources
一、基本概念
1、Resources:The Resources class allows you to find and access Objects including assets.
2、Resources.Load:1、使用形式public static 蚪嬷吃败ObjectLoad(stringpath);public static ObjectLo锾攒揉敫ad(stringpath, TypesystemTypeInstance);2、参数解释path:Pathname of the target folder. When using the empty string (i.e., ""), the function will load the entire contents of the Resources folder.systemTypeInstance:Type filter for objects returned.3、具体描述Loads an asset stored atpathin a Resources folder.Returns the asset atpathif it can be found otherwise returns null. Only objects oftypewill be returned if this parameter is supplied. Thepathis relative to any Resources folder inside the Assets folder of your project, extensions must be omitted.
3、使用中注意:1、Resources类只能读取名为“Resources”的文件夹里的资源,注意是复墙绅褡孛数吾疣璨普形式。2、Resources文件夹需要用户自己新建,可以放在Asset文件夹里任意层级的子目录中,若在不同目录下有多个“Resources”文件夹,加载某个指定资源时每一个“Resources”文件夹都会被检查。因此建议项目中只创建一个名为“Resources”的文件夹,且放在Asset文件夹的根目录下。3、Unity打包发布时,只有Resources文件夹里的资源在会被打入包中。4、Resources类加载资源时,使用”Resources”文件夹开始的相对路径,且不包含资源的扩展名。
二、Resources使用 之 快速学会资源Load加载
1、打开Unity,新建一个空工程,然后Unity界面如下图
2、在工程中新建一个脚本,脚本可以命名为“ResourcesTest”,具体如下图
3、选中“ResourcesTest”脚本,双击脚本或者右键“Open C# Project”,打开脚本,具体如下图
4、在打开的“ResourcesTest”脚本上进行代码编辑,首先设置一个变量,然后使用Load一个参数的方法加载资源,并生成资源到场景中个,最后使用Load带两个参数的方法加载资源,并使用到把之前生成的场景资源中,具体代码及代码说明如下图
5、脚本内容代码如下:using UnityEngine;public class ResourcesTest : MonoBehav足毂忍珩iour { private GameObject go; // Use this for initialization void Start () { go = Instantiate(Resources.Load("Cube")) as GameObject; go.GetComponent<MeshRenderer>().material.mainTexture = Resources.Load("CubeTexture", typeof(Texture)) as Texture; }}
6、脚本编译正确后,回到Unity界面,在场景中新建一个“GameObject”,然后把脚本“ResourcesTest”赋给“GameObject”,并且新建一个“Resources”文件夹,把所需资源放进“Resources”文件夹中,具体如下图
7、运行场景,即可看到场景中的生成的结果,具体如下图
8、到此,《Unity Resources使用 之 快速学会资源Load加载》讲解结束,谢谢