/// <summary> /// 是否包含<see cref="StaticEditorFlags"/> /// </summary> public static bool HasStaticEditorFlag(GameObject gameObject, StaticEditorFlags flag) { return((GameObjectUtility.GetStaticEditorFlags(gameObject) & flag) != 0); }
public static Transform[] CloneTargets(SetTransformation setTransform = null) { if (instance.filteredSelection.NodeTargets.Length == 0) { return(new Transform[0]); } var groupId = Undo.GetCurrentGroup(); //Undo.IncrementCurrentGroup(); var newTargets = new GameObject[instance.filteredSelection.NodeTargets.Length]; var newTransforms = new Transform[instance.filteredSelection.NodeTargets.Length]; for (int i = 0; i < instance.filteredSelection.NodeTargets.Length; i++) { var originalGameObject = instance.filteredSelection.NodeTargets[i].gameObject; var originalTransform = originalGameObject.GetComponent <Transform>(); newTargets[i] = CSGPrefabUtility.Instantiate(originalGameObject); var newTransform = newTargets[i].GetComponent <Transform>(); if (originalTransform.parent != null) { newTransform.SetParent(originalTransform.parent, false); newTransform.SetSiblingIndex(originalTransform.GetSiblingIndex() + 1); newTransform.name = GameObjectUtility.GetUniqueNameForSibling(originalTransform.parent, originalTransform.name); } if (setTransform == null) { newTransform.localScale = originalTransform.localScale; newTransform.localPosition = originalTransform.localPosition; newTransform.localRotation = originalTransform.localRotation; } else { setTransform(newTransform, originalTransform); } var childBrushes = newTargets[i].GetComponentsInChildren <CSGBrush>(); Dictionary <uint, uint> uniqueSmoothingGroups = new Dictionary <uint, uint>(); foreach (var childBrush in childBrushes) { for (int g = 0; g < childBrush.Shape.TexGens.Length; g++) { var smoothingGroup = childBrush.Shape.TexGens[g].SmoothingGroup; if (smoothingGroup == 0) { continue; } uint newSmoothingGroup; if (!uniqueSmoothingGroups.TryGetValue(smoothingGroup, out newSmoothingGroup)) { newSmoothingGroup = SurfaceUtility.FindUnusedSmoothingGroupIndex(); uniqueSmoothingGroups[smoothingGroup] = newSmoothingGroup; } childBrush.Shape.TexGens[g].SmoothingGroup = newSmoothingGroup; } } newTransforms[i] = newTransform; Undo.RegisterCreatedObjectUndo(newTargets[i], "Created clone of " + originalGameObject.name); } Selection.objects = newTargets; Undo.CollapseUndoOperations(groupId); return(newTransforms); }
static void Run() { Terrain terrain = Terrain.activeTerrain; if (terrain == null) { return; } CutsceneObjectHelper cutsceneObjectHelper = FindObjectOfType <CutsceneObjectHelper>(); Material[] flowerMats1 = cutsceneObjectHelper.flowerMats1; Material[] flowerMats2 = cutsceneObjectHelper.flowerMats2; TerrainData td = terrain.terrainData; CutsceneObjectsManager cutsceneObjectsManager = FindObjectOfType <CutsceneObjectsManager>(); Transform grassParent = cutsceneObjectsManager.transform.GetChild(0); Transform flowerParent = cutsceneObjectsManager.transform.GetChild(1); Transform treeParent = cutsceneObjectsManager.transform.GetChild(2); foreach (TreeInstance tree in td.treeInstances) { TreePrototype treeProt = td.treePrototypes[tree.prototypeIndex]; GameObject prefab = treeProt.prefab; if (prefab.name.Contains("Grass") && prefab.name.Contains("Cutscene")) { Vector3 pos = Vector3.Scale(tree.position, td.size) + terrain.transform.position; GameObject obj = GameObject.Instantiate(prefab, pos, Quaternion.AngleAxis(tree.rotation * Mathf.Rad2Deg, Vector3.up)) as GameObject; MeshRenderer[] renderers = obj.GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer renderer in renderers) { renderer.receiveShadows = false; //renderer.shadowCastingMode = ShadowCastingMode.TwoSided; GameObjectUtility.SetStaticEditorFlags(obj, StaticEditorFlags.ContributeGI); } Transform t = obj.transform; t.localScale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale); t.parent = grassParent.transform; if (Physics.Raycast(obj.transform.position + 30f * Vector3.up, Vector3.down, out RaycastHit hit, 50f, layerMask.value, QueryTriggerInteraction.Ignore)) { obj.transform.position = hit.point; obj.transform.up = hit.normal; } } else if (prefab.name.Contains("flower")) { Vector3 pos = Vector3.Scale(tree.position, td.size) + terrain.transform.position; GameObject obj = GameObject.Instantiate(prefab, pos, Quaternion.AngleAxis(tree.rotation * Mathf.Rad2Deg, Vector3.up)) as GameObject; MeshRenderer[] renderers = obj.GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer renderer in renderers) { renderer.receiveShadows = false; renderer.shadowCastingMode = ShadowCastingMode.TwoSided; GameObjectUtility.SetStaticEditorFlags(obj, StaticEditorFlags.ContributeGI); if (renderer.gameObject.name.Equals("Circle")) { renderer.material = flowerMats1[Random.Range(0, flowerMats1.Length)]; } else if (renderer.gameObject.name.Equals("Circle.001")) { renderer.sharedMaterials[1] = flowerMats2[Random.Range(0, flowerMats2.Length)]; } } Transform t = obj.transform; t.localScale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale); t.parent = flowerParent.transform; if (Physics.Raycast(t.position + 30f * Vector3.up, Vector3.down, out RaycastHit hit, 50f, layerMask.value, QueryTriggerInteraction.Ignore)) { t.position = hit.point; t.up = hit.normal; } } } }
private static void CreateSimpleScrollSnap() { // Canvas Canvas canvas = FindObjectOfType <Canvas>(); if (canvas == null) { GameObject canvasObject = new GameObject("Canvas"); canvas = canvasObject.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.gameObject.AddComponent <GraphicRaycaster>(); Undo.RegisterCreatedObjectUndo(canvasObject, "Create " + canvasObject.name); } // Scroll-Snap GameObject scrollSnap = new GameObject("Scroll-Snap"); RectTransform scrollSnapRectTransform = scrollSnap.AddComponent <RectTransform>(); scrollSnapRectTransform.sizeDelta = new Vector2(400, 250); ScrollRect scrollSnapScrollRect = scrollSnap.AddComponent <ScrollRect>(); scrollSnapScrollRect.horizontal = true; scrollSnapScrollRect.vertical = false; scrollSnapScrollRect.scrollSensitivity = 0f; scrollSnapScrollRect.decelerationRate = 0.01f; GameObjectUtility.SetParentAndAlign(scrollSnap, canvas.gameObject); scrollSnap.AddComponent <SimpleScrollSnap>(); // Viewport GameObject viewport = new GameObject("Viewport"); RectTransform viewportRectTransform = viewport.AddComponent <RectTransform>(); viewportRectTransform.anchorMin = new Vector2(0, 0); viewportRectTransform.anchorMax = new Vector2(1, 1); viewportRectTransform.offsetMin = Vector2.zero; viewportRectTransform.offsetMax = Vector2.zero; viewport.AddComponent <Mask>(); Image viewportImage = viewport.AddComponent <Image>(); viewportImage.color = new Color(1, 1, 1, 0.5f); scrollSnapScrollRect.viewport = viewportRectTransform; GameObjectUtility.SetParentAndAlign(viewport, scrollSnap.gameObject); // Content GameObject content = new GameObject("Content"); RectTransform contentRectTransform = content.AddComponent <RectTransform>(); contentRectTransform.sizeDelta = new Vector2(400, 250); contentRectTransform.anchorMin = new Vector2(0, 0.5f); contentRectTransform.anchorMax = new Vector2(0, 0.5f); contentRectTransform.pivot = new Vector2(0, 0.5f); scrollSnapScrollRect.content = contentRectTransform; GameObjectUtility.SetParentAndAlign(content, viewport.gameObject); GameObject[] panels = new GameObject[5]; for (int i = 0; i < 5; i++) { // Panel string name = (i + 1) + ""; panels[i] = new GameObject(name); RectTransform panelRectTransform = panels[i].AddComponent <RectTransform>(); panelRectTransform.anchorMin = Vector2.zero; panelRectTransform.anchorMax = Vector2.one; panelRectTransform.offsetMin = Vector2.zero; panelRectTransform.offsetMax = Vector2.zero; panels[i].AddComponent <Image>(); GameObjectUtility.SetParentAndAlign(panels[i], content.gameObject); // Text GameObject text = new GameObject("Text"); RectTransform textRectTransform = text.AddComponent <RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.offsetMin = Vector2.zero; textRectTransform.offsetMax = Vector2.zero; Text textText = text.AddComponent <Text>(); textText.text = name; textText.fontSize = 50; textText.alignment = TextAnchor.MiddleCenter; textText.color = Color.black; GameObjectUtility.SetParentAndAlign(text, panels[i]); } // Event System if (!FindObjectOfType <EventSystem>()) { GameObject eventObject = new GameObject("EventSystem", typeof(EventSystem)); eventObject.AddComponent <StandaloneInputModule>(); Undo.RegisterCreatedObjectUndo(eventObject, "Create " + eventObject.name); } // Editor Selection.activeGameObject = scrollSnap; Undo.RegisterCreatedObjectUndo(scrollSnap, "Create " + scrollSnap.name); }
// ----------------------------------------------------------------------------- // fix missing component // ----------------------------------------------------------------------------- private static bool FixMissingComponents(GameObjectIssueRecord issue, GameObject go, bool alternative) { var touched = false; #if UNITY_2019_1_OR_NEWER var removedCount = GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go); if (removedCount > 0) { touched = true; } #else if (!alternative) { CSObjectTools.SelectGameObject(go, issue.Location == RecordLocation.Scene); } var tracker = CSEditorTools.GetActiveEditorTrackerForSelectedObject(); if (tracker == null) { Debug.LogError(Maintainer.ConstructError("Can't get active tracker.")); return(false); } tracker.RebuildIfNecessary(); var activeEditors = tracker.activeEditors; for (var i = activeEditors.Length - 1; i >= 0; i--) { var editor = activeEditors[i]; if (editor.serializedObject.targetObject == null) { Object.DestroyImmediate(editor.target, true); touched = true; } } if (alternative) { return(touched); } if (!touched) { // missing script could be hidden with hide flags, so let's try select it directly and repeat var serializedObject = new SerializedObject(go); var componentsArray = serializedObject.FindProperty("m_Component"); if (componentsArray != null) { for (var i = componentsArray.arraySize - 1; i >= 0; i--) { var componentPair = componentsArray.GetArrayElementAtIndex(i); var nestedComponent = componentPair.FindPropertyRelative("component"); if (nestedComponent != null) { if (MissingReferenceDetector.IsPropertyHasMissingReference(nestedComponent)) { var instanceId = nestedComponent.objectReferenceInstanceIDValue; if (instanceId == 0) { var fileId = nestedComponent.FindPropertyRelative("m_FileID"); if (fileId != null) { instanceId = fileId.intValue; } } Selection.instanceIDs = new [] { instanceId }; touched |= FixMissingComponents(issue, go, true); } } else { Debug.LogError(Maintainer.LogPrefix + "Couldn't find component in component pair!"); break; } } if (touched) { CSObjectTools.SelectGameObject(go, issue.Location == RecordLocation.Scene); } } else { Debug.LogError(Maintainer.LogPrefix + "Couldn't find components array!"); } } #endif if (touched) { if (issue.Location == RecordLocation.Scene) { CSSceneTools.MarkSceneDirty(); } else { EditorUtility.SetDirty(go); } } return(touched); }
static void Drawer_BakeToolBar(SerializedProbeVolume serialized, Editor owner) { Bounds bounds = new Bounds(); bool foundABound = false; bool performFitting = false; bool performFittingOnlyOnSelection = false; bool ContributesToGI(Renderer renderer) { var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject) & StaticEditorFlags.ContributeGI; return((flags & StaticEditorFlags.ContributeGI) != 0); } void ExpandBounds(Bounds currBound) { if (!foundABound) { bounds = currBound; foundABound = true; } else { bounds.Encapsulate(currBound); } } if (GUILayout.Button(EditorGUIUtility.TrTextContent("Fit to Scene"), EditorStyles.miniButton)) { performFitting = true; } if (GUILayout.Button(EditorGUIUtility.TrTextContent("Fit to Selection"), EditorStyles.miniButton)) { performFitting = true; performFittingOnlyOnSelection = true; } if (performFitting) { if (performFittingOnlyOnSelection) { var transforms = Selection.transforms; foreach (var transform in transforms) { var childrens = transform.gameObject.GetComponentsInChildren <Transform>(); foreach (var children in childrens) { Renderer childRenderer; if (children.gameObject.TryGetComponent <Renderer>(out childRenderer)) { bool childContributeGI = ContributesToGI(childRenderer) && childRenderer.gameObject.activeInHierarchy && childRenderer.enabled; if (childContributeGI) { ExpandBounds(childRenderer.bounds); } } } } } else { var renderers = UnityEngine.GameObject.FindObjectsOfType <Renderer>(); foreach (Renderer renderer in renderers) { bool contributeGI = ContributesToGI(renderer) && renderer.gameObject.activeInHierarchy && renderer.enabled; if (contributeGI) { ExpandBounds(renderer.bounds); } } } (serialized.serializedObject.targetObject as ProbeVolume).transform.position = bounds.center; float minBrickSize = ProbeReferenceVolume.instance.MinBrickSize(); Vector3 tmpClamp = (bounds.size + new Vector3(minBrickSize, minBrickSize, minBrickSize)); tmpClamp.x = Mathf.Max(0f, tmpClamp.x); tmpClamp.y = Mathf.Max(0f, tmpClamp.y); tmpClamp.z = Mathf.Max(0f, tmpClamp.z); serialized.size.vector3Value = tmpClamp; } }
private void BuildTreeTypeCellMesh(GameObject owner, TreeSystemStructuredTrees cell, List <TreeSystemStoredInstance> trees, TreeSystemPrototypeData data) { int[] originalTriangles = m_SystemQuad.triangles; RowCol pos = cell.m_Position; GameObject mesh = new GameObject(); // Mark object as static GameObjectUtility.SetStaticEditorFlags(mesh, StaticEditorFlags.OccludeeStatic | StaticEditorFlags.ReflectionProbeStatic); mesh.transform.SetParent(owner.transform); mesh.name = "MeshCell[" + pos.m_Row + "_" + pos.m_Col + "_" + data.m_TreePrototype.name + "]"; Vector3 worldScale = new Vector3(data.m_Size.x, data.m_Size.y, data.m_Size.x); // Set material MeshRenderer rend = mesh.AddComponent <MeshRenderer>(); rend.sharedMaterial = data.m_BillboardBatchMaterial; MeshFilter filter = mesh.AddComponent <MeshFilter>(); Mesh treeMesh = new Mesh(); treeMesh.name = "TreeCell[" + pos.m_Row + "_" + pos.m_Col + "_" + data.m_TreePrototype.name + "]"; List <Vector4> m_TempWorldPositions = new List <Vector4>(); List <Vector3> m_TempWorldScales = new List <Vector3>(); List <Vector3> m_TempQuadVertices = new List <Vector3>(); List <Vector4> m_TempQuadTangents = new List <Vector4>(); List <Vector3> m_TempQuadNormals = new List <Vector3>(); List <int> m_TempQuadIndices = new List <int>(); Bounds newBounds = new Bounds(); newBounds.center = cell.m_Bounds.center; // TODO: populate mesh data for (int treeIndex = 0; treeIndex < trees.Count; treeIndex++) { Vector3 position = trees[treeIndex].m_WorldPosition; Vector3 scale = trees[treeIndex].m_WorldScale; float rot = trees[treeIndex].m_WorldRotation; // Offset world position, by the grounding factor Vector3 instancePos = position; instancePos.y += data.m_Size.z; // Scale by the world scale too so that we don't have to do an extra multip Vector3 instanceScale = scale; instanceScale.Scale(worldScale); // Encapsulate bottom and top also newBounds.Encapsulate(instancePos); newBounds.Encapsulate(instancePos + new Vector3(0, data.m_Size.y, 0)); // Add the world and scale data for (int index = 0; index < 4; index++) { Vector4 posAndRot = instancePos; posAndRot.w = rot; m_TempWorldPositions.Add(posAndRot); m_TempWorldScales.Add(instanceScale); } // Add stanard quad data m_TempQuadVertices.AddRange(m_SystemQuad.vertices); m_TempQuadTangents.AddRange(m_SystemQuad.tangents); m_TempQuadNormals.AddRange(m_SystemQuad.normals); // Calculate triangle indixes m_TempQuadIndices.AddRange(originalTriangles); for (int triIndex = 0; triIndex < 6; triIndex++) { // Just add to the triangles the existing triangles + the new indices m_TempQuadIndices[triIndex + 6 * treeIndex] = originalTriangles[triIndex] + 4 * treeIndex; } } treeMesh.Clear(); // Set standard data treeMesh.SetVertices(m_TempQuadVertices); treeMesh.SetNormals(m_TempQuadNormals); treeMesh.SetTangents(m_TempQuadTangents); // Set the custom data treeMesh.SetUVs(1, m_TempWorldPositions); treeMesh.SetUVs(2, m_TempWorldScales); // Set triangles and do not calculate bounds treeMesh.SetTriangles(m_TempQuadIndices, 0, false); // Set the manually calculated bounds treeMesh.bounds = newBounds; treeMesh.UploadMeshData(true); // Set the mesh filter.mesh = treeMesh; }
void ParsePathElement(Transform parentElement, XmlReader reader, ref int maskLayer) { string id = reader.GetAttribute("id") ?? "Path"; string dStr = reader.GetAttribute("d"); if (dStr != null) { string separators = @"(?=[A-Za-z])"; var tokens = Regex.Split(dStr, separators).Where(t => !string.IsNullOrEmpty(t)); GameObject pathObj = new GameObject(GameObjectUtility.GetUniqueNameForSibling(parentElement, id)); RectTransform pathElement = pathObj.AddComponent <RectTransform>(); pathElement.SetParent(parentElement, false); foreach (string token in tokens) { ParsePathCommand(pathElement, token); } Color fillColor = ParseFillColor(reader); foreach (Transform segment in pathElement) { EnvelopeChildren(segment); } if (pathElement.childCount > 1) { EnvelopeChildren(pathElement); if (pathObj.name.StartsWith("Path")) { pathObj.name = "Compound " + pathObj.name; } foreach (Transform segment in pathElement) { EvenOddFill mask = segment.gameObject.AddComponent <EvenOddFill>(); mask.layer = maskLayer; } GameObject fillObj = new GameObject("Segment Fill"); RectTransform fill = fillObj.AddComponent <RectTransform>(); fill.SetParent(pathElement, false); fill.anchorMin = Vector2.zero; fill.anchorMax = Vector2.one; fill.sizeDelta = Vector2.zero; Image fillImage = fillObj.AddComponent <Image>(); fillImage.color = fillColor; EvenOddFill fillEvenOdd = fillObj.AddComponent <EvenOddFill>(); fillEvenOdd.isMask = false; fillEvenOdd.layer = maskLayer; maskLayer = (maskLayer + 1) % 8; } // prune segment container else if (pathElement.childCount > 0) { _curSegment.gameObject.name = pathObj.name; _curSegment.transform.SetParent(parentElement, false); Graphic graphic = _curSegment.GetComponent <Graphic>(); graphic.color = fillColor; DestroyObject(pathElement.gameObject); } } }
/// <summary> /// Compares two hierarchies, asserts that they match precisely. /// The root can be allowed to mismatch. That's normal with /// GameObject.Instantiate. /// </summary> public static void AssertSameHierarchy( GameObject expectedHierarchy, GameObject actualHierarchy, bool ignoreRootName = false, bool ignoreRootTransform = false, bool checkComponents = false) { if (!ignoreRootName) { Assert.AreEqual(expectedHierarchy.name, actualHierarchy.name); } var expectedTransform = expectedHierarchy.transform; var actualTransform = actualHierarchy.transform; if (!ignoreRootTransform) { AssertVector3(actualTransform.localPosition, expectedTransform.localPosition, 0.0001f); AssertVector3(actualTransform.localEulerAngles, expectedTransform.localEulerAngles, 0.0001f); AssertVector3(actualTransform.localScale, expectedTransform.localScale, 0.0001f); } Assert.AreEqual(expectedTransform.childCount, actualTransform.childCount); if (checkComponents) { // make sure that they each have the same components var expectedComponents = expectedHierarchy.GetComponents <Component>(); var actualComponents = actualHierarchy.GetComponents <Component>(); System.Array.Sort(expectedComponents, CompareComponents); System.Array.Sort(actualComponents, CompareComponents); for (int i = 0; i < expectedComponents.Length; i++) { Assert.That(expectedComponents[i].GetType(), Is.EqualTo(actualComponents[i].GetType())); } // check GO properties as well Assert.That(expectedHierarchy.activeSelf, Is.EqualTo(actualHierarchy.activeSelf)); Assert.That(expectedHierarchy.isStatic, Is.EqualTo(actualHierarchy.isStatic)); Assert.That(expectedHierarchy.layer, Is.EqualTo(actualHierarchy.layer)); Assert.That(expectedHierarchy.tag, Is.EqualTo(actualHierarchy.tag)); Assert.That(GameObjectUtility.GetStaticEditorFlags(expectedHierarchy), Is.EqualTo(GameObjectUtility.GetStaticEditorFlags(actualHierarchy))); } foreach (Transform expectedChild in expectedTransform) { var actualChild = actualTransform.Find(expectedChild.name); Assert.IsNotNull(actualChild); AssertSameHierarchy(expectedChild.gameObject, actualChild.gameObject, checkComponents: checkComponents); } }
static void CreateCustomGameObject(MenuCommand menuCommand) { //Debug.Log("Run command"); GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath("Assets/Custom GameObjects/Horizontal Two Button List/Horizontal Two Button List.prefab", typeof(GameObject)); // Create a custom game object GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject; // Ensure it gets reparented if this was a context click (otherwise does nothing) GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject); // Register the creation in the undo system Undo.RegisterCreatedObjectUndo(go, "Create " + go.name); Selection.activeGameObject = menuCommand.context as GameObject; #region Code //if there is a selected object if (Selection.activeGameObject != null) { Debug.Log(Selection.activeGameObject.name); //Debug.Log("not null go"); //var parentHasCanvasCheck = false; var activeGO = Selection.activeGameObject; var activeGOparent = activeGO.transform.parent; //check through each parent to see if they have a canvas. var hasCanvas = false; while (activeGOparent != null) { var parentCanvas = activeGOparent.GetComponent <Canvas>(); //there is a canvas! if (parentCanvas != null) { hasCanvas = true; break; } activeGOparent = activeGOparent.parent; } //canvas in hiearchy, so attach if (hasCanvas) { go.transform.SetParent(activeGO.transform, false); //no canvas exist in hierarchy, so do previous check } else { //current selection has no parent //so just check activeGO var canvasCheck = activeGO.GetComponent <Canvas>(); //so, activeGO is root, but not canvas if (canvasCheck == null) { GameObject canvasGO = CreateAndGetNewCanvas(); canvasGO.transform.SetParent(activeGO.transform, false); go.transform.SetParent(canvasGO.transform, false); } else { //else, active go is root and canvas go.transform.SetParent(activeGO.transform, false); } } } else { //find canvas Canvas canvas = (Canvas)Object.FindObjectOfType(typeof(Canvas)); //if no canvas, make a new one and parent to gameobject if (canvas == null) { // default Canvas GameObject canvasGO = CreateAndGetNewCanvas(); go.transform.SetParent(canvasGO.transform, false); } else { go.transform.SetParent(canvas.transform, false); } } //selectionIndex++; //Selection.activeGameObject = null; #endregion }
static void ApplyFlagsRecursive( InheritFlags inheritFlags, int layer, string tag, int staticFlags, Transform trans ) { bool dirty = false; GameObject to = trans.gameObject; if (0 != (inheritFlags & InheritFlags.Layer)) { if (to.layer != layer) { dirty = true; to.layer = layer; } } if (0 != (inheritFlags & InheritFlags.Tag)) { if (!to.CompareTag(tag)) { dirty = true; to.tag = tag; } } #if UNITY_EDITOR if (0 != (inheritFlags & InheritFlags.StaticFlags)) { var flags = (StaticEditorFlags)staticFlags; var currFlags = GameObjectUtility.GetStaticEditorFlags(to); if (flags != currFlags) { dirty = true; GameObjectUtility.SetStaticEditorFlags(to, flags); } } if (dirty) { EditorUtility.SetDirty(to); } #endif // UNITY_EDITOR for (int i = 0; i < trans.childCount; ++i) { Transform child = trans.GetChild(i); ApplyFlagsRecursive( inheritFlags, layer, tag, staticFlags, child ); } }
public static void CreateGoldPlayer(MenuCommand menuCommand) { GameObject parent = menuCommand.context as GameObject; string uniqueName = GameObjectUtility.GetUniqueNameForSibling(parent != null ? parent.transform : null, "Gold Player Controller"); // Create the root object. GameObject root = new GameObject(uniqueName) { tag = "Player", layer = LayerMask.NameToLayer("TransparentFX") }; // Place the root in the scene. PlaceInScene(root, parent); // Create the graphics holder. GameObject graphicsHolder = CreateChild("Graphics", root); // Create the actual graphic. GameObject graphic = GameObject.CreatePrimitive(PrimitiveType.Capsule); // Set up the graphic. graphic.name = "Capsule"; graphic.layer = root.layer; graphic.transform.SetParent(graphicsHolder.transform, false); graphic.transform.localScale = new Vector3(0.8f, 1, 0.8f); graphic.transform.localPosition = Vector3.up; // Remove any colliders, if they are present. Collider graphicsCollider = graphic.GetComponent <Collider>(); if (graphicsCollider != null) { Object.DestroyImmediate(graphicsCollider); } // Create the bob target and set the position. GameObject bobTarget = CreateChild("Bob Target", root); bobTarget.transform.localPosition = new Vector3(0f, 1.6f, 0f); // Create the camera head. GameObject cameraHead = CreateChild("Camera Head", bobTarget); // Create the player camera. GameObject playerCameraGo = CreateChild("Player Camera", cameraHead); Camera playerCamera = playerCameraGo.AddComponent <Camera>(); playerCamera.clearFlags = CameraClearFlags.Skybox; playerCamera.fieldOfView = 80; playerCamera.nearClipPlane = 0.01f; playerCamera.farClipPlane = 1000f; playerCameraGo.AddComponent <FlareLayer>(); playerCameraGo.AddComponent <AudioListener>(); // Create the audio object. GameObject audioGo = CreateChild("Audio", root); AudioSource stepsSource = audioGo.AddComponent <AudioSource>(); AudioSource jumpSource = audioGo.AddComponent <AudioSource>(); AudioSource landSource = audioGo.AddComponent <AudioSource>(); // Add the character controller and set it up. CharacterController characterController = root.AddComponent <CharacterController>(); characterController.radius = 0.4f; characterController.height = 2; characterController.center = new Vector3(0, 1, 0); // Add the actual Gold Player Controller and set it up. GoldPlayerController goldController = root.AddComponent <GoldPlayerController>(); goldController.Camera.CameraHead = cameraHead.transform; goldController.Camera.FieldOfViewKick.TargetCamera = playerCamera; goldController.Movement.GroundLayer = 1; goldController.HeadBob.BobTarget = bobTarget.transform; goldController.Audio.FootstepsSource = stepsSource; goldController.Audio.JumpSource = jumpSource; goldController.Audio.LandSource = landSource; #if ENABLE_INPUT_SYSTEM && UNITY_2019_3_OR_NEWER root.AddComponent <GoldPlayerInputSystem>(); #else root.AddComponent <GoldPlayerInput>(); #endif // Register the undo. Undo.RegisterCreatedObjectUndo(root, "Create " + root.name); }
private static void BakeHelper(GameObject[] bakeRoots) { VertexBakerLib.Instance.BakeReset(); DateTime bakeStart = DateTime.Now; List <MeshFilter> meshes = new List <MeshFilter>(); s_meshRenderers = new List <MeshRenderer>(); // gather meshes in selection foreach (GameObject go in bakeRoots) { MeshFilter[] filters = go.GetComponentsInChildren <MeshFilter>(); foreach (MeshFilter filter in filters) { MeshRenderer mr = filter.GetComponent <MeshRenderer>(); if (filter.sharedMesh == null) { Debug.LogWarning(filter.gameObject.GetPath() + " has a missing mesh"); } bool staticLit = (StaticEditorFlags.LightmapStatic & GameObjectUtility.GetStaticEditorFlags(filter.gameObject)) > 0; if (filter.sharedMesh != null && filter.gameObject.activeSelf && staticLit && mr != null && mr.enabled) { s_meshRenderers.Add(mr); meshes.Add(filter); } } } if (meshes.Count == 0) { EditorUtility.DisplayDialog(Styles.kEditorTitle, Styles.kNoStaticMeshes, "ok"); return; } if (meshes.Count != s_meshRenderers.Count) { EditorUtility.DisplayDialog(Styles.kEditorTitle, "MeshRenderers are not 1 to 1 with Mesh Filters", "ok"); return; } List <Light> lights = new List <Light>(); DDRSettings settingsData = BakeData.Instance().GetBakeSettings(); if (settingsData.SelectedBakeSet.m_forceAllLights) { List <GameObject> sceneRoots = Utilities.GetAllRoots(); foreach (GameObject go in sceneRoots) { Light[] lightList = go.GetComponentsInChildren <Light>(); foreach (Light light in lightList) { if (light.IsLightmapLight()) { lights.Add(light); } } } } else { List <LightEntry> lightFilter = settingsData.SelectedBakeSet.m_lightList; Dictionary <int, Light> localFileIdToLight = Utilities.LightsByLocalFileId(); foreach (LightEntry lightEntry in lightFilter) { Light light = null; // group if lights if (!string.IsNullOrEmpty(lightEntry.m_group)) { // get parent objects for each path that matches the group path List <GameObject> parents = Utilities.FindAll(lightEntry.m_group); // gather all lights under group if (parents.Count > 0) { // add lights to the new group foreach (GameObject parent in parents) { for (int i = 0; i < parent.transform.childCount; ++i) { GameObject child = parent.transform.GetChild(i).gameObject; light = child.GetComponent <Light>(); if (light.IsLightmapLight()) { lights.Add(light); } } } } } else { // ungrouped light if (localFileIdToLight.TryGetValue(lightEntry.m_idInFile, out light)) { if (light.IsLightmapLight()) { lights.Add(light); } } } } } VertexBakerLib.Log("Collect data time: " + (DateTime.Now - bakeStart).TotalSeconds + " seconds"); /////////////// // native bake /////////////// try { // stop listening for changes m_ignoreNextChange = true; // int activeLightCount = DaydreamRendererSceneData.GetActiveLightCount(); // DaydreamRendererSceneData sceneData = TypeExtensions.FindOrCreateScriptableAsset<DaydreamRendererSceneData>(VertexBakerLib.DataPath, "scenedata"); s_bakeInProgress = true; VertexBakerLib.Instance.Bake(meshes, lights, delegate() { s_bakeIsFinished = true; }); } catch (Exception e) { Debug.LogError(e.Message); Debug.LogError(e.StackTrace); } }
static ActionResult DetachFacesToObject() { int detachedFaceCount = 0; List <GameObject> detached = new List <GameObject>(); foreach (ProBuilderMesh mesh in MeshSelection.topInternal) { if (mesh.selectedFaceCount < 1 || mesh.selectedFaceCount == mesh.facesInternal.Length) { continue; } var primary = mesh.selectedFaceIndexes; detachedFaceCount += primary.Count; List <int> inverse = new List <int>(); for (int i = 0; i < mesh.facesInternal.Length; i++) { if (!primary.Contains(i)) { inverse.Add(i); } } ProBuilderMesh copy = Object.Instantiate(mesh.gameObject, mesh.transform.parent).GetComponent <ProBuilderMesh>(); EditorUtility.SynchronizeWithMeshFilter(copy); if (copy.transform.childCount > 0) { for (int i = copy.transform.childCount - 1; i > -1; i--) { Object.DestroyImmediate(copy.transform.GetChild(i).gameObject); } foreach (var child in mesh.transform.GetComponentsInChildren <ProBuilderMesh>()) { EditorUtility.SynchronizeWithMeshFilter(child); } } Undo.RegisterCreatedObjectUndo(copy.gameObject, "Detach Selection"); mesh.DeleteFaces(primary); copy.DeleteFaces(inverse); mesh.Rebuild(); copy.Rebuild(); mesh.Optimize(); copy.Optimize(); mesh.ClearSelection(); copy.ClearSelection(); copy.SetSelectedFaces(copy.faces); copy.gameObject.name = GameObjectUtility.GetUniqueNameForSibling(mesh.transform.parent, mesh.gameObject.name);; detached.Add(copy.gameObject); } MeshSelection.SetSelection(detached); ProBuilderEditor.Refresh(); if (detachedFaceCount > 0) { return(new ActionResult(ActionResult.Status.Success, "Detach " + detachedFaceCount + " faces to new Object")); } return(new ActionResult(ActionResult.Status.Failure, "No Faces Selected")); }
// This method is used by Component specific classes (e.g. ChiselBoxEditor) // to create a menu Item that creates a gameObject with a specific component (e.g. ChiselBox) // Since MenuItems can only be created with attributes, and strings must be constant, // we can only do this from place where we specifically know which component the menu is for. protected static void CreateAsGameObjectMenuCommand(MenuCommand menuCommand, string name) { T component; // If we use the command object on a gameobject in the hierarchy, choose that gameobject // Otherwise: choose the activeModel (if available) var context = (menuCommand.context as GameObject); var parentGameObject = (context != null) ? context : (ChiselModelManager.ActiveModel != null) ? ChiselModelManager.ActiveModel.gameObject : null; var parentTransform = (parentGameObject == null) ? null : parentGameObject.transform; // If we used the command object on a generator, choose it's parent to prevent us from // adding a generator as a child to a generator if (parentTransform && parentTransform.GetComponent <ChiselGeneratorComponent>()) { parentTransform = parentTransform.parent; parentGameObject = (parentTransform == null) ? null : parentTransform.gameObject; } // Create the gameobject if (parentTransform) { component = ChiselComponentFactory.Create <T>(name, parentTransform); } else { component = ChiselComponentFactory.Create <T>(name); } var gameObject = component.gameObject; GameObjectUtility.SetParentAndAlign(gameObject, parentGameObject); Undo.RegisterCreatedObjectUndo(gameObject, "Create " + gameObject.name); // Find the appropriate model to make active after we created the generator ChiselModel model; if (typeof(T) != typeof(ChiselModel)) { model = gameObject.GetComponentInParent <ChiselModel>(); // If we don't have a parent model, create one and put the generator underneath it if (!model) { model = ChiselModelManager.CreateNewModel(gameObject.transform.parent); // Make sure we create the model at the exact same location as the generator var modelGameObject = model.gameObject; var modelTransform = model.transform; var childSiblingIndex = modelTransform.GetSiblingIndex(); modelTransform.SetSiblingIndex(childSiblingIndex); Undo.RegisterCreatedObjectUndo(modelGameObject, "Create " + modelGameObject.name); MoveTargetsUnderModel(new[] { component }, model); } } else { model = component as ChiselModel; } // Set the active model before we select the gameobject, otherwise we'll be selecting the model instead ChiselModelManager.ActiveModel = model; Selection.activeObject = gameObject; }
static public GameObject CreateGameObject(GameObject parent, string name, params Type[] types) => ObjectFactory.CreateGameObject(GameObjectUtility.GetUniqueNameForSibling(parent != null ? parent.transform : null, name), types);
private static void SetParentAndAlign(GameObject gameObject, MenuCommand menuCommand) { GameObjectUtility.SetParentAndAlign(gameObject, menuCommand.context as GameObject); }
public override void SetStaticFlags(GameObject gameObject, int flags = 1) { #if UNITY_EDITOR GameObjectUtility.SetStaticEditorFlags(gameObject, (StaticEditorFlags)flags); #endif }
//------------------------------- public void LoadSceneForUI() { GameObjectUtility.ClearObjectPools(); CharacterSpawner.EndGameClear(); LoadSceneAsync("BuildingOne"); }
public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { LoadTreeIcons(terrain); // Tree picker GUI.changed = false; ShowUpgradeTreePrototypeScaleUI(terrain); GUILayout.Label(Styles.trees, EditorStyles.boldLabel); selectedTree = TerrainInspector.AspectSelectionGridImageAndText(selectedTree, m_TreeContents, 64, Styles.noTreesDefined, out var doubleClick); if (selectedTree >= m_TreeContents.Length) { selectedTree = PaintTreesTool.kInvalidTree; } if (doubleClick) { TerrainTreeContextMenus.EditTree(new MenuCommand(terrain, selectedTree)); GUIUtility.ExitGUI(); } GUILayout.BeginHorizontal(); using (new EditorGUI.DisabledScope(selectedTree == PaintTreesTool.kInvalidTree)) { if (GUILayout.Button(Styles.massPlaceTrees)) { TerrainMenus.MassPlaceTrees(); } } GUILayout.FlexibleSpace(); TerrainInspector.MenuButton(Styles.editTrees, "CONTEXT/TerrainEngineTrees", terrain, selectedTree); TerrainInspector.ShowRefreshPrototypes(); GUILayout.EndHorizontal(); GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel); // Placement distance brushSize = TerrainInspectorUtility.PowerSlider(TerrainInspector.styles.brushSize, brushSize, 1, Mathf.Min(terrain.terrainData.size.x, terrain.terrainData.size.z), 4.0f); float oldDens = (3.3f - spacing) / 3f; float newDens = TerrainInspectorUtility.ScaledSliderWithRounding(Styles.treeDensity, oldDens, 0.1f, 1.0f, 100.0f, 1.0f); // Only set spacing when value actually changes. Otherwise // it will lose precision because we're constantly doing math // back and forth with it. if (newDens != oldDens) { spacing = (1.1f - newDens) * 3f; } GUILayout.Space(5); GUILayout.BeginHorizontal(); GUILayout.Label(Styles.treeHeight, GUILayout.Width(EditorGUIUtility.labelWidth - 6)); GUILayout.Label(Styles.treeHeightRandomLabel, GUILayout.ExpandWidth(false)); allowHeightVar = GUILayout.Toggle(allowHeightVar, Styles.treeHeightRandomToggle, GUILayout.ExpandWidth(false)); if (allowHeightVar) { EditorGUI.BeginChangeCheck(); float min = treeHeight * (1.0f - treeHeightVariation); float max = treeHeight * (1.0f + treeHeightVariation); EditorGUILayout.MinMaxSlider(ref min, ref max, 0.01f, 2.0f); if (EditorGUI.EndChangeCheck()) { treeHeight = (min + max) * 0.5f; treeHeightVariation = (max - min) / (min + max); } } else { treeHeight = EditorGUILayout.Slider(treeHeight, 0.01f, 2.0f); treeHeightVariation = 0.0f; } GUILayout.EndHorizontal(); GUILayout.Space(5); lockWidthToHeight = EditorGUILayout.Toggle(Styles.lockWidthToHeight, lockWidthToHeight); GUILayout.Space(5); using (new EditorGUI.DisabledScope(lockWidthToHeight)) { GUILayout.BeginHorizontal(); GUILayout.Label(Styles.treeWidth, GUILayout.Width(EditorGUIUtility.labelWidth - 6)); GUILayout.Label(Styles.treeWidthRandomLabel, GUILayout.ExpandWidth(false)); allowWidthVar = GUILayout.Toggle(allowWidthVar, Styles.treeWidthRandomToggle, GUILayout.ExpandWidth(false)); if (allowWidthVar) { EditorGUI.BeginChangeCheck(); float min = treeWidth * (1.0f - treeWidthVariation); float max = treeWidth * (1.0f + treeWidthVariation); EditorGUILayout.MinMaxSlider(ref min, ref max, 0.01f, 2.0f); if (EditorGUI.EndChangeCheck()) { treeWidth = (min + max) * 0.5f; treeWidthVariation = (max - min) / (min + max); } } else { treeWidth = EditorGUILayout.Slider(treeWidth, 0.01f, 2.0f); treeWidthVariation = 0.0f; } GUILayout.EndHorizontal(); } if (selectedTree == PaintTreesTool.kInvalidTree) { return; } GUILayout.Space(5); GameObject prefab = terrain.terrainData.treePrototypes[selectedTree].m_Prefab; string treePrototypeWarning; terrain.terrainData.treePrototypes[selectedTree].Validate(out treePrototypeWarning); bool isLodTreePrototype = TerrainEditorUtility.IsLODTreePrototype(prefab); using (new EditorGUI.DisabledScope(!isLodTreePrototype)) { randomRotation = EditorGUILayout.Toggle(Styles.treeRotation, randomRotation); } if (!isLodTreePrototype) { EditorGUILayout.HelpBox(Styles.treeRotationDisabled.text, MessageType.Info); } if (!string.IsNullOrEmpty(treePrototypeWarning)) { EditorGUILayout.HelpBox(treePrototypeWarning, MessageType.Warning); } // TODO: we should check if the shaders assigned to this 'tree' support _TreeInstanceColor or not.. complicated check though treeColorAdjustment = EditorGUILayout.Slider(Styles.treeColorVar, treeColorAdjustment, 0, 1); if (prefab != null) { StaticEditorFlags staticEditorFlags = GameObjectUtility.GetStaticEditorFlags(prefab); bool contributeGI = (staticEditorFlags & StaticEditorFlags.ContributeGI) != 0; using (new EditorGUI.DisabledScope(true)) // Always disabled, because we don't want to edit the prefab. contributeGI = EditorGUILayout.Toggle(Styles.treeContributeGI, contributeGI); } }
/// <summary> /// Editor Window /// </summary> private void OnGUI() { if (instance == null) { GetMapInstance(SceneManager.GetActiveScene()); } GetGUIStyles(); var enums = System.Enum.GetValues(typeof(MapScriptableObject.CellType)); EditorGUILayout.LabelField(instance.name); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Map Cell Editor", boldLabel); length_scr = EditorGUILayout.IntField("Length", length_scr); width_scr = EditorGUILayout.IntField("Width", width_scr); if ((instance.length != length_scr && length_scr > 0) || (instance.width != width_scr && width_scr > 0)) { EditorGUILayout.BeginHorizontal(); //CreateAnchorTextures(); for (var a = 0; a < anchorSet.Length; a++) { if (GUILayout.Button(anchorText[a], anchor == anchorSet[a] ? pressedButton : standardButton)) { anchor = anchorSet[a]; } if ((a + 1) % 3 == 0) { EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Apply")) { instance.Resize(length_scr, width_scr, anchor); } if (GUILayout.Button("Reset")) { length_scr = instance.length; width_scr = instance.width; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Separator(); } instance.height = EditorGUILayout.IntField("Height", instance.height); instance.cellsize = EditorGUILayout.FloatField("Cell Size", instance.cellsize); // guarantee details are set properly var insdetails = instance.details; var details = new MapTileDetails[enums.Length]; for (var k = 0; k < enums.Length; k++) { var cell = (MapScriptableObject.CellType)enums.GetValue(k); if (insdetails != null && k < insdetails.Length) { details[k] = insdetails[k]; } else { details[k] = new MapTileDetails { cell = cell } }; } instance.details = details; EditorGUILayout.Separator(); EditorGUILayout.LabelField("Tile Editor", boldLabel); // Paint buttons EditorGUILayout.BeginHorizontal(); var i = 0; foreach (var cellvalue in tileOptions) { if (GUILayout.Button(cellvalue.ToString(), selectedCellType == cellvalue ? pressedButton : standardButton)) { selectedCellType = cellvalue; } if (++i == 4) { i = 0; EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); } } EditorGUILayout.EndHorizontal(); // Show options for whichever is selected var item = details[(int)selectedCellType]; item.inactiveColor = EditorGUILayout.ColorField("Inactive Color", item.inactiveColor); item.activeColor = EditorGUILayout.ColorField("Active Color", item.activeColor); item.layer = EditorGUILayout.LayerField("Layer", item.layer); item.areaType = EditorGUILayout.Popup("Area Type", item.areaType, GameObjectUtility.GetNavMeshAreaNames()); EditorGUILayout.Space(); item.groundCreate = EditorGUILayout.Toggle("Create Ground?", item.groundCreate); if (item.groundCreate) { EditorGUI.indentLevel++; item.groundMaterial = (Material)EditorGUILayout.ObjectField("Ground Material", item.groundMaterial, typeof(Material), false); item.groundUseMapHeight = EditorGUILayout.Toggle("Use Height?", item.groundUseMapHeight); item.groundOffset = EditorGUILayout.FloatField("Ground Offset", item.groundOffset); EditorGUI.indentLevel--; EditorGUILayout.Space(); } item.colliderCreate = EditorGUILayout.Toggle("Create Colliders?", item.colliderCreate); if (item.colliderCreate) { EditorGUI.indentLevel++; item.colliderHeightUseMapHeight = EditorGUILayout.Toggle("Use Height?", item.colliderHeightUseMapHeight); item.colliderHeight = EditorGUILayout.FloatField("Collider Height", item.colliderHeight); item.colliderOffset = EditorGUILayout.FloatField("Collider Offset", item.colliderOffset); EditorGUI.indentLevel--; EditorGUILayout.Space(); } item.wallCreate = EditorGUILayout.Toggle("Create Walls?", item.wallCreate); if (item.wallCreate) { EditorGUI.indentLevel++; item.wallUseMapHeight = EditorGUILayout.Toggle("Use Height?", item.wallUseMapHeight); item.wallMaterial = (Material)EditorGUILayout.ObjectField("Wall Material", item.wallMaterial, typeof(Material), false); item.wallOffset = EditorGUILayout.FloatField("Wall Offset", item.wallOffset); item.wallHeight = EditorGUILayout.FloatField("Wall Height", item.wallHeight); item.wallScaleUVHeight = EditorGUILayout.Toggle("Scale UV Height?", item.wallScaleUVHeight); item.wallInvert = EditorGUILayout.Toggle("Invert?", item.wallInvert); EditorGUI.indentLevel--; EditorGUILayout.Space(); } item.mapUniqueCreate = EditorGUILayout.Toggle("Store in Map_Unique?", item.mapUniqueCreate); // Copy and paste EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Copy All", standardButton)) { savedDetailsAll = instance.details; } var copyState = savedDetailsAll != null && savedDetailsAll.Length > 0; if (GUILayout.Button("Paste All", copyState ? standardButton : disabledButton) && copyState) { instance.details = savedDetailsAll; } EditorGUILayout.EndHorizontal(); // Show/Hide maps. Create Map EditorGUILayout.Separator(); EditorGUILayout.LabelField("Map", boldLabel); if (GUILayout.Button(instance.display ? "Hide Map" : "Show Map")) { instance.display = !instance.display; onView = true; } if (GUILayout.Button("Create Map")) { CreateMap(); } EditorUtility.SetDirty(instance); }
protected override void CreateMeshBefore() { base.CreateMeshBefore(); #region RemoveChunk voxelObject.UpdateChunks(); var chunkObjects = voxelObject.chunks; { bool chunkObjectsUpdate = false; bool[] enableTale = new bool[chunkObjects.Length]; if (!removeAllChunk) { for (int i = 0; i < chunkDataList.Count; i++) { for (int j = 0; j < chunkObjects.Length; j++) { if (chunkDataList[i].position == chunkObjects[j].position) { enableTale[j] = true; break; } } } } else { removeAllChunk = false; } for (int i = 0; i < enableTale.Length; i++) { if (!enableTale[i]) { var go = chunkObjects[i].gameObject; while (go.transform.childCount > 0) { Undo.SetTransformParent(go.transform.GetChild(0), voxelObject.transform, "Remove Chunk"); } Undo.DestroyObjectImmediate(go); chunkObjectsUpdate = true; } } if (chunkObjectsUpdate) { voxelObject.UpdateChunks(); chunkObjects = voxelObject.chunks; } } #endregion #region AddChunk int chunkCount = 0; { bool chunkObjectsUpdate = false; for (int i = 0; i < chunkDataList.Count; i++) { GameObject chunkObject = null; for (int j = 0; j < chunkObjects.Length; j++) { if (chunkDataList[i].position == chunkObjects[j].position) { chunkObject = chunkObjects[j].gameObject; break; } } if (chunkObject == null) { chunkObject = new GameObject(chunkDataList[i].name); Undo.RegisterCreatedObjectUndo(chunkObject, "Create Chunk"); Undo.SetTransformParent(chunkObject.transform, voxelObject.transform, "Create Chunk"); GameObjectUtility.SetStaticEditorFlags(chunkObject, GameObjectUtility.GetStaticEditorFlags(voxelObject.gameObject)); chunkObject.transform.localPosition = Vector3.Scale(voxelObject.localOffset + chunkDataList[i].area.centerf, voxelObject.importScale); chunkObject.transform.localRotation = Quaternion.identity; chunkObject.transform.localScale = Vector3.one; chunkObject.layer = voxelObject.gameObject.layer; chunkObject.tag = voxelObject.gameObject.tag; chunkObjectsUpdate = true; } VoxelChunksObjectChunk controller = chunkObject.GetComponent <VoxelChunksObjectChunk>(); if (controller == null) { controller = Undo.AddComponent <VoxelChunksObjectChunk>(chunkObject); } controller.position = chunkDataList[i].position; controller.chunkName = chunkDataList[i].name; controller.basicOffset = Vector3.Scale(voxelObject.localOffset + chunkDataList[i].area.centerf, voxelObject.importScale); chunkCount++; } if (chunkObjectsUpdate) { voxelObject.UpdateChunks(); chunkObjects = voxelObject.chunks; } } #endregion #region SortChunk { List <Transform> objList = new List <Transform>(); var childCount = voxelObject.transform.childCount; for (int i = 0; i < childCount; i++) { objList.Add(voxelObject.transform.GetChild(i)); } objList.Sort((obj1, obj2) => string.Compare(obj1.name, obj2.name)); for (int i = 0; i < objList.Count; i++) { objList[i].SetSiblingIndex(childCount - 1); } voxelObject.UpdateChunks(); chunkObjects = voxelObject.chunks; } #endregion #region UpdateChunk for (int i = 0; i < chunkObjects.Length; i++) { for (int j = 0; j < chunkDataList.Count; j++) { if (chunkObjects[i].position == chunkDataList[j].position) { chunkDataList[j].chunkObject = chunkObjects[i]; break; } } } #endregion }
private static void CreatePagination() { // Canvas Canvas canvas = FindObjectOfType <Canvas>(); if (canvas == null) { GameObject canvasObject = new GameObject("Canvas"); canvas = canvasObject.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.gameObject.AddComponent <GraphicRaycaster>(); Undo.RegisterCreatedObjectUndo(canvasObject, "Create " + canvasObject.name); } // Pagination int numberOfToggles = 5; int side = 25; int spacing = 15; GameObject pagination = new GameObject("Pagination"); RectTransform paginationRectTransform = pagination.AddComponent <RectTransform>(); paginationRectTransform.sizeDelta = new Vector2((numberOfToggles * (side + spacing)) - spacing, side); GameObjectUtility.SetParentAndAlign(pagination, canvas.gameObject); for (int i = 0; i < numberOfToggles; i++) { // Toggle GameObject toggle = new GameObject((i + 1) + ""); GameObjectUtility.SetParentAndAlign(toggle, pagination); RectTransform toggleRectTransform = toggle.AddComponent <RectTransform>(); toggleRectTransform.anchorMin = toggleRectTransform.anchorMax = new Vector2(0, 0.5f); toggleRectTransform.pivot = new Vector2(0, 0.5f); toggleRectTransform.sizeDelta = new Vector2(side, side); toggleRectTransform.anchoredPosition = new Vector2(i * (side + spacing), 0); Toggle toggleToggle = toggle.AddComponent <Toggle>(); toggleToggle.isOn = false; toggleToggle.transition = Selectable.Transition.None; // Background GameObject background = new GameObject("Background"); GameObjectUtility.SetParentAndAlign(background, toggle); RectTransform backgroundRectTransform = background.AddComponent <RectTransform>(); backgroundRectTransform.anchorMin = Vector2.zero; backgroundRectTransform.anchorMax = Vector2.one; backgroundRectTransform.sizeDelta = Vector2.zero; Image backgroundImage = background.AddComponent <Image>(); backgroundImage.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/Knob.psd"); backgroundImage.color = new Color(0.75f, 0.75f, 0.75f); // Selected GameObject selected = new GameObject("Selected"); GameObjectUtility.SetParentAndAlign(selected, background); RectTransform selectedRectTransform = selected.AddComponent <RectTransform>(); selectedRectTransform.anchorMin = Vector2.zero; selectedRectTransform.anchorMax = Vector2.one; selectedRectTransform.sizeDelta = Vector2.zero; Image selectedImage = selected.AddComponent <Image>(); selectedImage.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/Knob.psd"); selectedImage.color = Color.white; toggleToggle.graphic = selected.GetComponent <Image>(); } // Event System if (!FindObjectOfType <EventSystem>()) { GameObject eventObject = new GameObject("EventSystem", typeof(EventSystem)); eventObject.AddComponent <StandaloneInputModule>(); Undo.RegisterCreatedObjectUndo(eventObject, "Create " + eventObject.name); } // Editor Selection.activeGameObject = pagination; Undo.RegisterCreatedObjectUndo(pagination, "Create " + pagination.name); }
public static void CreateInventory(MenuCommand pCommand) { const float const_fPosX = 120f; GameObject pObjectParents = pCommand.context as GameObject; if (pObjectParents == null) { pObjectParents = new GameObject($"{nameof(Inventory)}"); // 생성된 오브젝트를 Undo 시스템에 등록한다. Undo.RegisterCreatedObjectUndo(pObjectParents, "Create " + pObjectParents.name); } if (pObjectParents.GetComponent <Inventory>() == null) { Undo.AddComponent <Inventory>(pObjectParents); } if (pObjectParents.GetComponent <GridLayoutGroup>() == null) { Undo.AddComponent <GridLayoutGroup>(pObjectParents); } int iSlotCount = 5; GameObject pObjectSlotLast = null; for (int i = 0; i < iSlotCount; i++) { string strSlotName = $"Slot ({i + 1})"; pObjectSlotLast = new GameObject(strSlotName); // 생성된 오브젝트를 Undo 시스템에 등록한다. Undo.RegisterCreatedObjectUndo(pObjectSlotLast, "Create " + strSlotName); GameObjectUtility.SetParentAndAlign(pObjectSlotLast, pObjectParents); pObjectSlotLast.transform.position += new Vector3(const_fPosX * i, 0f); Image pSlotIcon = pObjectSlotLast.AddComponent <Image>(); pSlotIcon.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/UISprite.psd"); GameObject pObjectSlotFrame = new GameObject($"Image_ItemFrame"); GameObjectUtility.SetParentAndAlign(pObjectSlotFrame, pObjectSlotLast); Image pItemFrame = pObjectSlotFrame.AddComponent <Image>(); pItemFrame.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/UISprite.psd"); pItemFrame.rectTransform.SetAnchor(AnchorPresets.StretchAll); pItemFrame.rectTransform.sizeDelta = Vector2.one * -20f; GameObject pObjectItemIcon = new GameObject($"Image_ItemIcon"); GameObjectUtility.SetParentAndAlign(pObjectItemIcon, pObjectSlotLast); Image pItemIcon = pObjectItemIcon.AddComponent <Image>(); pItemIcon.sprite = AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/UISprite.psd"); pItemIcon.rectTransform.SetAnchor(AnchorPresets.StretchAll); pItemIcon.rectTransform.sizeDelta = Vector2.one * -30f; InventorySlot pSlot = pObjectSlotLast.AddComponent <InventorySlot>(); pSlot.iSlotIndex = i; } Selection.activeObject = pObjectSlotLast; }
/// <summary> /// Returns true if GameObject contains flags. /// </summary> /// <param name="go"></param> /// <param name="flags"></param> /// <returns></returns> internal static bool HasStaticFlag(this GameObject go, StaticEditorFlags flags) { return((GameObjectUtility.GetStaticEditorFlags(go) & flags) == flags); }
static void CreateTextMeshProGuiObjectPerform(MenuCommand command) { // Check if there is a Canvas in the scene Canvas canvas = Object.FindObjectOfType <Canvas>(); if (canvas == null) { // Create new Canvas since none exists in the scene. GameObject canvasObject = new GameObject("Canvas"); canvas = canvasObject.AddComponent <Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; // Add a Graphic Raycaster Component as well canvas.gameObject.AddComponent <GraphicRaycaster>(); Undo.RegisterCreatedObjectUndo(canvasObject, "Create " + canvasObject.name); } // Create the TextMeshProUGUI Object GameObject go = new GameObject("TextMeshPro Text"); RectTransform goRectTransform = go.AddComponent <RectTransform>(); Undo.RegisterCreatedObjectUndo((Object)go, "Create " + go.name); // Check if object is being create with left or right click GameObject contextObject = command.context as GameObject; if (contextObject == null) { //goRectTransform.sizeDelta = new Vector2(200f, 50f); GameObjectUtility.SetParentAndAlign(go, canvas.gameObject); TextMeshProUGUI textMeshPro = go.AddComponent <TextMeshProUGUI>(); textMeshPro.text = "New Text"; textMeshPro.alignment = TextAlignmentOptions.TopLeft; } else { if (contextObject.GetComponent <Button>() != null) { goRectTransform.sizeDelta = Vector2.zero; goRectTransform.anchorMin = Vector2.zero; goRectTransform.anchorMax = Vector2.one; GameObjectUtility.SetParentAndAlign(go, contextObject); TextMeshProUGUI textMeshPro = go.AddComponent <TextMeshProUGUI>(); textMeshPro.text = "Button"; textMeshPro.fontSize = 24; textMeshPro.alignment = TextAlignmentOptions.Center; } else { //goRectTransform.sizeDelta = new Vector2(200f, 50f); GameObjectUtility.SetParentAndAlign(go, contextObject); TextMeshProUGUI textMeshPro = go.AddComponent <TextMeshProUGUI>(); textMeshPro.text = "New Text"; textMeshPro.alignment = TextAlignmentOptions.TopLeft; } } // Check if an event system already exists in the scene if (!Object.FindObjectOfType <EventSystem>()) { GameObject eventObject = new GameObject("EventSystem", typeof(EventSystem)); eventObject.AddComponent <StandaloneInputModule>(); Undo.RegisterCreatedObjectUndo(eventObject, "Create " + eventObject.name); } Selection.activeGameObject = go; }
static float drawStaticIcon(GameObject gameObject, Rect rect) { rect.x -= 14; rect.width = 14; bool isStatic = gameObject.isStatic; StaticEditorFlags staticFlags = GameObjectUtility.GetStaticEditorFlags(gameObject); Texture2D buttonTexture = isStatic ? ((int)staticFlags == -1 ? QHierarchyResource.getTexture(QHierarchyTexture.ButtonStaticOn) : QHierarchyResource.getTexture(QHierarchyTexture.ButtonStaticHalf)) : QHierarchyResource.getTexture(QHierarchyTexture.ButtonStaticOff); GUI.DrawTexture(rect, buttonTexture); if (Event.current.isMouse && Event.current.button == 0 && rect.Contains(Event.current.mousePosition)) { if (Event.current.type == EventType.MouseDown) { targetStaticState = ((!isStatic) == true ? 1 : 0); } else if (Event.current.type == EventType.MouseDrag && targetStaticState != -1) { if (targetStaticState == (isStatic == true ? 1 : 0)) { return(rect.width); } } else { targetStaticState = -1; return(rect.width); } Event.current.Use(); bool showWarning = QHierarchySettings.getSetting <bool>(QHierarchySetting.ShowModifierWarning); List <GameObject> targetGameObjects = new List <GameObject>(); if (Event.current.shift) { if (!showWarning || EditorUtility.DisplayDialog("Change static", "Are you sure you want to " + (isStatic ? "disable" : "enable") + " Static of this GameObject and all its children? (You can disable this warning in the settings)", "Yes", "Cancel")) { getGameObjectListRecursive(ref targetGameObjects, gameObject); } } else if (Event.current.alt) { if (gameObject.transform.parent != null) { if (!showWarning || EditorUtility.DisplayDialog("Change static", "Are you sure you want to " + (isStatic ? "disable" : "enable") + " Static of this GameObject and all its siblings? (You can disable this warning in the settings)", "Yes", "Cancel")) { getGameObjectListRecursive(ref targetGameObjects, gameObject.transform.parent.gameObject, 1); targetGameObjects.Remove(gameObject.transform.parent.gameObject); } } else { gameObject.scene.GetRootGameObjects(targetGameObjects); } } else { if (Selection.Contains(gameObject)) { targetGameObjects.AddRange(Selection.gameObjects); } else { getGameObjectListRecursive(ref targetGameObjects, gameObject, 0); } } setStatic(targetGameObjects, !isStatic); } return(rect.width); }
public override void OnInspectorGUI() { // INITIALIZATION Level level = target as Level; // DRAW THE UI GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool addButtonResult = GUILayout.Button("Add Boundary", GUILayout.Width(300), GUILayout.Height(20)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool hideButtonResult = GUILayout.Button("Hide/Show Boundaries", GUILayout.Width(300), GUILayout.Height(20)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool resetButtonResult = GUILayout.Button("Reset", GUILayout.Width(300), GUILayout.Height(20)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool buildButtonResult = GUILayout.Button("Build", GUILayout.Width(300), GUILayout.Height(30)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // HANDLE THE INPUT if (buildButtonResult) { level.CompileLevel(); } else if (addButtonResult) { // Create a new GameObject with a Level attached GameObject newBoundary = GameObject.CreatePrimitive(PrimitiveType.Cube); newBoundary.name = "Boundary"; newBoundary.AddComponent <Boundary>(); // Ensure it gets reparented if this was a context click (otherwise does nothing) GameObjectUtility.SetParentAndAlign(newBoundary, ((Level)target).gameObject); // Register the creation in the undo system Undo.RegisterCreatedObjectUndo(newBoundary, "Create " + newBoundary.name); } else if (resetButtonResult) { // Destroy all child polygons foreach (Polygon poly in level.gameObject.GetComponents <Polygon>()) { DestroyImmediate(poly); } GUIUtility.ExitGUI(); } else if (hideButtonResult) { // toggle visibility of all child boundaries if (BoundariesVisible) { BoundariesVisible = false; } else { BoundariesVisible = true; } foreach (Transform child in level.transform) { child.gameObject.SetActive(BoundariesVisible); } } }
bool PlaceDecal(Vector2 mousePosition, Material mat, Rect uvCoordinates, float rotation, float scale, out GameObject decal, out Transform hitTransform) { decal = null; hitTransform = null; GameObject nearest = HandleUtility.PickGameObject(mousePosition, false); if (nearest == null) { return(false); } Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition); RaycastHit hit; MeshFilter mf = nearest.GetComponent <MeshFilter>(); TerrainCollider tc = nearest.GetComponent <TerrainCollider>(); if (mf != null && mf.sharedMesh != null) { Mesh msh = mf.sharedMesh; // Use IntersectRayMesh because no other raycast is capable of intersecting non-collider objects. object[] parameters = new object[] { ray, msh, nearest.transform.localToWorldMatrix, null }; if (IntersectRayMesh == null) { IntersectRayMesh = typeof(HandleUtility).GetMethod("IntersectRayMesh", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance); } object result = IntersectRayMesh.Invoke(this, parameters); if ((bool)result) { hit = (RaycastHit)parameters[3]; } else { return(false); } } else if (tc != null) { if (!Physics.Raycast(ray, out hit)) { return(false); } } else { return(false); } hitTransform = nearest.transform; decal = qd_Mesh.CreateDecal(mat, uvCoordinates, scale); Undo.RegisterCreatedObjectUndo(decal, "Place Decal"); StaticEditorFlags flags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.LightmapStatic | StaticEditorFlags.OccludeeStatic; GameObjectUtility.SetStaticEditorFlags(decal, flags); decal.transform.position = hit.point + hit.normal.normalized * .01f; decal.transform.localRotation = Quaternion.LookRotation(hit.normal); Vector3 rot = decal.transform.eulerAngles; rot.z += rotation; decal.transform.localRotation = Quaternion.Euler(rot); return(true); }
protected override void DrawInstanceUI() { foreach (var o in targets) { var p = o as PortalController; if (p == null) { return; } GameObjectUtility.SetStaticEditorFlags(p.gameObject, GameObjectUtility.GetStaticEditorFlags(p.gameObject) & ~StaticEditorFlags.LightmapStatic); } try { GUILayout.Label("Instance settings:", EditorStyles.boldLabel); foreach (PortalController p in targets) { Undo.RecordObject(p, "Portal Controller Editor Changes"); } EditorGUI.BeginChangeCheck(); TargetController.TargetController = (PortalController)EditorGUILayout.ObjectField( new GUIContent("Target Controller", "The targetTransform of this Portal."), TargetController.TargetController, typeof(PortalController), true, null); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.TargetController = TargetController.TargetController; } } //if (!PortalController.PortalScript.PortalCamera || // !PortalController.TargetController.PortalScript.PortalCamera) return; EditorGUI.BeginChangeCheck(); TargetController.PortalPrefab = (GameObject)EditorGUILayout.ObjectField( new GUIContent("Portal Prefab", "The Prefab to use for when the Portal is spawned"), TargetController.PortalPrefab, typeof(GameObject), false, null); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.PortalPrefab = TargetController.PortalPrefab; } } if (SKSGlobalRenderSettings.ShouldOverrideMask) { EditorGUILayout.HelpBox("Your Global Portal Settings are currently overriding the mask", MessageType.Warning); } EditorGUI.BeginChangeCheck(); TargetController.Mask = (Texture2D)EditorGUILayout.ObjectField( new GUIContent("Portal Mask", "The transparency mask to use on the Portal"), TargetController.Mask, typeof(Texture2D), false, GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { Undo.RecordObject(p.Mask, "Texture change"); p.Mask = TargetController.Mask; EditorUtility.SetDirty(p.Mask); EditorUtility.SetDirty(p); } } EditorGUI.BeginChangeCheck(); Material material = (Material)EditorGUILayout.ObjectField( new GUIContent("Portal Material", "The material to use for the Portal"), TargetController.PortalMaterial, typeof(Material), false, null); if (EditorGUI.EndChangeCheck()) { TargetMaterial = material; foreach (PortalController p in targets) { p.PortalMaterial = TargetController.PortalMaterial; } } EditorGUI.BeginChangeCheck(); TargetController.Enterable = EditorGUILayout.Toggle( new GUIContent("Enterable", "Is the Portal Enterable by Teleportable Objects?"), TargetController.Enterable); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.Enterable = TargetController.Enterable; } } EditorGUI.BeginChangeCheck(); TargetController.Is3D = EditorGUILayout.Toggle( new GUIContent("Portal is 3D Object", "Is the Portal a 3d object, such as a Crystal ball?"), TargetController.Is3D); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.Is3D = TargetController.Is3D; } } EditorGUI.BeginChangeCheck(); TargetController.Rendering = EditorGUILayout.Toggle( new GUIContent("Rendering Enabled", "Is the portal going to render?"), TargetController.Rendering, GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight)); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.Rendering = TargetController.Rendering; } } EditorGUI.BeginChangeCheck(); TargetController.DetectionScale = EditorGUILayout.Slider( new GUIContent("Detection zone Scale", "The scale of the portal detection zone."), TargetController.DetectionScale, 0.1f, 10f); if (EditorGUI.EndChangeCheck()) { foreach (PortalController p in targets) { p.DetectionScale = TargetController.DetectionScale; } } if (TargetController.DetectionScale < 1) { EditorGUILayout.HelpBox( "It is recommended that you do not set the detection scale" + "below 1, as lower values have a very high chance of not" + "detecting objects at all as they may move too quickly", MessageType.Warning); } //Show the Portal Material Inspector if (Application.isPlaying) { return; } } catch { //Just for cleanliness } finally { if (!SKSGlobalRenderSettings.Preview) { //CleanupTemp(); } } TargetMeshRenderer.gameObject.SetActive(false); //Cache state of random UnityEngine.Random.State seed = UnityEngine.Random.state; //Make color deterministic based on ID UnityEngine.Random.InitState(TargetController.GetInstanceID()); TargetController.color = UnityEngine.Random.ColorHSV(0, 1, 0.48f, 0.48f, 0.81f, 0.81f); //Reset the random UnityEngine.Random.state = seed; }