一、基本元素建立
1、建立3個Canvas,一個作為主要的,剩下一個是用來輸入使用者名和位址的,一個用來輸入伺服器IP
2、添加背景圖檔
先将2張背景圖檔轉換成精靈
Image添加圖檔
添加基本UI元素
在Canvas中添加登陸腳本,将腳本放到合适的位置
選擇你喜歡的編輯器,進行代碼編輯
添加4個函數
如果直接将腳本給按鈕,事件是無法調用的
需要先将腳本挂載到一個執行個體中,這裡将代碼就挂載到Canvas上,然後将Canvas附在On Click中
這樣就可以找到自己寫的函數了
找到想要調用的函數
以此類推,将4個函數挂載到4個按鈕上
編輯代碼,這裡需要在VS中移動代碼到Script目錄,這樣看起規整些,也可以不動
移動後的目錄
寫入如下代碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class longinScript : MonoBehaviour
{
public Canvas LoginCanvas;
public Canvas SettingCanvas;
public InputField Username;
public InputField Password;
public InputField IpAddr;
public InputField Port;
public Text LoginInfo;
public Text SettingInfo;
private string _ipAddr = "127.0.0.1";
private string _port = "7050";
private string _userName = "admin";
private string _password = "";
// Start is called before the first frame update
void Start()
{
Username.text = _userName;
LoginInfo.text = "";
SettingInfo.text = "";
}
// Update is called once per frame
void Update()
{
}
public void Login()
{
_userName = Username.text;
_password = Password.text;
LoginInfo.text = "登陸成功!";
Debug.Log($"userName:{_userName},password:{_password}");
}
public void Setting()
{
_ipAddr = IpAddr.text;
_port = Port.text;
SettingInfo.text = "設定成功!";
Debug.Log($"ipAddr:{_ipAddr},port:{_port}");
}
public void ToSettingView()
{
IpAddr.text = _ipAddr;
Port.text = _port;
SettingInfo.text = "";
LoginCanvas.gameObject.SetActive(false);
SettingCanvas.gameObject.SetActive(true);
}
public void ToLoginView()
{
LoginInfo.text = "";
LoginCanvas.gameObject.SetActive(true);
SettingCanvas.gameObject.SetActive(false);
}
}
指派
設定輸入框類型