[unity3d] Unity3d game development asynchronous record scene and achieve progress bar read effect

Source: Internet
Author: User

hello, I am Qin Yuanpei. Welcome everyone to follow my blog, my blog address is: blog.csdn.net/qinyuanpei. Finally in a variety of non-language paper work free, so immediately hurry to update the blog Here. Bo Master originally planned to Unity3d game development from the "soul bucket luo" game (on)--target Tracking This article and then write a "Unity3d game development from the" bucket Luo "game talk about (next)", but now Bo master project progress somewhat slow, So I want to wait until the project stabilized and then share with YOU.

As everyone waits for blogger to update the Blog's return, Let's say today that the game scenes in Unity3d are loaded asynchronously. So what is the game scenario asynchronous loading? Asynchronous loading is the System's ability to run other tasks when loading data, such as map data, model data, player data, and so On. In fact, we are familiar with Multithreading. conversely, in a single thread. We usually need to wait until the data is loaded and then continue to run the Task. We can find this example in games such as "paladin biography" and "gujian tan". For example, "chinese Paladin four" in the Wudu Beast Courage Reading bar Effect:


For example, "gujian tan" in the introduction of the game features introduced reading bar effect:


From the above examples we can see that in the game design through a reasonable game scene loading mode, reduce the player waiting Time. A problem that needs to be considered when designing a Game. A good web design in web design typically takes into account the need to minimize the time that a user waits for a page response, so that no user traffic is Lost. In an era of user-focused Experience. No matter what the design of the product, to bring users the most extreme experience is the most Important. We've noticed that all two games have been loaded in an asynchronous way. As the process of loading the game, the system is running the GUI elements of the interface drawing Work. so, well, After understanding the concept of asynchronous loading and the principle of asynchronous loading, we're going to implement Today's content, which is what we want to do today, and we want to be able to show the different cue content alternately below the progress bar in the process of loading the game today:



So how do we do that in detail? A Loadlevelasync () method is provided in Unity3d. This method can be used to load scene resources asynchronously.

The method returns a return value of type asyncoperation, which has two important properties: 1, isDone: ability to query for loading complete, 2,progress: A value between 0-1 to indicate the progress of loading

All right. Through these two properties and this Method. We will be able to achieve Today's content, start together!

First create a scene where we use the System's default GUI system,




This interface is our loading interface today, in the process of loading the interface, we can display the game tips and game progress under the Background. Usually. We need three interfaces to complete a full interface loading Effect.

The first interface, called the trigger interface, is primarily responsible for responding to user triggering actions. The second one is the loading interface we're talking about here today, which is primarily about reading bars and UI Refreshes. The third interface is the one that we finally present to the Player.

This analogy is in the "paladin biography" Game. The effect of an arrow appears at the door when the player is near the House. This will prompt the player to enter the triggering area of the scene loading. When the player enters this range, it will trigger the display of the loading interface. So that we can see the Wudu Beast Courage Reading Effect. When the bar is finished, it will go to the third interface, which is the interface we are finally going to show to the Player. well, That's The whole process of asynchronously loading a game scene.

Let's write the following script to implement Today's function, for the loading process this interface, we mainly use our Loadlevelasync () method:

Using unityengine;using System.collections;public class Loading:monobehaviour {//async object Private AsyncOperation mAsyn;//                    Binding tip guitextprivate Guitext mtip;//tip collection, The actual development of the need to read from the external file private string[] mtips=new string[] { "during Asynchronous Onboarding You can browse the introduction", "you can view the current progress during asynchronous loading", "you can infer whether loading is complete during asynchronous loading", "bo Master does not understand Xuan 6 Read the bar Why so slow "," is it because doom do not understand Unity3d ",};//update tip time Private Const float Updatetime=2.0f;//last finer Time Private float lasttime=0.0f;void Start () {mtip=gameobject.find ("guitips"). Getcomponent<guitext> (); Startcoroutine ("Load");} IEnumerator Load () {masyn=application.loadlevelasync ("Main"); yield return masyn;} void Update () {//if the scene is not loaded then show tip if (masyn!= null &&!masyn.isdone) {//assume that the updated time is reached if (time.time-lasttime>=    Updatetime) {lasttime=time.time; Mtip.guitext.text=mtips[random.range (0,5)]+ "(" + (float) masyn.progress * 100+ "%" + ")";}} Else{application.loadlevel ("Main");}}}


The code here is very well understood. Assuming the load is complete, load the end interface, otherwise the tips and loading progress will be displayed randomly.

In order to save time, bloggers are using the scenes from the previous Article.


For the interface that triggers the loading event, we just need to use the normal loading method:

Using unityengine;using system.collections;public class Triggertoload:monobehaviour {void Ongui () {if ( Guilayout.button ("load loading scene", guilayout.height ()) {application.loadlevel ("Scene2");}}}
obviously, This is a way to load a scene when the user clicks the button, so there's no more Explanation. Because this method only supports the Pro version number of unity3d, so Bo Master's free version of Unity3d is doomed to be unable to run, so here can not give you a program demonstration, I hope you understand ah. There are two common problems with the Unity3d asynchronous load Scenario:

1, use asyncoperation progress to get loading progress, load progress unchanged

2. Unable to capture the event loaded in the scene: using Dontdestroyonload to solve

well, Today's content is this, the Bo master's ability is limited, can understand only so Much. No matter what. Or hope to grow together with you, Hehe.

articles:Unity3d Research Institute asynchronous load game scenario and asynchronous load game resource progress bar Asynchronous transition of game scenes using the loading interface

Daily Motto: The Brave is not the one without Tears. But a man who runs with tears and Smiles.


like my blog please remember my name: Qin Yuanpei, my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the SOURCE. This article Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/30836567


November 30, 2015 update:A friend asked about the effect of this article is not possible, this is because this article writing time is Longer. and the Unity3d version number that the blogger used at that time was the free version number, so the contents of the asynchronous loading of this piece did not undergo a deep test.

Now that we have asked this question, I would like to add that there is a better way to solve this problem on the Internet.

First of all. One thing we should understand is that asynchronous loading differs from synchronous loading. Asynchronous loading is non-clogging, so in this process we can use a progress bar or loading interface to transition the loading process of the SCENE. second, the asynchronous loading of Unity3d has a bug that stops loading when the progress is loaded into 0.9. And it's going to be a bit of a lag. therefore, We cannot use 1.0 as an inferred flag to complete the Loading. The asyncoperation in Unity3d is a class in which we handle scenarios when loading asynchronously. This class encapsulates the information about the scene Loading. If the scene is loaded with Isdone and the current scene is loading the progress progress. Over here. We want to focus on allowsceneactivation this Attribute. This property determines whether the load of the remainder of the content is loaded by Unity3d itself when the scene is loaded to 0.9, so the default property is true, so when we load to 0.9, the scene will be slightly stuck. so, well, How do we solve the problem? This is done in two parts, that is, the previous 0.9 is loaded by UNITY3D. And the remaining 0.1 is manually loaded by Us. Let's take a look at the following code:

IEnumerator loadsceneasync (string Levelname) {///        Current progress        int currentprogress = 0;        Target progress        int targetprogress = 0;        AsyncOperation op = Application.loadlevelasync (levelname);        Load in front of 0.9        op.allowsceneactivation = false;        While (op.progress < 0.9f)        {            //calculate target progress            targetprogress = (int) op.progress *;            Smooth while            (currentprogress < Targetprogress) {++currentprogress) between current progress and target            progress                ;                Handle loading the relevant logic                yield return new waitforendofframe ();            }        }        Load the remaining 0.1        targetprogress = +;        Smooth while        (currentprogress < Targetprogress) {++currentprogress) between current progress and target        progress            ;            Handle loading the relevant logic            yield return new waitforendofframe () here;        }        Op.allowsceneactivation = true;    }


In this code, we actually use the Allowsceneactivation property to control the process of loading the scene, the previous 0.9 is the normal loading process, while the remaining 0.1 is the loading process that is added for the sake of the Deceive.

Here we also use a smooth process, which is due to the assumption that loading related logic such as a progress bar is set directly with the target PROGRESS. So the situation is that the loading progress is uneven, because the loading progress is jumping.

But can the actual loading progress be controlled evenly? The answer is No. Because the loading process of the resources itself is not uniform ah. So essentially the progress bar is the game resources in the process of fig leaf, it itself with a very strong sense of deception, such as the progress has been recorded in 99%, the results of the last 1% is loaded into a good long time, this science? This is obviously unscientific. This is where the blogger once again finds the original project and once again writes the code implementation of the scene to load the progress bar effect:


ok, this piece of the basic nothing to say, again reminded not to read code directly copy code, I am not what the great God. I wrote the code has been very slag, I have never intended to give you a Out-of-the-box programming experience, because the programming process itself is confusing, you need to explore the Step-by-step. Suppose you just copied the code I wrote to the editor, but I don't know what to do with the script, where there are errors in the Script. I don't think I really need to be selfless in this way, and I'm earning a lot from the open source community myself. So I'm willing to share what I've learned and explored, but that's not why you're lazy, right? A lot of novices think I'm particularly demanding for Beginners. Maybe the newbies think that if I do, I'm going to ask You. But the problem is the novice does not know how to ask questions or even do not know how to think, I do the undergraduate thesis, although the face is the professional I do not like. But I am more serious than every classmate in the class, even when the thesis to reply to the results will not be too big difference, but I like the process, because it let me know how to think, no doubt, to others to ask is to do homework, assuming do not know how to question, can often know, Suppose you want me to write the code directly to you, and even help you debug the code to find the bug, sorry I do not have this Obligation. A reader from the beginning of last week to me frequently asked for an article does not give the source of an IO class Code. I think I've explained the role of this class very clearly, and it's not doing anything particularly complicated. Just a simple encapsulation of the System.IO Namespace. I think anyone with a programming base should be familiar with the IO Section. But almost a week later, the reader still did not realize this part of the function, and even if I gave you the code, you will be seriously read it and then gain from it? Oh. I really don't want to be indignant about the laziness of some people. I am willing to share the technology is my freedom. I am not willing to provide complete code the same is my freedom. Coercion is not of any significance whatsoever. Except to make you more Ignorant. okay, This is the update!





[unity3d] Unity3d game development asynchronous record scene and achieve progress bar read effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.