Application类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ApplicationTest : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//游戏数据文件夹路径 只读、加密压缩Debug.Log(Application.dataPath); //D:/UnityProject/Life/AssetsDebug.Log(Application.dataPath + "txtTest.txt"); //D:/UnityProject/Life/Assets/txtTest.txt//持久化文件路径Debug.Log(Application.persistentDataPath);//C:/Users/l1/AppData/LocalLow/DefaultCompany/Life//streamingAssetsPath文件夹路径 只读、不加密、配置文件Debug.Log(Application.streamingAssetsPath);//D:/UnityProject/Life/Assets/StreamingAssets//临时文件夹Debug.Log(Application.temporaryCachePath);//C:/Users/l1/AppData/Local/Temp/DefaultCompany/Life//控制是否在后台运行Application.runInBackground = false;Debug.Log(Application.runInBackground);//false//打开urlApplication.OpenURL("www.baidu.com");//退出游戏Application.Quit();}// Update is called once per framevoid Update(){}
}
场景的加载
一个游戏的组成
默认创建的项目,游戏物体在SampleScene下,可以在Assests/Scenes/下再创建新的场景。
如果你的场景需要在游戏中使用,可以在文件/生成设置…/Build中的场景中将要使用的场景添加进去,此时每个场景会有一个索引。
可以通过代码从SampleScene场景自动加载到自己创建的场景MyScene中。
/场景类 场景管理类 需要导入命名空间UnityEngine.SceneManagement;//获取当前场景Scene scene = SceneManager.GetActiveScene();//场景名称Debug.Log(scene.name);//场景是否已经被加载Debug.Log(scene.isLoaded);//场景路径Debug.Log(scene.path);//场景索引Debug.Log(scene.buildIndex);//得到该场景所有的游戏物体 返回一个数组GameObject[] gos = scene.GetRootGameObjects();Debug.Log(gos.Length);//场景管理类//创建新场景Scene newScene = SceneManager.CreateScene("newScene");Debug.Log(SceneManager.sceneCount); //当前激活的场景数量//卸载场景SceneManager.UnloadSceneAsync(newScene);//场景跳转 加载场景//SceneManager.LoadScene(1); // 或通过名称SceneManager.LoadScene("MyScene");SceneManager.LoadScene(1, LoadSceneMode.Single);//第二个参数:加载方式 Sigle替换(原本的场景消失) Additive添加
异步加载场景
通过协程的方式实现异步加载:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;public class SceneTest : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){//协程异步加载StartCoroutine(loadScene());}AsyncOperation operation;//协程方法用来加载异步场景IEnumerator loadScene(){operation = SceneManager.LoadSceneAsync(1);operation.allowSceneActivation = false;// 此时可以在按键后将它置为true实现跳转yield return operation;}// Update is called once per framevoid Update(){//输出加载进度Debug.Log(operation.progress);}
}