Unity Editor中打开场景获取GameObject

本文介绍如何在Unity Editor中使用代码遍历并查找指定场景中的GameObject。通过示例代码,展示了如何打开多个场景,获取场景中的根游戏对象,并记录相关信息。同时,解释了OpenSceneMode枚举和CloseScene方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编辑器工具开发中,有时需要找到场景中的物体。下面介绍用代码在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后的效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值