【Unity】Resources.Load

本文详细介绍了Unity中使用协程和Resources.LoadAsync进行资源异步加载的方法。通过StartCoroutine开启协程,利用yield return null等待加载完成,然后实例化并放置加载的资源。同时,展示了如何递归加载多个资源。
摘要由CSDN通过智能技术生成

Unity Resources.LoadAsync使用

1、StartCoroutine(函数名)开启一个协程

2、返回值为IEnumerator的函数,函数中有yield return类型返回值,当yield return执行后,才会执行yield return以后的代码块

3、Resources.LoadAsync(资源路径)  异步加载的使用    返回值为ResourceRequest

      asset  被加载的资源

      isDone 加载是否完成,bool类型

      progress  加载的进度

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class test : MonoBehaviour

{

    // Start is called before the first frame update

    void Start()

    {

        //开启协程

        for(int i =0 ; i<64 ;i++)

        {

            StartCoroutine(AsyncLoadResources(0,i*28));

        }

    }

    // Update is called once per frame

    void Update()

    {

    }

    IEnumerator AsyncLoadResources(int index,int posx)

    {

        ResourceRequest resourcesRequest = Resources.LoadAsync("CSample" + index, typeof(GameObject));

        while (!resourcesRequest.isDone)

        {

            //Debug.Log("Loading progress: " + resourcesRequest.progress);

            //资源没有加载完成  返回空,加载完以后进行后面的模块

            yield return null;

        }

        GameObject prefab = resourcesRequest.asset as GameObject;

        //场景中实例化资源

        prefab = Instantiate(prefab,new Vector3(posx,0,0),Quaternion.identity);

        if (index < 5)

        {

            //协程中调用协程

            StartCoroutine(AsyncLoadResources(++index,posx));

        }

    }

}

————————————————

版权声明:本文为CSDN博主「ZSY今天也要学习」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_41194189/article/details/117330918

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值