Unity-Resources are loaded asynchronously

 Knowledge point 1 What is asynchronous loading of Resources

 Knowledge point 2 Resources asynchronous loading method

 1. Use the loaded resource by listening to the completion event in asynchronous loading

 When we use the LoadAsdync function of Resources to load files asynchronously, if we only do this step, then it will have no effect. What is done here is just to configure the environment and load the data. Here is a question, how do we know if it is loaded?

Look at its return type is a ResourcesRequest type, enter the interior:

Its base class AsyncOperation has an event, completed

 When the loading is complete, this function will call the completed event to notify the external that the loading is complete. We can detect whether the loading is complete by listening to this event. Add a new delegate to the completed event. When the loading is complete, the system calls completed and executes LoadOver (AsyncOperation rq). Print loading is complete.

 The image is loaded and we need to use it. We use it in OnGUI.

Pay attention to whether this judgment is null, asynchronous loading takes a certain amount of time to load the file. It doesn't finish loading right away. Therefore, a conditional judgment must be made.

When will resources be instantiated?

 When the asynchronous loading is completed, the asset public property will get the loaded resource. We get the content inside by calling asset.

Note that two as conversions are required here

The first time as: because asset is a property of ResourcesRequest. So turn AsyncOperation into ResourcesRequest

The second as:asset returns the Object type, and we need to use Texture to receive it. So it is Object to Texture;

 2. Use the loaded resources through the coroutine

First create a coroutine:

 yield return will return some specific content. Use rq as the return value of yield return.

 The base class of ResourcesRequest is AsyncOperation

 AsyncOperation为YieldInstryction

The base class of WaitForSeconds is also YieldInstryction.

 Prove that ResourcesRequest is also related to coroutines.

 When the resource is loaded, the following code will be executed. After the resources are loaded, instantiate the image.

 test:

 use of attributes.

 The above two methods, whether through time completed or through coroutines, mainly solve a problem. Is the file loaded? Because I can only instantiate when the file is loaded. The first method is to use completed to complete the loading and instantiation, and the second method is for the system to help us complete the judgment of whether the loading is complete.

 

Guess you like

Origin blog.csdn.net/qq_42705793/article/details/127692906