Unity Development Diary - Logical Implementation of Enter Game Button and Exit Game Button

foreword

This article just summarizes the two implementation methods of the logic codes of entering and exiting the game in UGUI, which is convenient for future reference. If there are other methods in the future, it will be updated at any time (Unity version is 2021)

Method 1: Button call event

1. 首先在场景中创建空物体并挂上脚本

insert image description here

2. 脚本中的代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;      //跳转场景必备

public class uguiButton : MonoBehaviour
{
    
    
    // Start is called before the first frame update

    //开始游戏
    public void Open()
    {
    
    
        SceneManager.LoadScene(1);      //跳到1场景
    }

    //关闭游戏
    public void Close()
    {
    
    
        Application.Quit();
    }

    
}
3. 设置游戏的开始按键的事件,如下图(退出游戏也是一样的)

insert image description here

4.然后选择事件函数即可

insert image description here

Method 2: Directly use the monitoring function call

  1. The first is to mount the script on the Image (background image) of the UIinsert image description here
  2. code show as below
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEditor;

public class gamebutton : MonoBehaviour
{
    
    
    private Button startButton;
    private Button exitButton;
    private Button cgButton;

    // Start is called before the first frame update
    void Start()
    {
    
    
        startButton = transform.Find("start_game").GetComponent<Button>();
        exitButton = transform.Find("exit_game").GetComponent<Button>();
        startButton.onClick.AddListener(StartButtonClick);                      //监听函数
        exitButton.onClick.AddListener(ExitButtonClick);
    }
        // 开始游戏
    private void StartButtonClick()
    {
    
    
        SceneManager.LoadScene(1);
    }

    //退出游戏(宏定义实现)
    private void ExitButtonClick()
    {
    
    
#if UNITY_EDITOR        //Unity编辑器中调试使用
        EditorApplication.isPlaying = false;
#else                   //导出游戏包后使用
        Application.Quit();
#endif
    }

Summarize

  1. Both approaches have their advantages. Method 1 has a small amount of code, but it is more troublesome to manage when the project is large; method 2 has a little more code, but it is quite easy to manage. After all, only one script is needed to be placed under the parent object of the background.

Guess you like

Origin blog.csdn.net/m0_52058484/article/details/127621771