gameObjects | 要复制的 GameObject 数组。 |
GameObject[] 复制的 GameObject 根节点数组。
复制一个 GameObject 数组并返回新 GameObject 根节点的数组。
在场景中复制 GameObjects。每个 GameObject 将与原始 GameObject 在层次结构中处于同一级别,并且它们将共享相同的父对象。如果原始 GameObject 存在任何子对象或组件,则副本也将拥有它们。如果父对象和子对象都添加到输入数组中,则仅复制并返回父对象(类似于编辑器中 Ctrl + D 的工作方式)。
要复制单个 GameObject,请使用 DuplicateGameObject。要复制资源,请使用 AssetDatabase.CopyAsset。
using UnityEngine; using UnityEditor;
public static class DuplicateGameObjectsExample { // Create context menu [MenuItem("Example/Duplicating GameObjects Example")] public static void DuplicatingGameObjectsExample() { // Creating the original GameObjects GameObject gameObject1 = new GameObject("gameObject1"); GameObject gameObject2 = new GameObject("gameObject2"); GameObject gameObject3 = new GameObject("gameObject3");
// Creating an array of all GameObjects GameObject[] gameObjectArray = { gameObject1, gameObject2, gameObject3 };
// Duplicating the array of GameObjects GameObject[] duplicatedGameObjectArray = GameObjectUtility.DuplicateGameObjects(gameObjectArray);
// Display the names of the duplicated GameObjects in the console Debug.Log("Duplicated GameObjects: "); for (int i = 0; i < duplicatedGameObjectArray.Length; i++) { Debug.Log(duplicatedGameObjectArray[i].name); } }
// Create context menu [MenuItem("Example/Duplicating Hierarchy Example")] public static void DuplicatingHierarchyExample() { // Creating the original GameObjects GameObject parent = new GameObject("parent"); GameObject child1 = new GameObject("child1"); GameObject child2 = new GameObject("child2");
// Assigning parents to children child1.transform.parent = parent.transform; child2.transform.parent = parent.transform;
// Creating an array of all GameObjects GameObject[] gameObjectArray = { parent, child1, child2 };
// Duplicating the array of GameObjects GameObject[] duplicatedGameObjectArray = GameObjectUtility.DuplicateGameObjects(gameObjectArray);
// Display the names of the duplicated GameObjects in the console // Only the parent will be returned Debug.Log("Duplicated GameObjects: "); for (int i = 0; i < duplicatedGameObjectArray.Length; i++) { Debug.Log(duplicatedGameObjectArray[i].name); } } }
复制操作产生的任何错误和警告都会在日志和控制台中报告。