最近在學習UI框架,無奈沒有完整的專案學習,四處搜尋找了這款遊戲原始碼,在Unity2018上完美執行。於是乎開始學習開發這款遊戲。今天主要完成的任務時拼UI。搭建了3個場景, StartScene, LoadingScene, MainScene。PlayScene比較複雜,包含了複雜的邏輯,放在最後學習。
1.StartScene
這個場景比較簡單,主要包括3個部分:背景,Logo,開始按鈕。
邏輯:點選開始按鈕,進入LoadingScene。
在UICamera或者Canvas(StartScene)物體上掛載指令碼StartMgr.cs
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StartMgr : MonoBehaviour
{
public Button btnStart;
private void Start()
{
if(btnStart != null)
{
//給按鈕新增監聽事件
btnStart.onClick.AddListener(OnLoadLevel);
}
} private void OnLoadLevel()
{
SceneManager.LoadScene();
} }
2.LoadingScene
這個場景包含的主要元素是:背景、Logo、齒輪(含旋轉的動畫),進度條。
載入遊戲用到了非同步載入技術,在LoadScene物體上掛載指令碼LoadScene.cs。
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections.Generic;
public class LoadScene : MonoBehaviour
{
public Slider progressBar;
//當前載入進度
private float currentProgress = ;
//目標載入進度
private float targetProgress = ; private void Start()
{
//啟動協程
StartCoroutine("LoadingScene");
} private IEnumerator LoadingScene()
{
//非同步載入
AsyncOperation asyncOp = SceneManager.LoadSceneAsync();
//沒有載入完畢時
while (asyncOp.progress < 0.9f)
{
Debug.Log("正在瘋狂載入中...");
currentProgress = asyncOp.progress;
yield return UpdateProgressBarValue();
}
currentProgress = 1f;
yield break;
} private IEnumerator<WaitForEndOfFrame> UpdateProgressBarValue()
{
while (targetProgress < currentProgress)
{
Debug.Log("正在更新進度...");
targetProgress += 0.01f;
progressBar.value = targetProgress;
yield return new WaitForEndOfFrame();
}
yield break;
} }
3.MainScene
這個場景元素比較多,分為七大塊。Main, PersonalInfo,Action,TAsk,Install,Explain
今天完成的邏輯比較簡單,就是點選頭像打開個人中心面板及其關閉邏輯。程式碼如下:Person
PersonalController.cs負責個人中心面板邏輯,MainSceneController負責整個場景遊戲邏輯。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainSceneController : MonoBehaviour
{
public Button headBtn;
public GameObject personalInfo; private void Start()
{
Init();
} private void Init()
{
headBtn.onClick.AddListener(OnHeadBtn);
}
private void OnHeadBtn()
{
personalInfo.SetActive(true);
} }
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PersonalController : MonoBehaviour
{
public InputField nameInput;
public InputField mottoInput;
public Button sureBtn;
public Button closeBtn; private void Start()
{
Init();
} private void Init()
{
sureBtn.onClick.AddListener(OnSureBtn);
closeBtn.onClick.AddListener(OnCloseBtn);
}
private void OnSureBtn()
{
PlayerPrefs.SetString("name", nameInput.text);
PlayerPrefs.SetString("motto", mottoInput.text);
OnCloseBtn();
} private void OnCloseBtn()
{
gameObject.SetActive(false);
}
}