Unity 四、常用脚本(十四)Resources加载

Resources加载

使用Resources可以加载获取项目中Project中的资源。

使用前需要将要加载的资源放到Resources文件夹中,文件夹需要自己创建。

创建文件夹:在Project界面右击选择Create,然后选择Folder。

加载预制体:

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

public class TestLoad : MonoBehaviour
{
    GameObject objNeed;//需要加载到场景中的物体
    GameObject objClone;//克隆物体

	void Start ()
    {
        //加载资源
        //写加载路径时不能加上Resources
        //此时场景中还无法看到
        objNeed = (GameObject)Resources.Load("Prefab/Cube");

        //将加载的资源实例化到场景中,此时场景中已经有了需要的物体
        objClone = Instantiate(objNeed);

        //根据需要对场景中的物体进行一些设置
        objClone.transform.parent = transform;//设置父节点
        objClone.transform.position = Vector3.zero;//设置位置
        objClone.name = "New";//重命名
    }
}

加载图片:

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

public class TestLoad : MonoBehaviour
{
    Sprite texNeed;//需要加载到场景中的物体
    SpriteRenderer tex;//场景中的物体

	void Start ()
    {
        //获取场景中物体
        tex = GameObject.Find("Tex").GetComponent<SpriteRenderer>();

        //加载资源
        texNeed = Resources.Load<Sprite>("Texture/TestTexture");

        //将加载的图片资源替换原图
        tex.sprite = texNeed;
    }
}

猜你喜欢

转载自blog.csdn.net/NCZ9_/article/details/88660893
今日推荐