[英]How can I sort the loop to debug.log the gameobjects according to the scenes order in the hierarchy?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class CompareObjects : MonoBehaviour
{
private GameObject[] allObjects;
private void Start()
{
allObjects = FindObjectsOfType<GameObject>();
foreach (GameObject go in allObjects)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
}
}
}
Now it's starting with objects from the second scene I added for testing then loop over the objects sometimes in the middle of the first scene then back to the second.现在它从我添加用于测试的第二个场景中的对象开始,然后有时在第一个场景的中间循环对象,然后返回到第二个。
Instead I want that it always will loop the top scene objects in the hierarchy and the next scene to the bottom.相反,我希望它始终将层次结构中的顶部场景对象和下一个场景循环到底部。
If the hierarchy is like this:如果层次结构是这样的:
Scene 1
GameObject t1
Scene 2
GameObject t2
Scene 3
GameObject t1
Then first loop t1 of Scene 1 then t2 and t1 of scene 3然后首先循环场景 1 的 t1,然后循环场景 3 的 t2 和 t1
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public static class EditorHelpers
{
[MenuItem("Tools/PrintHierarchy")]
public static void PrintHierarchy()
{
var scenes = Enumerable.Range(0, SceneManager.sceneCount)
.Select(SceneManager.GetSceneAt)
.Select(s => $"Scene {s.name}\n{GetSceneHierarchy(s.GetRootGameObjects())}")
.ToArray();
Debug.Log(string.Join("\n", scenes));
}
private static string GetSceneHierarchy(GameObject[] gameObjects)
{
var child = gameObjects.Select(g => GetChildHierarchyRecursively(g.transform)).ToArray();
return string.Join("\n", child);
}
private static string GetChildHierarchyRecursively(Transform parentTransform, string indent = " ")
{
var res = indent + parentTransform.name + "\n"
+ string.Join("\n",
Enumerable.Range(0, parentTransform.childCount)
.Select(i => GetChildHierarchyRecursively(parentTransform.GetChild(i), indent += " ")));
return res;
}
}
You can order the array using Linq's OrderBy
query.您可以使用 Linq 的
OrderBy
查询对数组进行排序。
You can then sort them by the scene index in your build settings, or the scene name, or whatever field/property available for the Scene class.然后,您可以按构建设置中的场景索引、场景名称或场景 class 可用的任何字段/属性对它们进行排序。
using System.Linq;
foreach (GameObject go in allObjects.OrderBy(x => x.scene.buildIndex)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
}
Alternatively you can group them by scene或者,您可以按场景对它们进行分组
foreach (var scene_objects in allObjects.GroupBy(x => x.scene))
{
Debug.Log("Scene: " + scene_objects.Key.name);
foreach (GameObject go in scene_objects)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.