1. 程式人生 > >Unity 之非同步載入

Unity 之非同步載入

學習下
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class UIMenu : MonoBehaviour
{
    /// <summary>
    /// 載入時間
    /// </summary>
    public float m_Time = 5f;

   

    /// <summary>
    /// 線的顏色
    /// </summary>
    public Color color;
    /// <summary>
    /// 是否開始漸變顏色
    /// </summary>
    private bool m_isColorGradient = false;

    /// <summary>
    ///載入Loading的背景 
    /// </summary>
    private Image m_ImageLg;
    /// <summary>
    /// 載入Loading 的text
    /// </summary>
    private Text m_TextLg;
    /// <summary>
    /// 是否載入完成
    /// </summary>
    private bool m_load_switch = false;
    /// <summary>
    /// 非同步操作
    /// </summary>
    private AsyncOperation async_operation;
  



    void Awake()
    {
        //m_VR = Resources.Load("Prefab/[CameraRig]") as GameObject;
        //m_RayClickEffect = Resources.Load("effect") as GameObject;


        Initialize();
    }
    private void Initialize()
    {
        m_ImageLg = m_Menu.transform.FindChild("Loading").GetComponent<Image>();
        m_TextLg = m_Menu.transform.FindChild("Loading").FindChild("Text").GetComponent<Text>();
    }

    void Start()
    {
        m_isColorGradient = false;
    }


    void Update()
    {

        if (m_load_switch)
        {
            if (async_operation.isDone)
            {
                m_isColorGradient = false;
                m_load_switch = false;
            }
        }
        ColorChange(m_ImageLg.color, m_TextLg.color, m_isColorGradient);

    }

    /// <summary>
    /// 場景載入
    /// </summary>
    /// <param name="device"></param>
    /// <param name="hand"></param>
    /// <param name="m_tip"></param>
    /// <param name="raycast"></param>
    /// <param name="hit"></param>
    public void DeviceAction()
    {

                    m_isColorGradient = true;
                    StartCoroutine("LoadScene", "Medieval Village");
                
    }
   
    /// <summary>
    /// 載入場景
    /// </summary>
    /// <param name="scene_name"></param>
    /// <returns></returns>
    IEnumerator LoadScene(string scene_name)
    {
        async_operation = SceneManager.LoadSceneAsync(scene_name);
        m_load_switch = true;
        yield return async_operation;
    }

    /// <summary>
    /// 顏色漸變
    /// </summary>
    private void ColorChange(Color color1, Color color2, bool isGradient)
    {

        if (isGradient)
        {
            if (m_ImageLg.color.a <= 1)
            {

                Debug.Log(isGradient + "dsfdsfdsf" + i++);
                m_ImageLg.color += new Color(0, 0, 0, 0.01f);
                m_TextLg.color += new Color(1, 1, 1, 0.01f);
            }

        }
        else
        {
            if (m_ImageLg.color.a > 0)
            {
                m_ImageLg.color -= new Color(0, 0, 0, 0.01f);
                m_TextLg.color -= new Color(1, 1, 1, 0.01f);
            }
        }
    }
}