unity主场景设置、场景切换、全屏设置、背景音乐设置(场景一加载就开始播放)

主场景设置

最简单的方法

一般情况下我们的场景会有挺多的,这时候我们进入游戏就会有问题了,unity应该先加载哪一个呢?
unity给了我们几种方案,其中一种是在文件——生成设置里面更改游戏场景的优先级,其中0是最高优先级(当然,必须得先把场景全都加进build中,要不如果你在外部跳转没有build的场景是会报错的)。
在这里插入图片描述

第二种方法

通过脚本的方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;//场景头部引入

public class ChageScene : MonoBehaviour
{
    
    
    [RuntimeInitializeOnLoadMethod]
    static void Initialize()
    {
    
    
        string startSceneName = "GameScene";
        Scene scene = SceneManager.GetActiveScene();
        if (scene.name.Equals(startSceneName))
        {
    
    
            return;
        }
        SceneManager.LoadScene(startSceneName);
    }

    
}

该脚本不需要挂在任何物体中,其游戏一加载就会编译该 [RuntimeInitializeOnLoadMethod]函数

场景切换

在挂在按钮的脚本里加上以下代码且按下监听那里加上即可跳转场景

    public void ClickTollGame(){
    
    
        /* gameObject.SetActive(true); */
        SceneManager.LoadScene("GameScene");  //另一个场景名叫GameScene
    }

在这里插入图片描述

全屏设置

全屏设置也同样是写在一个不用挂在任何物体的脚本里

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FullScreen : MonoBehaviour {
    
    
    private void Awake()
    {
    
    
        //获取设置当前屏幕分辩率 
        Resolution[] resolutions = Screen.resolutions;
        //设置当前分辨率 
        Screen.SetResolution(resolutions[resolutions.Length - 1].width, resolutions[resolutions.Length - 1].height, true);

        Screen.fullScreen = true;  //设置成全屏
      
    }
}

最后是背景音乐

其功能有:
1、场景加载完成就开始播放
2、具有暂停和播放功能(需要挂在按钮上)
先放代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class music : MonoBehaviour
{
    
    
    public AudioSource audi;  //相当于定义一个音频?

    void Start()
    {
    
    
        audi = GetComponent<AudioSource>(); //获取音频
        audi.Play();     //播放
//        Debug.Log("111");
    }

    public void estimateMusic () {
    
    
        if (audi.isPlaying)//正在播放背景音乐时
        {
    
    
            //audi.enabled = false;
            audi.Pause();
        }
        else//未播放背景音乐时
        {
    
    
            //audi.enabled = true;
            audi.Play();
        }

    }

}

在这里插入图片描述
挂在一个button上,当button被触发则运行
在这里插入图片描述
在这个button里加一个Audio Source的组件,放入音乐,这样脚本里才能获取得到音频
最后一个提示是,挂载音乐的按钮得是激活状态(显示状态),要不不会加载音乐,如果想要不显示这个按钮则可以将其颜色改成透明。

猜你喜欢

转载自blog.csdn.net/qq_19829077/article/details/130427433