当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Unity Editor中打开场景获取GameObject

Unity Editor中打开场景获取GameObject

2020年07月28日  | 移动技术网IT编程  | 我要评论

编辑器工具开发中,有时需要找到场景中的物体。下面介绍用代码在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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网