在Unity中更改JS脚本,以便更改场景

安东·尼尔森

我有正在使用的JavaScript代码,它在Unity游戏中提供了一个暂停菜单。这是一个简单的暂停菜单,显示“主菜单”和“退出游戏”按钮。

如何将按钮绑定到Unity中的场景?因此,如果我点击“主菜单”,我希望它带我进入scene1,然后用音乐按钮替换“退出游戏”按钮以打开/关闭我的音乐。

威尔·费舍尔

暂停菜单脚本:

#pragma strict
var musicBtnText : String = "Music: On";
var musicOn : boolean = true;
var isPaused : boolean = false;


function Update()
{
    if(musicOn)
    {
        musicBtnText = "Music: On";
    }
    else
    {
        musicBtnText = "Music: Off";
    }
    if(Input.GetKeyDown(KeyCode.P))
    {
        isPaused = !isPaused;
        if(isPaused)
        {
             Time.timeScale = 0;
        }
        else
        {
             Time.timeScale = 1;
        }
    }
}

function OnGUI()
{
    if(isPaused)
    {
        if (GUI.Button(Rect(Screen.width/2-50, 240, 100, 40), "Main Menu"))
        {
            Application.LoadLevel("scene1");
        }
        if(GUI.Button(Rect(Screen.width/2-50, 300, 100, 40), "" + musicBtnText))
        {
            musicOn = !musicOn;
            GameObject.Find("cameraName").GetComponent(AudioListener).enabled = !GameObject.Find("cameraName").GetComponent(AudioListener).enabled;
        }
    }
}

但是,如果要在自己的代码中实现此功能,则要注意的一件事是,当使按钮统一时,会将它们包含在if语句中。这样,只要单击该按钮,就会调用if语句中的所有代码。至于打开和关闭音乐,您需要启用和禁用主音频侦听器,默认情况下,该侦听器已连接到主摄像头。因此,在我的代码中说的是GameObject.Find("cameraName")用您的主摄像机名称替换摄像机名称。最后,通过调用来统一加载级别Application.LoadLevel("levelName")祝你好运!如果这给您带来任何错误,请发表评论,我们很乐意为您提供帮助。

在C#中:

using UnityEngine;
using System.Collections;

public class PauseMenu : MonoBehaviour {

    public string musicBtnText = "Music: On";
    public bool musicOn = true;
    public bool isPaused = false;


    void Update()
    {
        if(musicOn)
        {
            musicBtnText = "Music: On";
        }
        else
        {
            musicBtnText = "Music: Off";
        }
        if(Input.GetKeyDown(KeyCode.P))
        {
            isPaused = !isPaused;
            if(isPaused)
            {
                 Time.timeScale = 0;
            }
            else
            {
                 Time.timeScale = 1;
            }
        }
    }

    void OnGUI()
    {
        if(isPaused)
        {
            if (GUI.Button(new Rect(Screen.width/2-50, 240, 100, 40), "Main Menu"))
            {
                Application.LoadLevel("scene1");
            }
            if(GUI.Button(new Rect(Screen.width/2-50, 300, 100, 40), "" + musicBtnText))
            {
                musicOn = !musicOn;
                GameObject.Find("cameraName").GetComponent<AudioListener>().enabled = !GameObject.Find("cameraName").GetComponent<AudioListener>().enabled;
            }
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章