Tuesday, January 6, 2015

Loading screen in Unity3d

Standard
Hello All:

While creating games using Unity3d, often we need to show Loading screen in case of long running operations. In this post, I will show how to create a loading screen in Unity3d.

By the end of tutorial, we will have loading screen as can be seen here. We will start by creating an empty screen. Then create an empty object with following hierarchy.

Loading Screen


Set following settings for Background Game object. The texture used can be downloaded from here.

Loading Screen

Set following settings for Text Game object

Loading Screen




Set following settings for Dots Game object

Loading Screen

Now create a script "LoadingScreenController.cs" and copy following code in the file.

 
using UnityEngine;
using System.Collections;

public class LoadingScreenController : MonoBehaviour
{
    static LoadingScreenController instance;
    Transform dots;
    string startText;
    float updateTime = .1f;
    float startTime;
    public static LoadingScreenController Instance
    {
        get
        {
            return instance;
        }
    }
    void Awake()
    {
        if (instance)
        {
            Destroy(gameObject);
            Instance.Hide();
            return;
        }
        instance = this;
        instance.startText = "";
        foreach (Transform item in transform)
        {
            if (item.name == "Dots")
            {
                dots = item;
            }
        }
        DontDestroyOnLoad(this);
        instance.startTime = Time.time;
    }


    public void Show()
    {
        instance.startText = "";
        instance.startTime = Time.time;
        if (instanceAvailable())
        {
            instance.gameObject.SetActive(true);
        }
    }

    public void Update()
    {
        if (instanceAvailable())
        {
            if (Time.time > instance.startTime + instance.updateTime)
            {
                if (instance.startText.Length == 3)
                {
                    instance.startText = "";
                }
                startText = startText + ".";
                instance.dots.gameObject.guiText.text = startText;
                instance.startTime = Time.time;
            }
        }
    }
    public void Hide()
    {
        if (instanceAvailable())
        {
            instance.gameObject.SetActive(false);
        }
    }

    bool instanceAvailable()
    {
        return instance != null;
    }
}


Hope this helps. The full working code can be found here.

Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment