Using Sprite Images in Unity (1)

4

At first

In this article, even program beginners will find it easy to understand. I try to write comments on most of the source code.

* The version of Unity is 5.6.1f1.

summary

This article summarizes examples and uses of Sprite images in Unity.  ● Basics of Sprite images  ● Fade in, fade out, etc.

Further reading

Unity - Fade In and Fade Out

stream

First, create a 2D Object. A 2D Object can be created from Sprite> GameObject 2D >Object. If you create one, it should look like the following image.

Spriteの生成.PNG

Next, prepare the Sprite image. If you have a black image like the one below, that's fine.

Fade.png

When you drag and drop an image onto Assets in the Project tab, It will be added to Unity's project file.

image.png

When you select the image you added, in this case "Fade" and check the Inspector, You can see the setting of the image. In the initial state, the Texture Type is Default, Change it to Sprite (2D and UI). Press Apply at the bottom right corner. If you forget to press Apply, it will not be applied, so be careful.

image.png

When you select New Sprite from the Hierarchy tab and check the Inspector, You can see the status of SpriteRenderer. Sprite in SpriteRenderer is None (Sprite), so If you click on the Sprite image "Fade" to add it, The Sprite image appears on Scene.

image.png

image.png

image.png

Fade-in rendition with Sprite images

SpriteFadeinInvoker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///------------------------------------------------------
///------------------------------------------------------
/// <summary>
/// ■Sprite画像を利用して,フェードインを行うクラス.
/// </summary>
public class SpriteFadeinInvoker : MonoBehaviour {
    //色のための変数-------------------------------------------
    public float alpha;             //アルファ値
    public float alphaControlTime;  //アルファ値の変化時間
    //--------------------------------------------------------

    //GameObjectの取得----------------------------------------
    public GameObject spriteObject; //2Dオブジェクト(Sprite画像)の読み込み
    //-------------------------------------------------------


    ///------------------------------------------------------
    /// <summary>
    /// ●初期化する関数.
    /// </summary>
    void Start () {
        alpha = 1f; //アルファ値の初期値(Sprite画像が透明でない状態)
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●フェードイン演出を行う関数.
    /// </summary>
    public void FadeIn ()
    {
        alpha -= Time.deltaTime * alphaControlTime; //アルファ値の変化

        /*Scene内にフェード(2Dオブジェクト)が存在するとき,*/
        if (GameObject.Find ("Fade") != null)
        {
            /*フェード(2Dオブジェクト)を発見し,取得する.*/
            spriteObject = GameObject.Find ("Fade");
        }

        //フェード(2Dオブジェクト)の色の読み込み--------------------
        spriteObject.GetComponent<SpriteRenderer> ().color = new Color (0, 0, 0, alpha);
        //-------------------------------------------------------

        /*アルファ値が0以下のとき,*/
        if (alpha <= 0f)
        {
            /*アルファ値は0になる.*/
            alpha = 0f;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●1秒間に呼ばれる回数が一定で実行する関数.
    /// </summary>
    void FixedUpdate ()
    {
        FadeIn ();  //フェードイン演出を行う関数の呼びだし
    }
}

The above source code is a class that performs fade-in staging.

image.png

"SpriteFadeinInvoker.cs" on sprite images, which are 2D Objects Add Component and select a Sprite image under "Sprite Object". Or, if you rename "New Sprite" that you created in Scene, Automatically acquires 2D Objects. Then set the value of "Alpha Control Time" to a value greater than 0 to fade in.

image.png

Fade-out effect with Sprite image

SpriteFadeoutInvoker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///------------------------------------------------------
///------------------------------------------------------
/// <summary>
/// ■Sprite画像を利用して,フェードアウトを行うクラス.
/// </summary>
public class SpriteFadeoutInvoker : MonoBehaviour {
    //色のための変数-------------------------------------------
    public float alpha;             //アルファ値
    public float alphaControlTime;  //アルファ値の変化時間
    //--------------------------------------------------------

    //GameObjectの取得----------------------------------------
    public GameObject spriteObject; //2Dオブジェクト(Sprite画像)の読み込み
    //-------------------------------------------------------


    ///------------------------------------------------------
    /// <summary>
    /// ●初期化する関数.
    /// </summary>
    void Start () {
        alpha = 0f; //アルファ値の初期値(Sprite画像が透明な状態)
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●フェードアウト演出を行う関数.
    /// </summary>
    public void FadeOut ()
    {
        alpha += Time.deltaTime * alphaControlTime; //アルファ値の変化

        /*Scene内にフェード(2Dオブジェクト)が存在するとき,*/
        if (GameObject.Find ("Fade") != null)
        {
            /*フェード(2Dオブジェクト)を発見し,取得する.*/
            spriteObject = GameObject.Find ("Fade");
        }

        //フェード(2Dオブジェクト)の色の読み込み--------------------
        spriteObject.GetComponent<SpriteRenderer> ().color = new Color (0, 0, 0, alpha);
        //-------------------------------------------------------

        /*アルファ値が1以上のとき,*/
        if (alpha >= 1f)
        {
            /*アルファ値は1になる.*/
            alpha = 1f;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●1秒間に呼ばれる回数が一定で実行する関数.
    /// </summary>
    void FixedUpdate ()
    {
        FadeOut (); //フェードアウト演出を行う関数の呼びだし
    }
}

The above source code is a class that performs fade-out rendition.

image.png

The flow itself is exactly the same as the fade-in. "SpriteFadeoutInvoker.cs" on sprite images, which are 2D objects. Add Component and select a Sprite image under "Sprite Object". Or, if you rename "New Sprite" that you created in Scene, Automatically acquires 2D Objects. Then set the value of "Alpha Control Time" to a value greater than 0 to fade out.

image.png

image.png

Switching staging with Sprite images in enumerations

SpriteStagingInvoker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///------------------------------------------------------
///------------------------------------------------------
/// <summary>
/// ■Sprite画像を利用して,色々な演出を行うクラス.
/// </summary>
public class SpriteStagingInvoker : MonoBehaviour
{
    //色のための変数-------------------------------------------
    public float alpha;             //アルファ値
    public float alphaControlTime;  //アルファ値の変化時間
    //--------------------------------------------------------

    //GameObjectの取得----------------------------------------
    public GameObject spriteObject; //2Dオブジェクト(Sprite画像)の読み込み
    //-------------------------------------------------------

    //列挙型の取得--------------------------------------------
    public StagingType stagingType; //演出の種類
    //-------------------------------------------------------

    /// <summary>
    /// ●演出の種類
    /// </summary>
    public enum StagingType
    {
        /// 演出なし
        non,
        /// フェードイン演出
        fadein,
        /// フェードアウト演出
        fadeout
    };


    ///------------------------------------------------------
    /// <summary>
    /// ●初期化する関数.
    /// </summary>
    void Start ()
    {
        StandingTypeChange ();  //演出の種類を切り替える関数の呼び出し
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●初期化時に演出の種類によって対応を切り替える関数.
    /// </summary>
    public void StandingTypeChange ()
    {
        /*演出の種類が,*/
        switch (stagingType) {
        case StagingType.non:   /*演出なしの場合,*/
            /*何もしない.*/
            break;
        case StagingType.fadein:   /*フェードイン演出の場合,*/
            /*アルファ値を1(色を黒)にする.*/
            alpha = 1f;
            break;
        case StagingType.fadeout:  /*フェードアウト演出の場合,*/
            /*アルファ値を0(透明)にする.*/
            alpha = 0f;
            break;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●演出の種類を切り替える関数.
    /// </summary>
    public void StandingTypeInvoke ()
    {
        /*演出の種類が,*/
        switch (stagingType)
        {
        case StagingType.non:   /*演出なしの場合,*/
            /*何もしない.*/
            break;
        case StagingType.fadein:   /*フェードイン演出の場合,*/
            /*フェードイン演出を行う.*/
            FadeIn ();
            break;
        case StagingType.fadeout:  /*フェードアウト演出の場合,*/
            /*フェードアウト演出を行う.*/
            FadeOut ();
            break;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●フェードイン演出を行う関数.
    /// </summary>
    public void FadeIn ()
    {
        alpha -= Time.deltaTime * alphaControlTime; //アルファ値の変化

        /*Scene内にフェード(2Dオブジェクト)が存在するとき,*/
        if (GameObject.Find ("Fade") != null)
        {
            /*フェード(2Dオブジェクト)を発見し,取得する.*/
            spriteObject = GameObject.Find ("Fade");
        }

        //フェード(2Dオブジェクト)の色の読み込み--------------------
        spriteObject.GetComponent<SpriteRenderer> ().color = new Color (0, 0, 0, alpha);
        //-------------------------------------------------------

        /*アルファ値が0以下のとき,*/
        if (alpha <= 0f)
        {
            /*アルファ値は0になる.*/
            alpha = 0f;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●フェードアウト演出を行う関数.
    /// </summary>
    public void FadeOut ()
    {
        alpha += Time.deltaTime * alphaControlTime; //アルファ値の変化

        /*Scene内にフェード(2Dオブジェクト)が存在するとき,*/
        if (GameObject.Find ("Fade") != null)
        {
            /*フェード(2Dオブジェクト)を発見し,取得する.*/
            spriteObject = GameObject.Find ("Fade");
        }

        //フェード(2Dオブジェクト)の色の読み込み--------------------
        spriteObject.GetComponent<SpriteRenderer> ().color = new Color (0, 0, 0, alpha);
        //-------------------------------------------------------

        /*アルファ値が1以上のとき,*/
        if (alpha >= 1f)
        {
            /*アルファ値は1になる.*/
            alpha = 1f;
        }
    }


    ///------------------------------------------------------
    /// <summary>
    /// ●1秒間に呼ばれる回数が一定で実行する関数.
    /// </summary>
    void FixedUpdate ()
    {
        StandingTypeInvoke ();  //演出の種類を切り替える関数の呼び出し
    }
}


The above source code is a class that performs various effects with Sprite images. The flow itself is exactly the same as a fade-in-fade-out rendition. "SpriteFadeoutInvoker.cs" on sprite images, which are 2D objects. Add Component and select a Sprite image under "Sprite Object". Or, if you rename "New Sprite" that you created in Scene, Get the 2D Object. Then set the value of "Alpha Control Time" to a value greater than 0 to fade out.

Finally, if you change the Staging Type from Non to Fadein, it will be a fade-in rendition, If you change it from Non to Fadeout, it will be a fade-out rendition. If it stays as Non, nothing in particular will happen in the production.

image.png

explanation

The three source codes described this time all have the same behavior. By controlling the alpha value of the Sprite image, i.e. the transparency of the color, It enables fade-in and fade-out production.

The variable "alpha" is an alpha value that represents the transparency of the color, as described in the comments. As "alpha" approaches 1, the transparency of the color becomes darker (from transparent to black). As "alpha" approaches 0, the transparency of the color fades (from black to transparent).

The variable "alphaControlTime" is a variable for controlling the alpha value. The higher the value of "alphaControlTime", the faster the rendition. When the value of "alphaControlTime" is 0, nothing happens, so be careful.

To get a 2D Object, look for the object named "Fade" in "GameObject.Find", Once found, it automatically acquires it as a 2D Object. If it could not be found, change the object you want to retrieve to You can attach it to a script to get it.

(* Acquisition by "GameObject.Find" is more than acquisition by attachment work.)   Since it is considered that the processing is heavy, it may be better not to use it as much as possible .... )

This time, the reason why I used the enum type is that I can switch the direction in Inspector I felt that there was usefulness in what I could do. It can be done even by people in charge other than programmers, such as team development. It is possible to switch the rendition.

Postscript

In the next article, the source code described in this article, By using class inheritance, While directing fade in and fade out, I plan to write a script to transition to Scene.

Source code reviews are welcome. It's okay for those who say "it doesn't match the nomenclature and notation of this article!", Please be gentle. If you have any other requests, please contact us.

Thank you for reading until the end.

Share:
4
R T
Author by

R T

三度の飯よりもゲームを制作することが大好きな人間。 使用言語は、C, C++, C#, Java, Processingです。 使用ツール/ライブラリ/エンジンはVisual Studio, eclipse, OpenCV, Processing, POV-ray, Unity, PlayCanvas, Maya, Blenderです。

Updated on June 05, 2018