Skip to main content

Unity Native Toast - Technoob Technology

Unity engine is an awesome game engine but it doesn't contain a toast system within its API. In this article, you gonna learn how to create a toast system like the native Android toast system in Unity Engine. To accomplish this we need a tween engine and for this tutorial, we are using LeanTween which is available in the Unity asset store for free. You can change this to whatever tween engine you would like to use. Let's get started. 


This module contains only a single script and pretty easy to understand. Let's call the class as 'Toast' to give a taste of what this is for.

First, we need to create canvas prefab with a rounded rectangle and a text element.
Native toast android unity - technoob technology



Then We create the script called Toast and this should be a singleton in order to keep this toast canvas in every scene without destroying. The singleton pattern is simple and what it does is check if there is another toast canvas and if there is another one destroys the current one and doesn't destroy the game object when switching scenes. Then we add this script to the canvas element.



public static Toast instance;

private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }


We need references to the text elements Rect-transform and to the image elements Rect-transform in order to tween using LeanTween, and we need the reference to the text element to change the text through the script. You can get these using get components in the awake method. But for now, let's keep this as it is. You need to reduce the alpha of both image and text elements to hide them. Don't forget to turn off raycast target as this might block your user interface later if you don't do this.


public RectTransform basicStyleTextRect;
public Text basicStyleText;
public RectTransform basicStyleImageRect;


Now it's time to write the script. The method should be a static method in order to be able to call from other scripts. The code is very simple. A boolean value is needed to check if we are toasting when the method is called.


public static void MakeNativeToast(string _text)
{
        if (!instance.isNativeToasting)
        {
            instance.isNativeToasting = true;
            instance.basicStyleText.text = _text;
            LeanTween.alpha(instance.basicStyleTextRect, 1f, 0.8f).setIgnoreTimeScale(true).setOnComplete(() =>
            {
                LeanTween.delayedCall(0.8f, () => { LeanTween.alpha(instance.basicStyleTextRect, 0, 0.8f); }).setIgnoreTimeScale(true);
            }).setIgnoreTimeScale(true);
            LeanTween.alpha(instance.basicStyleImageRect, 0.75f, 0.8f).setIgnoreTimeScale(true).setOnComplete(() =>
            {
                LeanTween.delayedCall(0.8f, () => { LeanTween.alpha(instance.basicStyleImageRect, 0f, 0.8f).setIgnoreTimeScale(true); });
            }).setIgnoreTimeScale(true);;
            LeanTween.delayedCall(2.6f, () =>
            {
                instance.isNativeToasting = false;
                instance.ContinueNativeQueue();
            }).setIgnoreTimeScale(true);;
        }
}


What we do here is set the text elements text to the argument passed into the method and then increase the alpha value using Leantween and decreasing it according to the given time.


Now the native toast is working perfectly. The only problem in this script is if the method is called while it is toasting we gonna miss the second toast. We can use a Queue to avoid this issue. What we simply do is checking the isToasting bool and if true add the string argument to the queue to toast later.

We need a queue type of string and a simple method to continue the toasting process.


Queue<string> nativeQueue = new Queue<string>();

void ContinueNativeQueue()
    {
        if (nativeQueue.Count > 0)
        {
            string s = nativeQueue.Dequeue();
            MakeNativeToast(s);
        }
    }



The final code should look like this.


public static Toast instance;

public RectTransform basicStyleTextRect;

public Text basicStyleText;

public RectTransform basicStyleImageRect;

Queue<string> nativeQueue = new Queue<string>();

private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

public static void MakeNativeToast(string _text)
    {
        if (instance.isNativeToasting)
        {
            instance.nativeQueue.Enqueue(_text);
        }
        else
        {
            instance.isNativeToasting = true;
            instance.basicStyleText.text = _text;
            LeanTween.alpha(instance.basicStyleTextRect, 1f, 0.8f).setIgnoreTimeScale(true).setOnComplete(() =>
            {
                LeanTween.delayedCall(0.8f, () => { LeanTween.alpha(instance.basicStyleTextRect, 0, 0.8f); }).setIgnoreTimeScale(true);
            }).setIgnoreTimeScale(true);
            LeanTween.alpha(instance.basicStyleImageRect, 0.75f, 0.8f).setIgnoreTimeScale(true).setOnComplete(() =>
            {
                LeanTween.delayedCall(0.8f, () => { LeanTween.alpha(instance.basicStyleImageRect, 0f, 0.8f).setIgnoreTimeScale(true); });
            }).setIgnoreTimeScale(true);;
            LeanTween.delayedCall(2.6f, () =>
            {
                instance.isNativeToasting = false;
                instance.ContinueNativeQueue();
            }).setIgnoreTimeScale(true);;
        }
    }


    void ContinueNativeQueue()
    {
        if (nativeQueue.Count > 0)
        {
            string s = nativeQueue.Dequeue();
            MakeNativeToast(s);
        }
    }


Related Articles,


Stay connected with our facebook page Technoob to get notified when new articles are published. 



Comments

Popular posts from this blog

How to make a first person character controller - Unity

A first-person character controller script is the starting point of any fps shooter game. Even new Unity game developers tend to write their own fps controller script before learning anything else as it is challenging and very exciting. In this article, we gonna create two simple fps controllers from scratch and will guide you step by step on how it works. First, let's understand the basic concept of an fps controller. You should have a rotating camera that rotates in the x-axis to look up and down and the character should rotate on the y-axis to look around. There are two ways to create an fps controller in the Unity Engine.  Using Character controller component Using the RigidBody component Both have different advantages and disadvantages when using them. It depends on your game to select the best fps controller according to your needs.  Character controller based fps controller Pros: Is grounded check is built-in Has its own methods to move the chara

Unity Get Post web requests - Technoob Technology

Web requests in unity are super easy to use. We gonna use the UnityWebRequest class as the WWW class is deprecated now. UnityWebRequest class can be used for both Get and Post methods. The 'UnityEngine.Networking' namespace is required to work with UnityWebRequests.  This tutorial is made with some simple UI elements. First Let's see how the GET method works. 01. UnityWebRequest.GET We use this method to receive data from the server as normal get requests. Using coroutines in web requests is mandatory as we have to wait until the download is complete before showing the results, and the coroutines make this much easier. A simple button calls the method and a text element will show the result. The script contains a reference to the text element and the string URL of your PHP file.  When the button is pressed the button executes the ButtonGetData method and that method simply starts the GetData coroutine. We use the using keyword as this data

How to make an Advanced Audio Manager for Unity - Technoob Technology

Unity engine gives us a good control on audio clips we use, But the problem is when we add several audio sources for several audio clips it's gonna get hard to control them all. And if you want to make some changes to only one audio source you have to find it first.  This will become a mess if you gonna work with more than 10 audio clips. In this case, we can Create an AudioManager and include all the audio clips in it and make some static methods to play, pause the audio from other scripts. This Audio Manager is written in C# and if you use unity-script you have to convert this into unity script first. In this tutorial, we gonna create an audio manager which contains 7 methods. 1.Play 2.Pause 3.Unpause 4.Stop 5.FadeIn 6.FadeOut 7.lower volume for a duration First, we need a Custom class which contains some strings, floats, bools and an audio clip. This class is not derived from unity mono behavior so we should add [System.Serializable] to mak