Unity3D 小案例技巧05------UI登录+场景切换

编辑器使用Unity2021

1.创建UI---Canvas,修改名称为login

  设置Canvas的大小为1920*1080

        

 

2. 在login下创建UI----image   背景:bg

  给背景添加背景图,将图片先添加到Unity下的文件夹

  

 

   再点击图片,修改为2D+UI类型-----执行Apply

  

 

         

  最后,将图片拖入bg

  

3.在login下创建UI----Text    标题:title

  导入字体文件,再点击文件创建Create---->TextMeshPro---->Font Asset生成Unity支持的字体文件

  

 

   修改Text内容和字体文件

  

 

 4.在login下创建UI----Input Field   账号输入框:username

  修改提示内容

  

 

 5.在login下创建UI----Input Field   账号输入框:password

  修改提示内容

  

 

  6.在login下创建UI----Text 登录提示:reminderText

  隐藏显示,再修改字体文件

      

  6.在login下创建UI----Button 登录按钮:submit

  修改按钮颜色和内容

  

 

   

 

   7.创建脚本,添加到login下

  

 

   

 

 注意:将脚本使用的组件对象拖入到对应下

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Login : MonoBehaviour
{
    //进入前变量
    public TMP_InputField username, password;
    public TMP_Text reminderText;
    public int errorsNum;
    public Button loginButton;

    public void OnLogin()
    {
        Debug.Log(username.text+":"+ password.text);
        reminderText.gameObject.SetActive(true);
        if (username.text != "")
        {           
            if (password.text != "")
            {
                reminderText.text = "登录成功";
                //执行1秒
                new WaitForSeconds(2);
                Debug.Log("登录成功");
                SceneManager.LoadScene("index");
            }
            else
            {
                reminderText.text = "密码错误";
                errorsNum++;
                if (errorsNum >= 3)
                {
                    reminderText.text = "连续错误3次,请30秒后再试!";
                    loginButton.interactable = false;
                    Invoke("Recovery", 5);
                    errorsNum = 0;
                }
            }
        }
        else
        {
            reminderText.text = "账号不存在";
        }
    }
}

8.最后创建一个index场景,给场景随便添加个物体,再到File -----Bulid Setting下将2个场景添加

  

 

posted @ 2023-03-20 12:22  打工仔-也想飞  阅读(791)  评论(0)    收藏  举报