void SaveAsTile(GameObject go)
        {
            var builder = FindObjectOfType <LevelBuilder>();

            if (!builder)
            {
                Debug.LogWarning("Create a level builder in scene."); return;
            }
            if (!builder.tileSet)
            {
                Debug.LogWarning("Add a tileatlas to builder."); return;
            }
            var newTile = TileObject.CreateNewTileFileFromPrefabs(go);

            builder.tileSet.tiles.Add(newTile);
            builder.tileSet.GetDictionaryFromList();
        }
示例#2
0
 public void RemoveFromAtlas(TileObject tile)
 {
     foreach (var layer in layers)
     {
         if (layer.layerObjects.Contains(tile))
         {
             RemoveTileFromLayer(tile, layer);
         }
     }
     TileFromGuid.Remove(tile.guid);
     tiles.Remove(tile);
     if (AssetDatabase.IsSubAsset(tile))
     {
         AssetDatabase.RemoveObjectFromAsset(tile);
     }
     UnityEditor.EditorUtility.SetDirty(this);
     AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this));
 }
        public void RemovePlacedTiles(TileObject tile, int layerIndex)
        {
            Undo.RegisterCompleteObjectUndo(this, "Before RemovedPlaced Tiles");
            List <int3> keysToRemove = new List <int3>();

            foreach (var kvp in layers[layerIndex])
            {
                if (kvp.Value.tileObject == tile)
                {
                    if (kvp.Value.placedObject)
                    {
                        Undo.DestroyObjectImmediate(kvp.Value.placedObject);
                        DestroyImmediate(kvp.Value.placedObject);
                    }
                    keysToRemove.Add(kvp.Key);
                }
            }
            foreach (var key in keysToRemove)
            {
                layers[layerIndex].Remove(key);
            }
        }
        void DrawMultipleTiles(int3 startPosition, int3 endPosition, TileObject tile, TileAtlas.TagLayer layer)
        {
            int3 brushSize   = tile.GetSize(layer.rasterSize);
            int3 minPosition = math.min(startPosition, endPosition);
            int3 maxPosition = math.max(startPosition, endPosition);
            int  widthX      = Mathf.FloorToInt((maxPosition.x - minPosition.x) / brushSize.x);
            int  widthZ      = Mathf.FloorToInt((maxPosition.z - minPosition.z) / brushSize.z);

            for (int x = 0; x <= widthX; x++)
            {
                for (int z = 0; z <= widthZ; z++)
                {
                    t.PlaceTile(tile.guid,
                                minPosition + new int3(
                                    x * brushSize.x,
                                    0,
                                    z * brushSize.z),
                                brushRotation,
                                layerIndex, layer, true); // <-- turn to false if performance becomes problematic
                }
            }
            //t.UpdateMultiple(minPosition - new int3(1, 0, 1), maxPosition + new int3(2,0,2), layerIndex);
        }
 public void ChangeTileToLayer(TileAtlas atlas, int i2, TileObject buttonTileObject)
 {
     Debug.Log(i2 + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
     atlas.layers[i2].layerObjects.Add(buttonTileObject);
 }
        private void OnGUI()
        {
            if (!CheckForRequirements())
            {
                return;
            }
            EditorGUILayout.BeginHorizontal();
            painting = GUILayout.Toggle(painting, "painting", "Button");
            EditorGUILayout.LabelField(new GUIContent(layerIndex + ":" + paletteIndex), GUILayout.Width(30));
            EditorGUILayout.EndHorizontal();
            brushRotation = EditorGUILayout.Vector3Field("Brush Direction", brushRotation);
            //if (painting)
            {
                //if (layerIndex < -1 || layerIndex >= t.tileSet.layers.Count) return;
                layerIndex   = Mathf.Clamp(layerIndex, -1, t.tileSet.layers.Count - 1);
                paletteIndex = Mathf.Clamp(paletteIndex, 0,
                                           layerIndex == -1 ? (t.tileSet.tiles.Count - 1) : (t.tileSet.layers[layerIndex].layerObjects.Count - 1));
                paletteIndex = Mathf.Max(0, paletteIndex);
                if (layerIndex == -1)
                {
                    selectedTileGuid = t.tileSet.tiles[paletteIndex].guid;
                }
                else if (t.tileSet.layers[layerIndex]?.layerObjects.Count > 0)
                {
                    selectedTileGuid = t.tileSet.layers[layerIndex]?.layerObjects[paletteIndex]?.guid;
                }
                if (!string.IsNullOrEmpty(selectedTileGuid))
                {
                    t.tileSet.TileFromGuid.TryGetValue(selectedTileGuid, out selectedTile);
                }
                if (!selectedTile)
                {
                    selectedTile     = t.tileSet.tiles[0];
                    selectedTileGuid = selectedTile.guid;
                }
            }
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Grid Visibility ");
            rasterVisibility = (RasterVisibility)EditorGUILayout.EnumPopup(rasterVisibility);
            rasterColor      = EditorGUILayout.ColorField(rasterColor);
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.BeginHorizontal();
            targetHeigth = EditorGUILayout.IntField("Heigth: ", targetHeigth);
            // activeLayer = EditorGUILayout.IntField("Layer:", activeLayer);
            EditorGUILayout.EndHorizontal();
            Event e = Event.current;

            if (e.type == EventType.DragUpdated || e.type == EventType.DragPerform)
            {
                Rect myRect = GUILayoutUtility.GetRect(100, 40, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
                GUI.Box(myRect, "Drag and Drop Prefabs to this Box!");
                if (myRect.Contains(e.mousePosition))
                {
                    if (e.type == EventType.DragUpdated)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    }
                    if (e.type == EventType.DragPerform)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        //Debug.Log(DragAndDrop.objectReferences.Length);
                        for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
                        {
                            var draggedTile = DragAndDrop.objectReferences[i] as TileObject;
                            if (!draggedTile)
                            {
                                var draggedGameObject = DragAndDrop.objectReferences[i] as GameObject;
                                draggedTile = TileObject.CreateNewTileFileFromPrefabs(false, draggedGameObject);
                                AssetDatabase.AddObjectToAsset(draggedTile, t.tileSet);
                            }
                            t.tileSet.tiles.Add(draggedTile);
                            if (layerIndex != -1)
                            {
                                t.tileSet.layers[layerIndex].layerObjects.Add(draggedTile);
                            }
                        }
                        t.tileSet.GetDictionaryFromList();
                        DragAndDrop.AcceptDrag();
                        e.Use();
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(t.tileSet));
                    }
                }
            }
            DrawPalette(t.tileSet, Event.current);
            if (GUILayout.Button("Select Atlas"))
            {
                Selection.activeObject = t.tileSet;
            }
            if (GUILayout.Button("Clear Level"))
            {
                t.ClearLevel();
            }
        }
        void TileRightClickMenu(Event e, TileObject buttonTileObject, TileAtlas atlas)
        {
            GenericMenu menu = new GenericMenu();

            menu.AddItem(new GUIContent("Select Tile Object"), false, () =>
            {
                Selection.activeObject = buttonTileObject;
            });

            menu.AddItem(new GUIContent("Select linked Prefab"), false, () =>
            {
                Selection.activeObject = buttonTileObject.prefabs[0];
            });

            for (int i = 0; i < atlas.layers.Count; i++)
            {
                if (i == layerIndex)
                {
                    continue;
                }
                int weird = i;
                menu.AddItem(new GUIContent("Move to Layer/Layer " + weird + " : " + atlas.layers[weird].name), false, () =>
                {
                    Debug.Log(weird + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
                    atlas.MoveTileToLayer(buttonTileObject, atlas.layers[weird]);
                    t.MoveExistingTilesToLayer(buttonTileObject, layerIndex, weird);
                });
            }

            menu.AddItem(new GUIContent("Remove/Clear Tiles from Layer"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                }
            });
            menu.AddItem(new GUIContent("Remove/Clear Tiles from Layer and move to Unsorted"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                    atlas.RemoveTileFromLayer(buttonTileObject, atlas.layers[layerIndex]);
                }
            });
            menu.AddItem(new GUIContent("Remove/Clear Tiles and remove from Atlas"), false, () =>
            {
                if (layerIndex > 0 && layerIndex < atlas.layers.Count)
                {
                    t.RemovePlacedTiles(buttonTileObject, layerIndex);
                    atlas.RemoveTileFromLayer(buttonTileObject, atlas.layers[layerIndex]);
                }
                atlas.RemoveFromAtlas(buttonTileObject);
            });
            // ----------------- disabled multi layer support for now and see if a need arises -----------------//
            //for (int i = 0; i < atlas.layers.Count; i++)
            //{
            //    if (i == layerIndex) continue;
            //    int weird = i;
            //    menu.AddItem(new GUIContent("Add to Layer/Layer " + weird +" : "+atlas.layers[weird].name), false, () =>
            //    {
            //        Debug.Log(weird + ":" + atlas.layers.Count + " obj: " + buttonTileObject.name);
            //        atlas.MoveTileToLayer(buttonTileObject, atlas.layers[weird], true);
            //    });
            //}
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Move to and create new Layer"), false, () =>
            {
                atlas.AddTagLayer();
                atlas.MoveTileToLayer(buttonTileObject, atlas.layers[atlas.layers.Count - 1]);
            });
            menu.ShowAsContext();

            e.Use();
        }
        void DrawPalette(TileAtlas atlas, Event e)
        {
            TileAtlas.TagLayer activeLayer = layerIndex == -1 ? atlas.defaultLayer : (layerIndex < atlas.layers.Count) ? atlas.layers[layerIndex] : atlas.defaultLayer;
            //DragTest
            //Rect myRect = GUILayoutUtility.GetRect(100, 40, GUILayout.ExpandWidth(true));
            //GUI.Box(myRect, "Drag and Drop Prefabs to this Box!");
            //if (myRect.Contains(e.mousePosition))
            //{
            //    if (e.type == EventType.DragUpdated)
            //    {
            //        DragAndDrop.visualMode = DragAndDropVisualMode.Move;
            //        //Debug.Log("Drag Updated!");
            //        e.Use();
            //    }
            //    else if (e.type == EventType.DragPerform)
            //    {
            //        DragAndDrop.AcceptDrag();
            //        Debug.Log("Drag Perform!");
            //        Debug.Log(DragAndDrop.objectReferences.Length);
            //        if (atlas.layers.Count > 0)
            //            for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
            //            {
            //                atlas.layers[0].layerObjects.Add(DragAndDrop.objectReferences[i] as TileObject);
            //            }
            //        e.Use();
            //    }
            //}
            //if (e.type == EventType.DragExited || e.type == EventType.MouseUp)
            //{
            //    //Debug.Log("Drag exited");
            //    DragAndDrop.PrepareStartDrag();
            //}
            //------
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            Color guiColor = GUI.color;

            //EditorGUIUtility.IconContent("Settings")
            if (GUILayout.Button("Ξ", GUILayout.Width(18), GUILayout.Height(activeLayer == atlas.defaultLayer ? 60 : 30)))
            {
                layerIndex = -1;
            }
            for (int i = 0; i < atlas.layers.Count; i++)
            {
                int index = i;
                GUI.color = atlas.layers[i].color;
                Rect buttonRect = GUILayoutUtility.GetRect(new GUIContent(i.ToString()), "Button", GUILayout.Width(18), GUILayout.Height(activeLayer == atlas.layers[i] ? 60 : 30));
                if (GUI.Button(buttonRect, i.ToString()))
                {
                    layerIndex = i;
                    if (e.button == 1)
                    {
                        LayerRightClickMenu(e, index, atlas);
                    }
                }
            }
            GUI.color = guiColor;
            if (GUILayout.Button("+", GUILayout.Width(18), GUILayout.Height(18)))
            {
                atlas.AddTagLayer();
            }
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            if (activeLayer != atlas.defaultLayer)
            {
                bool changedBefore = GUI.changed;
                activeLayer.name = EditorGUILayout.TextField(activeLayer.name);
                if (!changedBefore && GUI.changed)
                {
                    UnityEditor.EditorUtility.SetDirty(atlas);
                }
            }
            else
            {
                EditorGUILayout.HelpBox("Unsorted objects, rightclick and move to a layer to use.", MessageType.Info, true);
            }

            if (layerIndex >= 0 && layerIndex < atlas.layers.Count)
            {
                //activeLayer.rasterSize = EditorGUILayout.Vector3Field("raster ", activeLayer.rasterSize);
                bool changedBefore = GUI.changed;
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Rastersize");
                activeLayer.rasterSize.x = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.x);
                activeLayer.rasterSize.y = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.y);
                activeLayer.rasterSize.z = EditorGUILayout.DelayedFloatField(activeLayer.rasterSize.z);
                EditorGUILayout.EndHorizontal();
                if (!changedBefore && GUI.changed)
                {
                    t.UpdateTilePositionsOnLayer(activeLayer, layerIndex);
                }
            }

            if (activeLayer != atlas.defaultLayer && activeLayer.layerObjects.Count == 0)
            {
                EditorGUILayout.HelpBox("Drag and Drop Tiles here.", MessageType.Info, true); return;
            }

            //-----
            EditorGUILayout.Vector2Field("scroll", paletteScroll);
            float columnCount = 4f;
            float panelSize   = (position.width - 60) / columnCount;

            paletteScroll = EditorGUILayout.BeginScrollView(paletteScroll);
            List <GUIContent> paletteIcons     = new List <GUIContent>();
            float             enumerationCount = 0;

            if (activeLayer == atlas.defaultLayer)
            {
                foreach (var atlasTile in atlas.TileFromGuid.Values)
                {
                    // Get a preview for the prefab
                    if (!atlasTile)
                    {
                        continue;
                    }

                    Vector2 yValues = new Vector2(Mathf.Floor(enumerationCount / columnCount) * panelSize,
                                                  Mathf.Floor(enumerationCount / columnCount) * panelSize + panelSize);
                    if (yValues.x < paletteScroll.y - panelSize || yValues.y > paletteScroll.y + panelSize * 4 + panelSize) //(atlas.tiles.Count > maximumPreviewImages)
                    {
                        paletteIcons.Add(new GUIContent(atlasTile.name));
                    }
                    else
                    {
                        Texture2D texture = null;
                        if (atlasTile.prefabs.Length != 0)
                        {
                            texture = AssetPreview.GetAssetPreview(atlasTile.prefabs[0]);
                        }
                        paletteIcons.Add(texture ? new GUIContent(texture) : new GUIContent("No Preview Available"));
                    }
                    enumerationCount++;
                }
                if (paletteIcons.Count == 0)
                {
                    EditorGUILayout.HelpBox("No unsorted tiles in atlas", MessageType.Info);
                }
            }
            else
            {
                foreach (var atlasTile in activeLayer.layerObjects)
                {
                    // Get a preview for the prefab
                    if (!atlasTile)
                    {
                        continue;
                    }
                    Vector2 yValues = new Vector2(Mathf.Floor(enumerationCount / columnCount) * panelSize,
                                                  Mathf.Floor(enumerationCount / columnCount) * panelSize + panelSize);
                    if (yValues.x < paletteScroll.y - panelSize || yValues.y > paletteScroll.y + panelSize * 4 + panelSize)
                    {
                        paletteIcons.Add(new GUIContent(atlasTile.name));
                        //paletteIcons.Add(new GUIContent($"{enumerationCount} : {yValues}"));
                    }
                    else
                    {
                        Texture2D texture = null;
                        if (atlasTile.prefabs.Length != 0)
                        {
                            texture = AssetPreview.GetAssetPreview(atlasTile.prefabs[0]);
                        }
                        paletteIcons.Add(texture ? new GUIContent(texture) : new GUIContent("No Preview Available"));
                    }
                    enumerationCount++;
                }
            }

            if (activeLayer != atlas.defaultLayer)
            {
                paletteIcons.Add(EditorGUIUtility.IconContent("Toolbar Plus"));
            }
            // Display the grid

            //paletteIndex = GUILayout.SelectionGrid(paletteIndex, paletteIcons.ToArray(), 4, GUILayout.Width(position.width-38));

            EditorGUILayout.BeginHorizontal();
            GUIStyle iconLabel = new GUIStyle("Label");

            iconLabel.alignment        = TextAnchor.UpperCenter;
            iconLabel.normal.textColor = Color.grey;
            for (int i = 0; i < paletteIcons.Count; i++)
            {
                Rect       buttonRect       = GUILayoutUtility.GetRect(paletteIcons[i], "Button", GUILayout.Width(panelSize), GUILayout.Height(panelSize));
                TileObject buttonTileObject = activeLayer == atlas.defaultLayer ? atlas.tiles[i] : i < activeLayer.layerObjects.Count ? activeLayer.layerObjects[i] : null;
                bool       clickHere        = false;
                if (buttonRect.Contains(e.mousePosition))
                {
                    switch (e.type)
                    {
                    //case EventType.MouseDrag:
                    //    DragAndDrop.PrepareStartDrag();

                    //    DragAndDrop.SetGenericData("TileObject", buttonTileObject);
                    //    DragAndDrop.objectReferences = new Object[] { buttonTileObject };
                    //    DragAndDrop.StartDrag("Drag");
                    //    break;
                    //case EventType.DragExited:
                    //    clickHere = true;
                    //    break;
                    case EventType.MouseDown:
                        clickHere = true;
                        break;
                    }
                }
                TileAtlas.TagLayer tileLayer = null;
                foreach (var layer in atlas.layers)
                {
                    if (layer.layerObjects.Contains(buttonTileObject))
                    {
                        tileLayer = layer;
                        break;
                    }
                }

                GUI.backgroundColor = tileLayer != null?tileLayer.color:guiColor;
                GUI.Toggle(buttonRect, paletteIndex == i, paletteIcons[i], "Button");
                if (buttonTileObject)
                {
                    GUI.Label(buttonRect, buttonTileObject.name, iconLabel);
                }
                if (clickHere)
                {
                    paletteIndex = i;
                    if (activeLayer == atlas.defaultLayer)
                    {
                        Selection.activeObject = buttonTileObject;
                    }
                    if (activeLayer != atlas.defaultLayer && i == paletteIcons.Count - 1)
                    {
                        AddTileToLayerMenu(atlas, activeLayer, e);
                        paletteIndex = 0;
                    }
                    else if (e.button == 1)  // rightclick
                    {
                        TileRightClickMenu(e, buttonTileObject, atlas);
                    }
                }
                if (i % (int)(columnCount) == columnCount - 1)// && i != 0)
                {
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.BeginHorizontal();
                }
            }
            EditorGUILayout.EndHorizontal();

            if (activeLayer == atlas.defaultLayer)
            {
                selectedTileGuid = atlas.tiles[paletteIndex].guid;
            }
            else
            {
                if (paletteIndex >= activeLayer.layerObjects.Count)
                {
                    paletteIndex = 0;
                }
                if (activeLayer.layerObjects[paletteIndex])
                {
                    selectedTileGuid = activeLayer.layerObjects[paletteIndex].guid;
                }
                else
                {
                    selectedTileGuid = "";
                }
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndHorizontal();
            GUI.backgroundColor = guiColor;
        }
示例#9
0
        public static TileObject TileFromSprite(Sprite sprite)
        {
            var go = PrefabFromSprite(sprite);

            return(TileObject.CreateNewTileFileFromPrefabs(go));
        }
示例#10
0
        public static List <TileObject> GenerateFromSpriteSheet(string path, bool isRelativePath)
        {
            string filePath = isRelativePath ? path : ("Assets" + path.Substring(Application.dataPath.Length));

            List <TileObject> export = new List <TileObject>();

            var    tex        = AssetDatabase.LoadAssetAtPath <Texture2D>(filePath);
            string folderPath = filePath.Substring(0, filePath.LastIndexOf("/") + 1) + tex.name;

            EnsureFolders(filePath, tex.name);
            Material mat = MaterialFromTex(tex, folderPath);

            Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).OfType <Sprite>().ToArray();
            //Mesh mesh = new Mesh();
            //mesh.subMeshCount = sprites.Length;
            //List<Vector3> allVerts = new List<Vector3>();
            //List<Vector2> allUVs = new List<Vector2>();
            //List<ContainerForSubMesh> submeshes = new List<ContainerForSubMesh>();
            for (int index = 0; index < sprites.Length; index++)
            {
                var sprite = sprites[index];
                Debug.Log("Creating " + sprite.name);
                //foreach (var vert in sprite.vertices)
                //    Debug.Log("vert: (" + vert.x.ToString("0.00") + ";" + vert.y.ToString("0.00") + ")");
                //foreach (var uv in sprite.uv)
                //    Debug.Log("uv: (" + uv.x.ToString("0.00") + ";" + uv.y.ToString("0.00") + ")");
                //return;

                Vector3[] verts = new Vector3[sprite.vertices.Length];
                Vector2[] uvs   = new Vector2[sprite.uv.Length];
                for (int i = 0; i < verts.Length; i++)
                {
                    verts[i] = new Vector3(sprite.vertices[i].x, 0f, sprite.vertices[i].y);
                    uvs[i]   = sprite.uv[i];
                }
                int[] faces = new int[sprite.triangles.Length];
                for (int i = 0; i < faces.Length; i++)
                {
                    //Debug.Log(index + " : face " + sprite.triangles[i]);
                    faces[i] = sprite.triangles[i];// + vertOffset;
                }

                Mesh mesh = new Mesh();
                mesh.name = sprite.name;
                mesh.SetVertices(verts);
                mesh.SetUVs(0, uvs);
                mesh.SetTriangles(faces, 0);
                AssetDatabase.CreateAsset(mesh, folderPath + "/meshes/" + sprite.name + ".asset");
                AssetDatabase.SaveAssets();
                GameObject meshHolder = new GameObject();
                var        filter     = meshHolder.AddComponent <MeshFilter>();
                filter.sharedMesh = AssetDatabase.LoadAssetAtPath <Mesh>(folderPath + "/meshes/" + sprite.name + ".asset");
                var rend = meshHolder.AddComponent <MeshRenderer>();
                rend.sharedMaterial = mat;
                var go = PrefabUtility.SaveAsPrefabAsset(meshHolder, folderPath + "/prefabs/" + sprite.name + ".prefab");
                export.Add(TileObject.CreateNewTileFileFromPrefabs(go));
                GameObject.DestroyImmediate(meshHolder);
                //submeshes.Add(new ContainerForSubMesh(verts, uvs, faces));
                //allVerts.AddRange(verts);
                //allUVs.AddRange(uvs);
            }
            //mesh.SetVertices(allVerts);
            //mesh.SetUVs(0, allUVs);
            //for (int i = 0; i < submeshes.Count; i++)
            //{
            //    mesh.SetTriangles(submeshes[i].faces, i);
            //    //submeshes[i].DrawDebugMesh(3f);
            //}
            //string savePath = filePath.Substring(0, filePath.LastIndexOf("/") + 1) + tex.name + "-mesh.asset";
            //AssetDatabase.CreateAsset(mesh, savePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            return(export);
        }