前言
本篇文章只是總結一下UGUI中進入游戲和退出游戲的邏輯代碼的兩種實現(xiàn)方式,方便以后查閱,以后如果有其他的方法也會隨時更新(Unity版本為2021)
方法一:Button調用事件
1. 首先在場景中創(chuàng)建空物體并掛上腳本
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. 設置游戲的開始按鍵的事件,如下圖(退出游戲也是一樣的)
文章來源:http://www.zghlxwxcb.cn/news/detail-505459.html
4.然后選擇事件函數(shù)即可
文章來源地址http://www.zghlxwxcb.cn/news/detail-505459.html
方法二:直接使用監(jiān)聽函數(shù)調用
- 首先是在UI的Image(背景圖)上掛載腳本
- 代碼如下
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); //監(jiān)聽函數(shù)
exitButton.onClick.AddListener(ExitButtonClick);
}
// 開始游戲
private void StartButtonClick()
{
SceneManager.LoadScene(1);
}
//退出游戲(宏定義實現(xiàn))
private void ExitButtonClick()
{
#if UNITY_EDITOR //Unity編輯器中調試使用
EditorApplication.isPlaying = false;
#else //導出游戲包后使用
Application.Quit();
#endif
}
總結
- 兩種方法各有各的好。方法一代碼量少但項目大的時候管理比較麻煩;方法二代碼量雖然多一點,但管理起來相當容易,畢竟只需要一個腳本放在背景這個父物體下就可以了
到了這里,關于Unity開發(fā)日記-進入游戲按鈕和退出游戲按鈕的邏輯實現(xiàn)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!