Unity scene loading and resource loading

sequence

A game is often composed of many scenes, such as main interface scenes, battle scenes, etc. Different scenes are also composed of a number of resources. During the production process of the game, the loading of scenes and resources is indispensable. Short. Both scenes and resources will involve loading issues. When should scenes or resources be loaded? How to distinguish between scene loading and resource loading? Should I use synchronous or asynchronous loading? …

Scene loading

When you need to switch to a new scene, scene loading is involved. Unity scene loading is divided into synchronous loading and asynchronous loading.

Speaking of scene jumps, the preparatory work to achieve scene transitions in Unity is to add the scenes involved in loading to Scenes In Build.
Operation process:
1. Select Build Settings in File

2. Add scenes in Scenes In Build

Commonly used scene loading related methods in Unity

1. Loading scenes (synchronous, asynchronous)

Synchronous loadingScene SceneManager.LoadScene();

The first parameter of this method can use the name of the scene (use a string when entering the name) or the corresponding number in Scenes In Build.
The second parameter of this method is an enumeration variable, and the corresponding enumeration type is LoadSceneMode. This enumeration type has only two values

(1) When assigning LoadSceneMode.Single to the second parameter, this loading scene method will make the current game have and only the scene we have given (the scene passed in by the first parameter) will is loaded.
(1) When assigning LoadSceneMode.Additive to the second parameter, the scene we gave will be loaded and displayed at the same time as the currently loaded scene.

One problem with this synchronous scene loading method is that when the loaded scene is large and complex, the loading speed will slow down, and there will be lags during loading. To solve this problem, Unity provides a new method.

Asynchronous loadingScene SceneManager.LoadSceneAsync();

This method has a return value i, and the type of the return value is AsyncOperation. We can track the loading progress of the scene by receiving this return value.

AsyncOperation.isDone 
// 这个是用来判断加载是否完成。这个属性是加载完并且跳转成功后才会变成完成。
AsyncOperation.allowSceneActivation 
// 这个是加载完后,是否允许跳转,当为false时,即使场景加载完了,也不会跳转。
AsyncOperation.progress 
// 这个时表示加载场景的进度。实际上的值时 0 - 0.9, 当值为0.9的时候,场景就已经加载完成了。

It should be noted that the SceneManager.LoadSceneAsync() method can also be called in a normal method, but doing so will cause the main thread to be blocked, causing the application to freeze or become unresponsive during loading. Therefore, asynchronous loading scenarios are more recommended for use in unloading coroutines.

2. Get the current scene SceneManager.GetActiveScene();

This method is usually used to perform some subsequent operations to obtain information, such as

// 获取当前场景
Scene scene = SceneManager.GetActiveScene();
// 场景名称
Debug.log(scene.name);
// 场景是否已经加载
Debug.log(scene.isLoaded);
// 场景路径
Debug.log(scene.path);
// 场景索引
Debug.log(scene.buildIndex);

3. Get all game objects in the scene pointed to by the calling scene object

Scene scene = SceneManager.GetActiveScene();
GameObject[] gos = scene.GetRootGameObjects();

The above are all methods for scenes. Here are some methods for scene management classes.

4. Get the number of currently loaded scenes

Debug.log(SceneManager.sceneCount);

This variable can get the number of currently loaded scenes. There is not only one scene that can exist at the same time, but multiple scenes can be superimposed.

5. Create a new scene

// 方法中的参数是新场景的名称
Scenee scene = SceneManager.CreateScene("newScene"); 

6. Uninstall scene

// 参数是要卸载的场景的场景名
SceneManager.UnloadSceneAsync(newScene);

After uninstalling this scene, the scene and its corresponding scene files will be deleted.

Analyze LoadSceneAsync related issues

The reason why LoadSceneAsync is analyzed separately here is because this method of Unity asynchronously loading scenes does have some pitfalls, which is not convenient for users to use.

1. SceneManager.LoadSceneAsync() is not really background loading, it loads some resources in each frame;
2. After setting allowSceneActivation to false, Unity It will only load to 90%, and the rest will not be loaded until allowSceneActivation is set to true. When loading to 90%, we artificially control the value of the progress bar to 100%, but the loading is not actually completed, so it will freeze;
3. Conversion rules for converting float type to int type: The value will be rounded towards zero, 1.99 will return 1, and 0.9 will return 0, so my progress bar directly goes from 0 to 100. For this reason, it always returns 0.

Type conversion rules:
When performing forced type conversion between int (assuming int is 32-bit), float and double formats, the principles are as follows:
1. Convert from int to float, the number will not overflow, but may be rounded.
2. Convert from int and float to double to retain accurate values. Because double has a larger range and higher precision (significant digits).
3. Convert from double to float. Because the range of float is smaller, the value may overflow to +∞ or -∞. In addition, due to the small precision of float, it may be rounded.
4. When converting from float or double to int, the value will be rounded towards zero. For example, 1.999 will be converted into 1, and -1.999 will be converted into -1. At the same time the value may overflow.

Resource loading

Resource loading is similar to scene loading. There are also synchronous loading and asynchronous loading. In the process of developing games using Unity, the loading of resources has always been a focus.

Resource loading method provided by Unity

Unity provides a total of 5 ways to load resources, namely
1. Resources (only resources in the Resources directory can be loaded)
2 , AssetBundle (only AB resources can be loaded, and any path allowed to be accessed by the current device can be used)
3. WWW (can load resources from anywhere, including resources outside the project (such as remote servers)) 5. UnityWebRequest (can load resources anywhere, is an upgraded version of WWW )
4. AssetDatabase (can only load resources in the Assets directory, but can only be used for Editor)

The meaning, advantages and disadvantages of synchronous loading and asynchronous loading

Since there are two ways to load resources, synchronous and asynchronous, it must be because both have their own advantages and disadvantages. Only by understanding the differences between the two can we use them flexibly in development.

1. Synchronization: It does not mean simultaneously or together literally, but refers to coordinated steps, assistance, and mutual cooperation. It is executed in sequence. When issuing a function call, it will wait until the return result is obtained and will not continue execution.

Advantages of synchronization: easy management, resources can be returned in time when ready. Disadvantages: Not as fast as asynchronous.

2. Asynchronous: Just the opposite of synchronous, that is, when issuing a function call, regardless of whether the result is obtained or not, the execution continues. Asynchronous loading of at least one frame Delay.

Advantages of asynchronous: fast speed has nothing to do with the main thread. Disadvantages: Calling is cumbersome. The best way is to use callbacks.

Commonly used resource loading related methods of Resource in Unity

1, Synchronous loadingResources Resources.Load();

(1) The root directory when reading files is Assets/Resources. All resource files are placed in this folder. The path in the command starts from the Resources folder.
(2) Use / to indicate subfolders.
(3) Do not add the file suffix to the file being read.
(4) The type of reading written in <> after Load.

2, Asynchronous loadingResources Resources.LoadAsync<>();

Asynchronous loading of Resources means opening a new thread internally to load resources, which will not cause the main thread to get stuck.

Note: Asynchronous loading cannot get the loaded resources immediately, it must wait for at least one frame.

The more common ways to load resources asynchronously are: one is event listening to implement asynchronous loading, and the other is coroutine to implement asynchronous loading. Both methods have their own advantages and disadvantages. The event monitoring method implements asynchronous loading. The advantage is that the writing method is simple, but it has certain limitations. It can only be used when resources are loaded. Processed after the end, this actually belongs to "Linear loading". Asynchronous loading is implemented through coroutines. The advantage is that complex logic can be processed in coroutines (for example, loading multiple resources at the same time, updating progress bars, etc.) , but the corresponding writing logic will be more complicated, which is actually similar to "Parallel loading".

Loading transition (loading interface)
Whether it is a scene or a resource, there will be a problem when it is loaded asynchronously. When the resource is loaded asynchronously, there may be Switching scenes before the resources are loaded will result in poor performance.
Q: How to solve performance problems when resources are loaded asynchronously?
A: Generally speaking, the simplest way is to use the UI to block it (loading interface). Another more common way is to jump to the loading page scene after clicking the button on other homepages. , and at the same time asynchronously load the scene to be jumped to.

There are many ways to implement the loading interface, and there are many documents on the Internet. I will not go into details here. Here are several relevant links for reference:
1. http://t.csdn.cn/VTTvA
2. http://t.csdn.cn/wlmwqhttp://t.csdn.cn/h6Pnn
3.

参考文档:
1、https://blog.csdn.net/ChinarCSDN/article/details/82914541
2、http://t.csdn.cn/NfaMx
3、http://t.csdn.cn/wqenA

Guess you like

Origin blog.csdn.net/ProSWhite/article/details/132600551