private static void MoveGameObjectsToScene(IEnumerable <GameObject> addedObjects, Scene scene) { foreach (var obj in addedObjects) { EditorSceneManager.MoveGameObjectToScene(obj, scene); } }
/// <summary> /// Saves the scenes. /// </summary> void SaveScenes() { foreach (var layer in currentCollections) { foreach (var item in loadedScenes) { if (item.name.StartsWith(layer.prefixScene) && item.isLoaded) { if (GameObject.Find(item.name) == null) { GameObject split = new GameObject(item.name); SceneSplitManager sceneSplitManager = split.AddComponent <SceneSplitManager> (); sceneSplitManager.sceneName = split.name; sceneSplitManager.size = new Vector3(layer.xSize != 0 ? layer.xSize : 100, layer.ySize != 0 ? layer.ySize : 100, layer.zSize != 0 ? layer.zSize : 100); int posx; int posy; int posz; Streamer.SceneNameToPos(layer, item.name, out posx, out posy, out posz); posx *= layer.xSize; posy *= layer.ySize; posz *= layer.zSize; sceneSplitManager.position = GetSplitPosition(new Vector3(posx, posy, posz), layer); sceneSplitManager.color = layer.color; EditorSceneManager.MoveGameObjectToScene(split, item); } } } } EditorSceneManager.SaveModifiedScenesIfUserWantsTo(loadedScenes.ToArray()); }
static void SplitTerrainsIntoScenes(OpenWorldSettings openWorldSettings, Dictionary <Vector2Int, UnityEngine.Terrain> splitTerrains) { foreach (var grid in splitTerrains.Keys) { string scenePath = OpenWorldSettingsEditor.Grid2Scene(openWorldSettings, grid, 1, true); if (!string.IsNullOrEmpty(scenePath)) { Scene scene = EditorSceneManager.GetSceneByName(Path.GetFileNameWithoutExtension(scenePath)); bool wasOpen = scene.IsValid(); if (!wasOpen) { scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); } splitTerrains[grid].gameObject.AddComponent <TerrainChunk>(); EditorSceneManager.MoveGameObjectToScene(splitTerrains[grid].gameObject, scene); EditorSceneManager.SaveScene(scene, scenePath); if (!wasOpen) { EditorSceneManager.CloseScene(scene, true); } } else { Debug.LogError("Terrain at grid: " + grid + " is out of world scenes range... Keepign in Scene: " + EditorSceneManager.GetActiveScene().name); } } }
static private void Setup_SceneDescriptor() { var comps = Object.FindObjectsOfType(typeof(VRCSDK2.VRC_SceneDescriptor)); VRCSDK2.VRC_SceneDescriptor descriptor; switch (comps.Length) { case 0: Iwlog.Warn("VRC_SceneDescriptor not found. Create temporary"); var go = new GameObject("VRC_SceneDescriptor holder"); descriptor = go.AddComponent <VRCSDK2.VRC_SceneDescriptor>(); var scene = EditorSceneManager.GetActiveScene(); EditorSceneManager.MoveGameObjectToScene(go, scene); break; case 1: descriptor = (VRCSDK2.VRC_SceneDescriptor)comps[0]; break; default: Iwlog.Warn("Too many VRC_SceneDescriptor found."); descriptor = (VRCSDK2.VRC_SceneDescriptor)comps[0]; break; } LocalPlayerContext.SceneDescriptor = descriptor; }
static void CreateScenesFromObjects() { GameObject[] parent = Selection.gameObjects; if (parent.Length == 0) { Debug.Log("<color=red>Nothing selected!!!</color>"); } else { foreach (var item in parent) { item.transform.parent = null; Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.MoveGameObjectToScene(item, newScene); string path = string.Format("{0}{1}.unity", PATH_SCENES, item.name); if (EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), path)) { Debug.Log(string.Format("Saving scene <color=blue>{0}</color>", item.name)); } } Debug.Log(string.Format("<color=green>{0}</color> Scenes exported succesfully", parent.Length.ToString())); } }
static void OnCompilationStart(string obj) { var scene = EditorSceneManager.GetSceneByName(string.Empty); AudioSource audioSource = null; if (scene.isLoaded) { audioSource = FindAudioSource(scene); } else { scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); } if (audioSource == null) { audioSource = new GameObject(AudioSourceName).AddComponent <AudioSource>(); EditorSceneManager.MoveGameObjectToScene(audioSource.gameObject, scene); } if (audioSource.isPlaying) { } else { var clip = GetResource <AudioClip>(ScriptName + " Loop"); audioSource.clip = clip; audioSource.loop = true; audioSource.Play(); } }
public void EditStart() { var exsitScene = SceneManager.GetSceneByName(ViewSystemEditScene); if (exsitScene != null) { EditEnd(); } newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); newScene.name = ViewSystemEditScene; //建立 UI Hierarchy 環境 if (!string.IsNullOrEmpty(data.globalSetting.ViewControllerObjectPath)) { var go = new GameObject(data.globalSetting.ViewControllerObjectPath); EditorSceneManager.MoveGameObjectToScene(go, newScene); ViewControllerTransform = go.transform; } GameObject ui_root = null; if (data.globalSetting.UIRoot != null && data.globalSetting.UIRootScene == null) { //Always generate a new one to avoid version conflict. #if UNITY_2019_1_OR_NEWER ui_root = PrefabUtility.InstantiatePrefab(data.globalSetting.UIRoot, ViewControllerTransform) as GameObject; #else ui_root = PrefabUtility.InstantiatePrefab(data.globalSetting.UIRoot); ((GameObject)ui_root).transform.SetParent(ViewControllerTransform); #endif data.globalSetting.UIRootScene = ui_root; PrefabUtility.UnpackPrefabInstance(data.globalSetting.UIRootScene, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction); } }
public static QObjectList createObjectListInScene(Scene scene) { QObjectList objectList; if (!objectListDictionary.ContainsKey(scene)) { GameObject gameObjectList = new GameObject(); gameObjectList.name = ObjectListName; if (scene != gameObjectList.scene) { EditorSceneManager.MoveGameObjectToScene(gameObjectList, scene); } objectList = gameObjectList.AddComponent <QObjectList>(); objectListDictionary.Add(scene, objectList); } else { objectList = objectListDictionary[scene]; } objectList.tag = null; MonoScript monoScript = MonoScript.FromMonoBehaviour(objectList); if (MonoImporter.GetExecutionOrder(monoScript) != -10000) { MonoImporter.SetExecutionOrder(monoScript, -10000); } return(objectList); }
protected override void OnUpdate() { Entities.WithNone <EditorCompanionInPreviewSceneTag>().ForEach((EditorRenderData renderData, CompanionLink link) => { foreach (var sceneAndMask in m_CompanionScenes) { if (sceneAndMask.mask == renderData.SceneCullingMask) { EditorSceneManager.MoveGameObjectToScene(link.Companion, sceneAndMask.scene); return; } } var scene = EditorSceneManager.NewPreviewScene(); m_CompanionScenes.Add(new SceneAndMask { scene = scene, mask = renderData.SceneCullingMask }); EditorSceneManager.SetSceneCullingMask(scene, renderData.SceneCullingMask); EditorSceneManager.MoveGameObjectToScene(link.Companion, scene); }); EntityManager.AddComponent <EditorCompanionInPreviewSceneTag>(m_WithoutTag); }
public static AudioSource CreateAudioSource(Scene scene) { var audioSource = new GameObject(AudioSourceName).AddComponent <AudioSource>(); EditorSceneManager.MoveGameObjectToScene(audioSource.gameObject, scene); return(audioSource); }
public void SetUp() { waypoints = new List <Waypoint>(); var systemObj = new GameObject(); waypointSystem = systemObj.AddComponent <WaypointSystem>(); EditorSceneManager.MoveGameObjectToScene(systemObj, editorScene); }
public static RenderTexture Render(GameObject gameObject, int resolution) { if (threePointLight == null) { threePointLight = Resources.Load <GameObject>("Prefabs/ThreePointLights"); } //calculate object bounds Bounds bounds = new Bounds(); foreach (MeshRenderer renderer in gameObject.GetComponentsInChildren <MeshRenderer>()) { bounds.Encapsulate(renderer.bounds); } var renderScene = EditorSceneManager.NewPreviewScene(); GameObject parent = new GameObject("Scene Parent"); GameObject instance = GameObjectFactory.Instantiate(gameObject, parent: parent.transform); GameObject cameraGameObject = GameObjectFactory.Create("Camera", parent: parent.transform); var camera = cameraGameObject.AddComponent <Camera>(); camera.clearFlags = CameraClearFlags.Nothing; camera.forceIntoRenderTexture = true; cameraGameObject.transform.position = bounds.center + Vector3.right + Vector3.forward + Vector3.up; cameraGameObject.transform.position *= Mathf.Max(bounds.extents.x, bounds.extents.y, bounds.extents.z) * 1.2f; cameraGameObject.transform.rotation = Quaternion.Euler(0, 225, 0) * Quaternion.Euler(45f, 0, 0); RenderTexture texture = new RenderTexture(resolution, resolution, 16); texture.Create(); camera.targetTexture = texture; camera.scene = renderScene; GameObject lightGameObject = GameObjectFactory.Instantiate(threePointLight, parent: parent.transform); var light = lightGameObject.AddComponent <Light>(); light.type = LightType.Directional; light.transform.rotation = Quaternion.Euler(50f, -30f, 0f); EditorSceneManager.MoveGameObjectToScene(parent, renderScene); camera.Render(); camera.targetTexture = null; GameObject.DestroyImmediate(parent); EditorSceneManager.UnloadSceneAsync(renderScene); return(texture); }
private Scene GetTempScene() { if (_tempScene == null) { _tempScene = EditorSceneManager.NewPreviewScene(); var root = new GameObject("VideoPlayer"); EditorSceneManager.MoveGameObjectToScene(root, _tempScene); } return(_tempScene); }
private Waypoint CreateWaypoint(Vector2 position) { var waypoint = new GameObject(); EditorSceneManager.MoveGameObjectToScene(waypoint, editorScene); waypoint.transform.position = position; var waypointComponent = waypoint.AddComponent <Waypoint>(); waypoints.Add(waypointComponent); return(waypointComponent); }
private void Save() { dirty = false; note.text = text; if (text.Length == 0 && !isNew) { Delete(); return; } if (!inScene) { if (isNew) { isNew = false; EditorNotes.Settings.notes.Add(note); EditorNotes.Settings.UpdateCache(); EditorApplication.RepaintProjectWindow(); } EditorUtility.SetDirty(EditorNotes.Settings); } else { if (container == null) { GameObject go = new GameObject(EditorNotes.NotesContainerObjName) { tag = "EditorOnly", hideFlags = HideFlags.HideInHierarchy }; container = go.AddComponent <NotesContainer>(); if (go.scene != targetGO.scene) { EditorSceneManager.MoveGameObjectToScene(go, targetGO.scene); } EditorNotes.UpdateSceneCache(); } if (isNew) { isNew = false; container.notes.Add(note); container.UpdateCache(); EditorApplication.RepaintHierarchyWindow(); } EditorSceneManager.MarkSceneDirty(container.gameObject.scene); } }
/// <summary> /// 保存GamingMapArea /// </summary> /// <param name="area"></param> public void SaveGamingArea(GamingMapArea area) { if (area == null || area.gameObject == null) { return; } string areaName = area.GetAreaScenePath(); if (string.IsNullOrEmpty(areaName)) { if (!Application.isBatchMode) { EditorUtility.DisplayDialog("提示", "不存在Area场景", "确定"); } return; } string areaPath = areaName.Replace("Assets", Application.dataPath); Scene areaScene; if (!File.Exists(areaPath)) { areaScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); } else { areaScene = EditorSceneManager.OpenScene(areaName, OpenSceneMode.Additive); } if (areaScene != null) { GameObject[] rootObjs = areaScene.GetRootGameObjects(); if (rootObjs != null && rootObjs.Length > 0) { for (int rIndex = 0; rIndex < rootObjs.Length; rIndex++) { GameObject.DestroyImmediate(rootObjs[rIndex]); } } area.transform.SetParent(null); EditorSceneManager.MoveGameObjectToScene(area.gameObject, areaScene); SceneManager.SetActiveScene(areaScene); } EditorSceneManager.SaveScene(areaScene, areaName); EditorSceneManager.CloseScene(areaScene, true); if (area != null && area.gameObject != null) { GameObject.DestroyImmediate(area.gameObject); } }
//////////////////////////////////////////////////////////// static private GameObject SpawnFromPrefab(string path) { var prefab = Resources.Load <GameObject>(path); if (prefab == null) { Iwlog.Error("Prefab not found. path='" + path + "'"); return(null); } var instance = Object.Instantiate(prefab); var scene = EditorSceneManager.GetActiveScene(); EditorSceneManager.MoveGameObjectToScene(instance, scene); return(instance); }
public QObjectList getObjectList(GameObject gameObject, bool createIfNotExist = true) { QObjectList objectList = null; objectListDictionary.TryGetValue(gameObject.scene, out objectList); if (objectList == null && createIfNotExist) { objectList = createObjectList(gameObject); if (gameObject.scene != objectList.gameObject.scene) { EditorSceneManager.MoveGameObjectToScene(objectList.gameObject, gameObject.scene); } objectListDictionary.Add(gameObject.scene, objectList); } return(objectList); }
private static void UpdateSceneIndex(Scene scene) { //Find SceneIndexer and update its caches list SceneIndexer indexer = SceneUtils.FindInScene <SceneIndexer>(scene); //Create a new one if one doesn't exist if (indexer == null) { GameObject newObj = new GameObject("SceneIndexer"); EditorSceneManager.MoveGameObjectToScene(newObj, scene); indexer = newObj.AddComponent <SceneIndexer>(); } indexer.CacheSceneObjects(); //Hack, save string on save scene Localisation.SaveStrings(); }
//Camera public virtual void CreateCamera(Scene scene) { //Camera Parent GameObject camParent = new GameObject(); EditorSceneManager.MoveGameObjectToScene(camParent, scene); camParent.hideFlags = HideFlags.HideAndDontSave; camParent.transform.position = Vector3.zero; camParent.transform.position += Vector3.up * terrainSegments * segmentSize * 0.9f; camParent.transform.rotation = Quaternion.Euler(90, 0, 0); camParent.transform.RotateAround(Vector3.zero, camParent.transform.right, -90); GameObject camGO = new GameObject(); camera = camGO.AddComponent <Camera>(); EditorSceneManager.MoveGameObjectToScene(camGO, scene); camGO.transform.parent = camParent.transform; camera.scene = scene; camera.clearFlags = CameraClearFlags.Color; camera.backgroundColor = Color.black; camGO.hideFlags = HideFlags.HideAndDontSave; //Move and rotate Camera camera.transform.localPosition = Vector3.zero; camera.transform.rotation = camParent.transform.rotation; camera.transform.RotateAround(Vector3.zero, camParent.transform.right, 90); camera.targetTexture = renderTexture; camera.farClipPlane = 10000; camera.orthographicSize = terrainSegments * segmentSize / 1.9f; //Set starting transforms camParentStartPosition = camParent.transform.position; camParentStartRotation = camParent.transform.rotation; camStartPosition = camera.transform.position; camStartRotation = camera.transform.rotation; camera.orthographic = true; //starting 2d top down view }
private static void SaveTrunksAsScenes(string sceneName, SceneTrunkMgr sceneTrunkMgr, List <TerrainTrunk> trunks) { string sceneSubDir = string.Format("Assets/Scenes/{0}_Trunks", sceneName); if (System.IO.Directory.Exists(sceneSubDir)) { System.IO.Directory.Delete(sceneSubDir, true); } System.IO.Directory.CreateDirectory(sceneSubDir); for (int i = 0; i < trunks.Count; i++) { var trunk = trunks[i]; string trunkSceneName = string.Format("{0}_{1}_{2}", sceneName, trunk.xIndex, trunk.zIndex); string trunkScenePath = string.Format("{0}/{1}.unity", sceneSubDir, trunkSceneName); var trunkScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.SetActiveScene(trunkScene); trunk.terrian.transform.parent = null; EditorSceneManager.MoveGameObjectToScene(trunk.terrian.gameObject, trunkScene); EditorSceneManager.SaveScene(trunkScene, trunkScenePath); EditorSceneManager.CloseScene(trunkScene, true); var trunkAsset = AssetImporter.GetAtPath(trunkScenePath); var trunkName = string.Format("trunk_{0}_{1}.bundle", trunk.xIndex, trunk.zIndex); trunkAsset.assetBundleName = string.Format("scenes/{0}/{1}", sceneName, trunkName); sceneTrunkMgr.entries[i] = new SceneTrunkDataEntry() { x = trunk.xIndex, z = trunk.zIndex, trunkBundlePath = trunkAsset.assetBundleName, trunkName = trunkSceneName, }; } }
public static void EnterPreviewMode(GameObject clone) { Scene originalScene = EditorSceneManager.GetActiveScene(); originalScenePath = EditorApplication.currentScene; Scene previewScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive); EditorSceneManager.MoveGameObjectToScene(clone, previewScene); EditorSceneManager.UnloadSceneAsync(originalScene); previewModeEnable = true; inspectedGrabbable = GameObject.FindObjectOfType <VR_Grabbable>(); activeController = GameObject.FindObjectOfType <VR_Controller>(); OverrideGrabAnimation(); activeController.Animator.SetBool("IsGrabbing", true); EditorApplication.update += Update; }
//Called when MainWindow is opened public void CreateScene() { //Scene scene = EditorSceneManager.NewPreviewScene(); scene.name = "Noise Perspective"; //Culling mask ulong cullingMask = EditorSceneManager.CalculateAvailableSceneCullingMask(); EditorSceneManager.SetSceneCullingMask(scene, cullingMask); //Prevents running out of culling masks if editor is reopened several times //Light GameObject lightGo = new GameObject(); sceneLight = lightGo.AddComponent <Light>(); sceneLight.type = LightType.Directional; EditorSceneManager.MoveGameObjectToScene(lightGo, scene); lightGo.transform.position = lightGo.transform.up * 10; lightGo.transform.rotation = Quaternion.Euler(60, 0, 0); sceneLight.shadows = LightShadows.None; }
public void LoadInObjects(List <GameObject> objects, string tag, bool editMode) { SubsceneTag referenceTag = FindTagFromName(tag); if (referenceTag.loaded) { Scene s = SceneManager.GetSceneByName(referenceTag.sceneTagName + "_SubScene"); for (int i = 0; i < objects.Count; i++) { EditorSceneManager.MoveGameObjectToScene(objects[i], s); } EditorSceneManager.MarkAllScenesDirty(); } else { LoadScene(referenceTag, editMode); Debug.LogError("Needed to load scene, retry loading."); } }
void BuildScene(int x, int y, int lod, string directory) { string sceneName = x.ToString() + "_" + y.ToString() + "@LOD" + lod.ToString() + OpenWorld.openWorldSceneKey + "WorldScene"; Scene scene = EditorSceneManager.GetSceneByName(sceneName); bool wasOpen = scene.IsValid(); if (!wasOpen) { scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); GameObject g = new GameObject("Editor_CellDisplay"); g.AddComponent <CellGizmo>(); EditorSceneManager.MoveGameObjectToScene(g, scene); // PrefabUtility.InstantiatePrefab(openWorldSettings.cellDisplayPrefab, scene); } EditorSceneManager.SaveScene(scene, directory + sceneName + ".unity"); if (!wasOpen) { EditorSceneManager.CloseScene(scene, true); } }
//Terrain public virtual void CreateTerrain(Scene scene) { terrain = new GameObject(name + ": Terrains"); EditorSceneManager.MoveGameObjectToScene(terrain, scene); terrainDatas = new TerrainData[terrainSegments, terrainSegments]; //Create Terrain Segments for (int x = 0; x < terrainSegments; x++) { for (int y = 0; y < terrainSegments; y++) { TerrainData terrainData = new TerrainData(); terrainData.SetDetailResolution(detailResolution, 32); terrainData.heightmapResolution = heightResolution; terrainData.size = new Vector3(segmentSize, terrainHeight, segmentSize); terrainData.name = "TerrainData-" + x.ToString("D3") + "-" + y.ToString("D3"); GameObject terrainSegment = Terrain.CreateTerrainGameObject(terrainData); EditorSceneManager.MoveGameObjectToScene(terrainSegment, scene); terrainSegment.name = "Terrain-" + x.ToString("D3") + "-" + y.ToString("D3"); terrainSegment.transform.parent = terrain.transform; terrainSegment.transform.localPosition = new Vector3(x * segmentSize, 0, y * segmentSize); terrainDatas[x, y] = terrainData; //Destroy collider as not needed and can improve performance UnityEngine.Object.DestroyImmediate(terrainSegment.GetComponent <TerrainCollider>()); } } Terrain.SetConnectivityDirty(); terrain.transform.position = new Vector3((-segmentSize * terrainSegments) / 2, 0, (-segmentSize * terrainSegments) / 2); //Center Terrain //Set active during render and disabled again so each camera only renders its target terrain terrain.SetActive(false); }
public VisualElement CreateShelfElement() { VisualElement shelfButton = new VisualElement(); shelfButton.name = nameof(GroupSelection); shelfButton.StyleHeight(23); shelfButton.StyleJustifyContent(Justify.Center); Color c = EditorGUIUtility.isProSkin ? new Color32(32, 32, 32, 255) : new Color32(128, 128, 128, 255); shelfButton.StyleBorderColor(c); shelfButton.StyleBorderWidth(0, 0, 1, 0); // Image image = new Image(); // image.StyleSize(HierarchyEditor.GLOBAL_SPACE_OFFSET_LEFT, 16); // image.scaleMode = ScaleMode.ScaleToFit; // string path = string.Format("Assets/Duy Assets/Hierarchy 2/Editor/Icons/{0}", EditorGUIUtility.isProSkin ? "d_GroupSelectionIcon.png" : "GroupSelectionIcon.png"); // image.image = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; // shelfButton.Add(image); shelfButton.Add(new Label("Group Selections")); VerticalLayout menuOptions = new VerticalLayout(); menuOptions.StylePosition(Position.Absolute); menuOptions.StyleTop(-1); menuOptions.StyleWidth(128); menuOptions.StyleBackgroundColor(backgroundColor); menuOptions.StyleMarginLeft(-1); menuOptions.StyleBorderWidth(1, 1, 1, 1); menuOptions.StyleBorderRadius(0, 0, 0, 0); menuOptions.StyleBorderColor(borderColor); menuOptions.StyleDisplay(false); shelfButton.Add(menuOptions); Label option1 = new Label("Same parent (Offset)"); option1.StyleHeight(21); option1.StylePadding(4, 4, 0, 0); option1.StyleTextAlign(TextAnchor.MiddleLeft); option1.RegisterCallback <MouseEnterEvent>((evt) => { option1.StyleBackgroundColor(new Color(.5f, .5f, .5f, .5f)); }); option1.RegisterCallback <MouseLeaveEvent>((evt) => { option1.StyleBackgroundColor(Color.clear); }); option1.RegisterCallback <MouseDownEvent>((evt) => { if (Selection.gameObjects.Length > 0) { if (IsSelectionsSameScene()) { if (IsSelectionsSameParent()) { var scene = Selection.activeGameObject.scene; GameObject group = new GameObject(); group.name = "New Group"; Undo.RegisterCreatedObjectUndo(group, "Group Selection"); EditorSceneManager.MoveGameObjectToScene(group, scene); Vector3 offset = Vector3.zero; foreach (var go in Selection.gameObjects) { offset += go.transform.position; } group.transform.position = offset; group.transform.rotation = Quaternion.identity; group.transform.localScale = Vector3.one; group.transform.SetParent(Selection.activeTransform.parent); foreach (var go in Selection.gameObjects) { Undo.SetTransformParent(go.transform, group.transform, "Group Selection"); } Selection.activeGameObject = group; } else { Debug.LogWarning("Can't group selections different parent, use global instead."); } } else { Debug.LogWarning("Can't group selections from multiple scene."); } } shelfButton.parent.StyleDisplay(false); evt.StopPropagation(); }); menuOptions.Add(option1); Label option2 = new Label("Global (Offset)"); option2.StyleHeight(21); option2.StylePadding(4, 4, 0, 0); option2.StyleTextAlign(TextAnchor.MiddleLeft); option2.RegisterCallback <MouseEnterEvent>((evt) => { option2.StyleBackgroundColor(new Color(.5f, .5f, .5f, .5f)); }); option2.RegisterCallback <MouseLeaveEvent>((evt) => { option2.StyleBackgroundColor(Color.clear); }); option2.RegisterCallback <MouseDownEvent>((evt) => { if (Selection.gameObjects.Length > 0) { if (IsSelectionsSameScene()) { var scene = Selection.activeGameObject.scene; GameObject group = new GameObject(); group.name = "New Group"; Undo.RegisterCreatedObjectUndo(group, "Group Selection"); EditorSceneManager.MoveGameObjectToScene(group, scene); Vector3 offset = Vector3.zero; foreach (var go in Selection.gameObjects) { offset += go.transform.position; } group.transform.position = offset; group.transform.rotation = Quaternion.identity; group.transform.localScale = Vector3.one; foreach (var go in Selection.gameObjects) { Undo.SetTransformParent(go.transform, group.transform, "Group Selection"); } Selection.activeGameObject = group; } else { Debug.LogWarning("Can't group selections from multiple scene."); } } shelfButton.parent.StyleDisplay(false); evt.StopPropagation(); }); menuOptions.Add(option2); Label option3 = new Label("Global (Zero)"); option3.StyleHeight(21); option3.StylePadding(4, 4, 0, 0); option3.StyleTextAlign(TextAnchor.MiddleLeft); option3.RegisterCallback <MouseEnterEvent>((evt) => { option3.StyleBackgroundColor(new Color(.5f, .5f, .5f, .5f)); }); option3.RegisterCallback <MouseLeaveEvent>((evt) => { option3.StyleBackgroundColor(Color.clear); }); option3.RegisterCallback <MouseDownEvent>((evt) => { if (Selection.gameObjects.Length > 0) { if (IsSelectionsSameScene()) { var scene = Selection.activeGameObject.scene; GameObject group = new GameObject(); group.name = "New Group"; Undo.RegisterCreatedObjectUndo(group, "Group Selection"); EditorSceneManager.MoveGameObjectToScene(group, scene); group.transform.position = Vector3.zero; group.transform.rotation = Quaternion.identity; group.transform.localScale = Vector3.one; foreach (var go in Selection.gameObjects) { Undo.SetTransformParent(go.transform, group.transform, "Group Selection"); } Selection.activeGameObject = group; } else { Debug.LogWarning("Can't group selections from multiple scene."); } } shelfButton.parent.StyleDisplay(false); evt.StopPropagation(); }); menuOptions.Add(option3); shelfButton.RegisterCallback <MouseDownEvent>((evt) => { evt.StopPropagation(); }); shelfButton.RegisterCallback <MouseEnterEvent>((evt) => { shelfButton.StyleBackgroundColor(new Color(.5f, .5f, .5f, .5f)); menuOptions.StyleLeft(shelfButton.layout.width + 1); menuOptions.StyleDisplay(true); }); shelfButton.RegisterCallback <MouseLeaveEvent>((evt) => { shelfButton.StyleBackgroundColor(Color.clear); menuOptions.StyleDisplay(false); }); return(shelfButton); }
void LoadAllPackages(List <string> paths, bool isGameplayPackage, string targetProjectFolder, IResourceLocator resourceLocator) { PackageObject.ResetIDs(); var jobs = new PackageLoadJob[paths.Count]; for (var i = 0; i < paths.Count; i++) { jobs[i] = new PackageLoadJob(paths[i], targetProjectFolder, resourceLocator); } try { for (var i = 0; i < jobs.Length; i++) { if (EditorUtility.DisplayCancelableProgressBar("Creating Structures", string.Format("{0}/{1} - {2}", i, jobs.Length, jobs[i].PackageName), Mathf.Clamp01((float)i / jobs.Length) * 0.5f)) { if (EditorUtility.DisplayDialog("Cancel?", "temporary objects will not be cleaned up", "Yes", "No")) { throw new Exception("aborted"); } } jobs[i].LoadObjects(isGameplayPackage); } if (pauseForDebugger) { EditorUtility.DisplayDialog("", "Attach debugger now", "Ok"); } for (var i = 0; i < jobs.Length; i++) { if (EditorUtility.DisplayCancelableProgressBar("Importing Package Data", string.Format("{0}/{1} - {2}", i, jobs.Length, jobs[i].PackageName), 0.5f + Mathf.Clamp01((float)i / jobs.Length) * 0.5f)) { if (EditorUtility.DisplayDialog("Cancel?", "temporary objects will not be cleaned up", "Yes", "No")) { throw new Exception("aborted"); } } jobs[i].DeserializeObjectContent(); } if (!isGameplayPackage) { for (var i = 0; i < jobs.Length; i++) { EditorUtility.DisplayProgressBar("Creating Map files", string.Format("{0}/{1} - {2}", i, jobs.Length, jobs[i].PackageName), Mathf.Clamp01((float)i / jobs.Length)); var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); EditorSceneManager.MoveGameObjectToScene(jobs[i].Package.gameObject, scene); while (jobs[i].Package.transform.childCount > 0) { jobs[i].Package.transform.GetChild(0).parent = null; } GameObject.DestroyImmediate(jobs[i].Package.gameObject, false); EditorSceneManager.SaveScene(scene, string.Format("Assets/{0}/{1}.unity", targetProjectFolder, jobs[i].PackageName)); EditorSceneManager.CloseScene(scene, true); } } } catch (Exception e) { Debug.LogException(e); } finally { for (var i = 0; i < jobs.Length; i++) { jobs[i].Finish(); } EditorUtility.ClearProgressBar(); AssetDatabase.SaveAssets(); } }
public void LoadGamingMapArea(AreaSpawner areaSpawner, bool closeOtherArea = true) { if (areaSpawner == null) { return; } string m_AreaScenePath = string.Format("{0}/GamingMapArea_{1}_{2}.unity", GetOwnerAreaPath(), m_Uid, areaSpawner.GetAreaId()); if (string.IsNullOrEmpty(m_AreaScenePath)) { Debug.LogError("m_AreaScenePath == null"); return; } GamingMapArea[] areaArray = UnityEngine.Object.FindObjectsOfType <GamingMapArea>(); if (areaArray != null && areaArray.Length > 0) { for (int iArea = 0; iArea < areaArray.Length; iArea++) { GamingMapArea area = areaArray[iArea]; if (area != null && area.m_AreaId == areaSpawner.GetAreaId()) { //Debug.LogError(string.Format("{0}Area已导入", area.m_AreaId)); return; } } } if (closeOtherArea) { SaveOtherGamingArea(); } string areaScenePath = m_AreaScenePath.Replace("Assets", Application.dataPath); Scene areaScene; if (!File.Exists(areaScenePath)) { string gamingAreaPath = ""; GamingMapEditorSetting gamingSetting = GamingMapEditorUtility.GetGamingMapEditorSetting(); if (gamingSetting != null) { gamingAreaPath = gamingSetting.m_GamingAreaTemplete; } areaScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive); GameObject areaTempleteAsset = AssetDatabase.LoadAssetAtPath <GameObject>(gamingAreaPath); GameObject gamingArea = GameObject.Instantiate(areaTempleteAsset); GamingMapArea mapArea = gamingArea.GetComponent <GamingMapArea>(); mapArea.Init(areaSpawner, this); EditorSceneManager.MoveGameObjectToScene(gamingArea, areaScene); EditorSceneManager.SaveScene(areaScene, m_AreaScenePath); EditorSceneManager.CloseScene(areaScene, true); AssetDatabase.Refresh(); } areaScene = EditorSceneManager.OpenScene(m_AreaScenePath, OpenSceneMode.Additive); if (areaScene != null) { GamingMapArea mapArea = null; GameObject[] rootObjs = areaScene.GetRootGameObjects(); if (rootObjs != null && rootObjs.Length > 0) { for (int rIndex = 0; rIndex < rootObjs.Length; rIndex++) { mapArea = rootObjs[rIndex].GetComponent <GamingMapArea>(); if (mapArea != null) { break; } } } if (mapArea != null) { EditorSceneManager.MoveGameObjectToScene(mapArea.gameObject, GetOwnerScene()); mapArea.transform.SetParent(transform); } EditorSceneManager.CloseScene(areaScene, true); } }
public static void ReplaceArt(string src, string des, string srcSceneName, string desSceneName, List <string> replaceList, string tag) { //if (replaceList == null) //{ // return; //} Scene desScene = EditorSceneManager.OpenScene(desSceneName, OpenSceneMode.Additive); //打开拷贝的场景对象 Scene srcScene = EditorSceneManager.OpenScene(srcSceneName, OpenSceneMode.Additive);//被拷贝的场景对象 SceneManager.SetActiveScene(srcScene); //查到所有需要把被拷贝的被对象 GameObject obj = GameObject.Find(src);//查找到cutscene if (obj == null) { Debug.LogErrorFormat("{0} is not exit ", src); return; } //移动不保存 EditorSceneManager.MoveGameObjectToScene(obj, desScene); //整体移动到拼接场景 // EditorSceneManager.CloseScene(srcScene, true); // EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); //替换存在的剧本对象和路径对象 desScene = EditorSceneManager.OpenScene(desSceneName, OpenSceneMode.Additive); SceneManager.SetActiveScene(desScene); GameObject desObj = GameObject.Find(des);//找到path或者是cutscene if (desObj == null) { desObj = new GameObject(des); if (!string.IsNullOrEmpty(tag)) { desObj.gameObject.tag = tag; } Debug.LogWarningFormat("{0} is not exit {1} object", desScene.name, desObj.gameObject.name); } GameObject source = GameObject.Find(src);//找到pathart或者是cutsceneart if (source == null) { Debug.LogErrorFormat("{0} is not exit {1} object", desScene.name, src); return; } List <Transform> _SourceList = new List <Transform>(); //查找需要被替换场景的所有对象 for (int i = 0; i < source.transform.childCount; i++) { //获取需要被替换的对象名字 Transform child = source.transform.GetChild(i); child.gameObject.SetActive(true); if ((replaceList != null && ListContainItem(child.name, replaceList)) || replaceList == null) { //判断当前的对象是在需要替换场景的子节点中,是则删除 Transform temp = hasSameChild(desObj.transform, child.name); if (temp != null) { DestroyImmediate(temp.gameObject); } //美术制作的对象保留 _SourceList.Add(child); } } //拷贝source下的所有子对象到需要拼接场景的父节点 //while (source.transform.childCount > 0) for (int i = 0; i < _SourceList.Count; i++) { Transform child = _SourceList[i]; Transform temp = hasSameChild(desObj.transform, child.name); if (temp != null) { child.SetParent(desObj.transform); } else { if (child == null) { continue; } child.SetParent(desObj.transform); } } DestroyImmediate(source.gameObject); // EditorSceneManager.CloseScene(srcScene, false); _DirtyScene.Enqueue(srcScene); }