Related Posts Plugin for WordPress, Blogger...

6-13 Switching Login Window And Signup Window

今天要接著製作登入頁面跟註冊頁面的跳轉,註冊頁面的製作方式與前幾章介紹得差不多,請大家舉一反三自己做看看吧。不會做的話請參考以下兩章:
6-11 Decorating Login User Interface

6-12 Finishing Login User Interface

做完以後大致如下圖,登入畫面多了一顆按鈕,按下去後切換到註冊畫面。

然後註冊畫面也差不多,按下去會回到登入畫面。註冊畫面請根據自己的需求做調整,因為我的遊戲範例只用到帳號跟密碼兩種資料,不需要再輸入姓名等其它個資。

接著在Login Window新增一個Script名為LoginWindow.cs。

同理在Signup Window也新增一個SignupWindow.cs。

接著來撰寫程式吧,由於我過去已經針對視窗類型寫了一個共用類別Panel.cs,所以就直接繼承Panel便能使用他的Hide與Show方法。如果不知道Panel.cs寫了哪些內容,可以先參考這篇文章:
5-14 Discard Item And Control Panel Display
https://3dactionrpg.blogspot.tw/2018/01/5-14-discard-item-and-control-panel.html

不過我還是提供本次會用到的完整原始碼:
LoginWindow.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LoginWindow : Panel {

 [SerializeField] SignupWindow signupWindow;

 public void OnLoginButton(){
  
 }

 public void OnShowSignupButton(){
  this.Hide ();
  signupWindow.Show ();
 }
}


SignupWindow.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SignupWindow : Panel {

 [SerializeField] LoginWindow loginWindow;

 public void OnSignupButton(){
  
 }

 public void OnShowLoginButton(){
  this.Hide ();
  loginWindow.Show ();
 }
}


Panel.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Panel : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {

 [SerializeField] float panelAlpha = 1;
 [SerializeField] float smoothAlphaMultiplier = 4;
 [SerializeField] KeyCode hotKey;

 CanvasGroup canvasGroup;

 void Start () {
  canvasGroup = GetComponent ();
 }
 
 void Update () {
  if (Input.GetKeyDown (hotKey)) {
   DisplaySwitch ();
  }

  if (canvasGroup.alpha != panelAlpha) {
   // 用Lerp函數控制Alpha的漸變
   canvasGroup.alpha = Mathf.Lerp (canvasGroup.alpha, panelAlpha, Time.deltaTime * smoothAlphaMultiplier);
   if (Mathf.Abs (canvasGroup.alpha - panelAlpha) < 0.01f) {
    canvasGroup.alpha = panelAlpha;
   }
  }
 }

 public void Show(){
  canvasGroup.blocksRaycasts = true;
  panelAlpha = 1;
 }

 public void Hide(){
  canvasGroup.blocksRaycasts = false;
  panelAlpha = 0;
 }

 public void DisplaySwitch(){
  if (panelAlpha == 1) {
   Hide ();
  } else {
   Show ();
  }
 }

 public void OnBeginDrag(PointerEventData eventData){
 }

 public void OnDrag(PointerEventData eventData){
  // 將滑鼠座標轉換成Canvas上的座標
  Vector2 position;
  Canvas canvas = GetComponentInParent ();
  RectTransformUtility.ScreenPointToLocalPointInRectangle (
   canvas.transform as RectTransform,
   Input.mousePosition,
   null,
   out position);
  transform.localPosition = position;
 }

 public void OnEndDrag(PointerEventData eventData){
 }
}


撰寫好以後,請回到Login Window,將SignupWindow的物件放進框框中,並新增一個Canvas Group物件。

同樣,在SignupWindow中也這麼做。

接著在Signup Window的Button中,將Signup Window拉近On Click事件並選擇OnShowLoginButton,如下圖。

同理在Login Window的Button中,也選擇OnShowSignupButton事件。如此便完成兩個頁面切換的功能啦!




留言