Unity Editor中打开场景获取GameObject
程序员文章站
2022-04-02 20:18:56
编辑器工具开发中,有时需要找到场景中的物体。下面介绍用代码在Editor中寻找指定场景中的GameObject如上图,在三个场景中分别有一些GameObject,现在随机打卡一个场景,然后再当前场景中找其他场景中的GameObject代码如下:using UnityEngine;using UnityEditor;using System.IO;using UnityEditor.SceneManagement;using UnityEngine.SceneManagement;publ...
编辑器工具开发中,有时需要找到场景中的物体。下面介绍用代码在Editor中寻找指定场景中的GameObject
如上图,在三个场景中分别有一些GameObject,现在随机打卡一个场景,然后再当前场景中找其他场景中的GameObject
代码如下:
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
public class ForeachObjectsInEditor {
[MenuItem("Tools/ForeachObjectsInEditor")]
public static void ForeachObjects(){
string[] sceneArr = {
"ForeachObjsScene1",
"ForeachObjsScene2",
"ForeachObjsScene3",
};
string sceneRootPath = "Assets\\ForeachObjectsInEditor";
for (int i = 0; i < sceneArr.Length; i++)
{
string sceneName = sceneArr[i];
string fullPath = Path.Combine(sceneRootPath, sceneName) + ".unity";
Scene scene = EditorSceneManager.OpenScene(fullPath, OpenSceneMode.Additive);
GameObject[] objects = scene.GetRootGameObjects();
Debug.Log("<color=red>======================================</color>");
for (int j = 0; j < objects.Length; j++)
{
Debug.LogFormat("<color=yellow>Scene : {0}, GameObject : {1}</color>", sceneName, objects[j].name);
}
EditorSceneManager.CloseScene(scene, true);
}
}
}
运行效果如下:
其中需要注意的是:
1. OpenSceneMode
Scene scene = EditorSceneManager.OpenScene(fullPath, OpenSceneMode.Additive);
OpenSceneModed有三种:
public enum OpenSceneMode
{
//
// 摘要:
// Closes all current open scenes and loads a scene.
Single = 0,
//
// 摘要:
// Adds a scene to the current open scenes and loads it.
Additive = 1,
//
// 摘要:
// Adds a scene to the current open scenes without loading it. It will show up as
// 'unloaded' in the Hierarchy Window.
AdditiveWithoutLoading = 2
}
2. Close时候的第二个参数
EditorSceneManager.CloseScene(scene, true);
// true:关闭后删除
// false:关闭后不删除
设置为false后的效果如下:
本文地址:https://blog.csdn.net/YuAnHandSome/article/details/107617623