/// <summary> /// To read the existing level file and set the scene for edit it /// </summary> /// <param name="editionInfo"></param> public void readLevelFile(EditionInfo editionInfo) { StreamReader sr = new StreamReader(SettingsManager.LevelsFilesPath + "/" + editionInfo.levelName + ".txt"); string line = sr.ReadLine(); int columns = int.Parse(line.Split('x')[0]); int rows = int.Parse(line.Split('x')[1]);//if needs editionInfo.levelSize = new Vector2(columns, rows); generateBackTiles(editionInfo.levelSize); int row = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); string[] cells = line.Split(';'); for (int colum = 0; colum < columns; colum++) { string tileName; string[] cellsTiles = cells[colum].Split('-');//The two tiles in this position: 0 if there is nothing if (cellsTiles[0] != "0") { tileName = TileCodification.getTileName(cellsTiles[0]); instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { //Instantiate nothing } } else { if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { //Instantiate nothing } } } row++; } sr.Close(); }
/// <summary> /// To save the level /// </summary> /// <param name="levelName">the level name</param> /// <param name="levelSize">level size in terms of number of rows and columns</param> /// <param name="tilesPlaced">The tiles placed</param> public bool saveLevel(EditionInfo editInformation) { //string levelName, Vector2 levelSize, List<TileInEditorWorldSpace.TileInWorldSpace> tilesPlaced if (verifSpawnPoint(editInformation.tilesPlaced))//If there is one spawn point { if (verifCratesPointAndCrates(editInformation.tilesPlaced)) { if (editInformation.reeditingLevel) { setLevelPath("temp_"); } try { StreamWriter sw = new StreamWriter(levelPath); sw.WriteLine(editInformation.levelSize.x + "x" + editInformation.levelSize.y); for (int row = (int)editInformation.levelSize.y - 1; row >= 0; row--) { string line = ""; for (int colum = 0; colum <= editInformation.levelSize.x - 1; colum++) { bool swt1 = false; int tileIndex = 0; Vector3 searchTileOnPosition = new Vector3(TileCodification.TileSize * colum, TileCodification.TileSize * row, 0); while (tileIndex < editInformation.tilesPlaced.Count && swt1 == false) { if (editInformation.tilesPlaced[tileIndex].position == searchTileOnPosition)//Look for the actual tile, placed at the position (tileSize*row,tileSize*colum,0) { swt1 = true; } else { tileIndex++; } } if (swt1) //If found one { if (editInformation.tilesPlaced[tileIndex].tileGameObject.tag == "Ground") //Only if the Tile is a Ground Tile, we search again for another possible tile that could be over it { //We make the second Search omiting the one we found bool swt2 = false; int otherTileIndex = 0; while (otherTileIndex < editInformation.tilesPlaced.Count && !swt2) { if (editInformation.tilesPlaced[otherTileIndex].position == searchTileOnPosition && otherTileIndex != tileIndex)//Look for the actual tile, placed at the same position { swt2 = true; } else { otherTileIndex++; } } if (swt2)//if we found another tile over the first one { string fistTileCode = TileCodification.getTileCode(editInformation.tilesPlaced[tileIndex].tileName); string secondTileCode = TileCodification.getTileCode(editInformation.tilesPlaced[otherTileIndex].tileName); if (colum == 0) { line = fistTileCode + "-" + secondTileCode; } else { line = line + ";" + fistTileCode + "-" + secondTileCode; } } else//Dind't found the posible second Tile { if (colum == 0) { line = TileCodification.getTileCode(editInformation.tilesPlaced[tileIndex].tileName) + "-0"; } else { line = line + ";" + TileCodification.getTileCode(editInformation.tilesPlaced[tileIndex].tileName) + "-0"; } } } else//Found a tile that isn't a ground tile { if (colum == 0) { line = "0-" + TileCodification.getTileCode(editInformation.tilesPlaced[tileIndex].tileName); } else { line = line + ";0-" + TileCodification.getTileCode(editInformation.tilesPlaced[tileIndex].tileName); } } } else//There is no tile there, so it's 0 { if (colum == 0) { line = "0-0"; } else { line = line + ";0-0"; } } } //Debug.Log(line); sw.WriteLine(line); } sw.Close(); if (editInformation.reeditingLevel) { string sourceFileName = levelPath; setLevelPath(editionInfo.levelName); string destFileName = levelPath; File.Delete(destFileName); File.Move(sourceFileName, destFileName); File.Delete(sourceFileName); } ShowMessage.showMessageText("World Saved Succesfully", MessageType.Confirmation); return(true); } catch (Exception e) { Debug.Log(e.ToString()); ShowMessage.showMessageText(e.ToString(), MessageType.Error); } } } return(false); }
/// <summary> /// Load the world /// </summary> /// <param name="fileName">The world file </param> /// <param name="worldType">the world type (if GameWorld or MyWorld)</param> void readWorldFile(string fileName, WorldType worldType) { GameObject worldGameObject = new GameObject("World"); if (worldType.Equals(WorldType.MyWorld)) { StreamReader sr = new StreamReader(MapEditor.WorldsFilesPath + "/" + fileName); string line = sr.ReadLine(); string[] worldParameters = line.Split(';'); string[] backgrounds = sr.ReadLine().Split(';'); int rows = int.Parse(worldParameters[0].Split('x')[0]);//if needs int columns = int.Parse(worldParameters[0].Split('x')[1]); setBackground(backgrounds[0], backgrounds[1], columns, rows); int row = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); string[] vec = line.Split(';'); for (int colum = 0; colum < columns; colum++) { string tile1Code = vec[colum].Split('-')[0]; string tile2Code = vec[colum].Split('-')[1]; if (!tile1Code.Equals("0")) { //No hay forma que el tileCode sea un spawn point, eso se controla en la creacion del mundo y en el archivo, entonces instacinamos con seguridad string tileName = TileCodification.getTileName(tile1Code); GameObject tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; GameObject tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); if (!tile2Code.Equals("0")) { //Aqui si puede haber spawn Points if (!tile2Code.Equals(TileCodification.getTileCode("Spawn Point"))) { tileName = TileCodification.getTileName(tile2Code); tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); if (tile1Code.Substring(0, 1) == "b" && tile2Code.Substring(0, 1) == "f")//also could be use TileCodification.getTileLayer(TileCodification.getTileName(tile1Code)) to get the Tiles layers { tile.layer = LayerMask.NameToLayer("Ground"); } } else { GameObject sp = new GameObject("Spawn Point " + spawnPointsList.Count); sp.transform.position = new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f); spawnPointsList.Add(sp.transform); } } else { //Instantiate nothing } } else { if (!tile2Code.Equals("0")) { if (!tile2Code.Equals(TileCodification.getTileCode("Spawn Point"))) { string tileName = TileCodification.getTileName(tile2Code); GameObject tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; GameObject tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); } else { GameObject sp = new GameObject("Spawn Point " + spawnPointsList.Count); sp.transform.position = new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f); spawnPointsList.Add(sp.transform); } } else { //Instantiate nothing } } } row++; } sr.Close(); } else { //Reading a txt file inside resources folder of the project in adroid build (Android), also works on editor so no problem TextAsset path = Resources.Load <TextAsset>("Files/World Files/" + fileName); using (StreamReader sr = new StreamReader(new MemoryStream(path.bytes))) { string line = sr.ReadLine(); string[] worldParameters = line.Split(';'); string[] backgrounds = sr.ReadLine().Split(';'); int rows = int.Parse(worldParameters[0].Split('x')[0]);//if needs int columns = int.Parse(worldParameters[0].Split('x')[1]); setBackground(backgrounds[0], backgrounds[1], columns, rows); int row = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); string[] vec = line.Split(';'); for (int colum = 0; colum < columns; colum++) { string tile1Code = vec[colum].Split('-')[0]; string tile2Code = vec[colum].Split('-')[1]; if (!tile1Code.Equals("0")) { //No hay forma que el tileCode sea un spawn point, eso se controla en la creacion del mundo y en el archivo, entonces instacinamos con seguridad string tileName = TileCodification.getTileName(tile1Code); GameObject tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; GameObject tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); if (!tile2Code.Equals("0")) { //Aqui si puede haber spawn Points if (!tile2Code.Equals(TileCodification.getTileCode("Spawn Point"))) { tileName = TileCodification.getTileName(tile2Code); tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); if (tile1Code.Substring(0, 1) == "b" && tile2Code.Substring(0, 1) == "f")//also could be use TileCodification.getTileLayer(TileCodification.getTileName(tile1Code)) to get the Tiles layers { tile.layer = LayerMask.NameToLayer("Ground"); } } else { GameObject sp = new GameObject("Spawn Point " + spawnPointsList.Count); sp.transform.position = new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f); spawnPointsList.Add(sp.transform); } } else { //Instantiate nothing } } else { if (!tile2Code.Equals("0")) { if (!tile2Code.Equals(TileCodification.getTileCode("Spawn Point"))) { string tileName = TileCodification.getTileName(tile2Code); GameObject tilePrefab = Resources.Load("Tiles/" + tileName) as GameObject; GameObject tile = Instantiate(tilePrefab, new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f), Quaternion.identity) as GameObject; tile.name = tileName; tile.transform.SetParent(worldGameObject.transform); } else { GameObject sp = new GameObject("Spawn Point " + spawnPointsList.Count); sp.transform.position = new Vector3(blocksSize * colum, blocksSize * ((rows - 1) - row), 0f); spawnPointsList.Add(sp.transform); } } else { //Instantiate nothing } } } row++; } sr.Close(); } } }
// Update is called once per frame void Update() { horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); jump = CrossPlatformInputManager.GetButton("Jump"); attack = CrossPlatformInputManager.GetButtonDown("Fire1"); #if UNITY_ANDROID && !UNITY_EDITOR if (Input.touchCount == 1) { Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { clickTime = Time.timeSinceLevelLoad; clicked = true; mousePosition = touch.position; hit = Physics2D.Raycast(new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y), Vector2.zero, 0); } if (clicked && Time.timeSinceLevelLoad - clickTime > 0.3) { //LONG PRESS if (hit) { if (hit.transform.tag.Equals("Tile")) { if (Vector2.Distance(myCharacter.transform.position, hit.transform.position) <= myCharacter.destroyLimitRadius) { Debug.Log("Esta en el Limite"); Tile tile = hit.transform.GetComponent <Tile>(); tile.PressedTile(); } else { Debug.Log("Esta Muy Lejos"); } } } clicked = false;//Because we dont want to execute this code anymore, just once } if (touch.phase == TouchPhase.Ended) { clicked = false; if (Time.timeSinceLevelLoad - clickTime < 0.3) { //SHORT CLICK //BUILD SYSTEM if (hit)//if raycast hit something { //FALTA VERIFICAR QUE NO ESTE SOBRE UN UI Vector2 mousePositionInWorldSpace = new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y); if (hit.transform.gameObject.layer.Equals(LayerMask.NameToLayer("Background Tile"))) { //Instanciar el bloque, si no es otra background if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { if (TileCodification.getTileLayer(myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) != LayerMask.NameToLayer("Background Tile")) { GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; tile.GetComponent <Tile>().canPlaceOverIt = false; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); if (tile.layer.Equals(LayerMask.NameToLayer("Front Tile"))) { tile.layer = LayerMask.NameToLayer("Ground"); } } } } else { Debug.Log("No puede construir tan lejos"); } } else if (hit.transform.gameObject.layer.Equals(LayerMask.NameToLayer("Special Tile"))) { //Instanciar el bloque solo si es es una FrtonTile if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { if (TileCodification.getTileLayer(myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) == LayerMask.NameToLayer("Front Tile"))//only if is a front tile { if (hit.transform.GetComponent <Tile>().canPlaceOverIt) { Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; tile.GetComponent <Tile>().canPlaceOverIt = false; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); } } } } else { Debug.Log("No puede construir tan lejos"); } } else { //Do nothing, can't instantiate tile over the other layers } } else//not hit something { if (!EventSystem.current.IsPointerOverGameObject())//isn't over an UI element { //We transform de mouse position on a World position Vector2 mousePositionInWorldSpace = new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y); //We verify if the click is on player destry Limit radius if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); } } else { Debug.Log("No puede construir tan lejos"); } } } } else { //WE RELEASE LONG PRESS Debug.Log("End long click"); if (hit) { if (hit.transform.tag.Equals("Tile")) { if (Vector2.Distance(myCharacter.transform.position, hit.transform.position) <= myCharacter.destroyLimitRadius) { Tile tile = hit.transform.GetComponent <Tile>(); tile.ReleasedTile(); } } } } } } #elif UNITY_EDITOR if (Input.GetMouseButtonDown(0)) { clickTime = Time.timeSinceLevelLoad; clicked = true; mousePosition = Input.mousePosition; hit = Physics2D.Raycast(new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y), Vector2.zero, 0); } if (clicked && (Time.timeSinceLevelLoad - clickTime) > 0.3) { // long click effect Debug.Log("Long pressing"); if (hit) { if (hit.transform.tag.Equals("Tile")) { if (Vector2.Distance(myCharacter.transform.position, hit.transform.position) <= myCharacter.destroyLimitRadius) { Debug.Log("Esta en el Limite"); Tile tile = hit.transform.GetComponent <Tile>(); tile.PressedTile(); } else { Debug.Log("Esta Muy Lejos"); } } } clicked = false;//Because we dont want to execute this code anymore, just once } if (Input.GetMouseButtonUp(0)) { clicked = false; if ((Time.timeSinceLevelLoad - clickTime) < 0.3) { // short click effect Debug.Log("Short click"); //BUILD SYSTEM if (hit)//if raycast hit something { //FALTA VERIFICAR QUE NO ESTE SOBRE UN UI Vector2 mousePositionInWorldSpace = new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y); if (hit.transform.gameObject.layer.Equals(LayerMask.NameToLayer("Background Tile"))) { //Instanciar el bloque, si no es otra background if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { if (TileCodification.getTileLayer(myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) != LayerMask.NameToLayer("Backgroun Tile")) { Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; tile.GetComponent <Tile>().canPlaceOverIt = false; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); if (tile.layer.Equals(LayerMask.NameToLayer("Front Tile"))) { tile.layer = LayerMask.NameToLayer("Ground"); } } } } else { Debug.Log("No puede construir tan lejos"); } } else if (hit.transform.gameObject.layer.Equals(LayerMask.NameToLayer("Special Tile"))) { //Instanciar el bloque solo si es es una FrtonTile if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { if (TileCodification.getTileLayer(myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) == LayerMask.NameToLayer("Front Tile"))//only if is a front tile { if (hit.transform.GetComponent <Tile>().canPlaceOverIt) { Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; tile.GetComponent <Tile>().canPlaceOverIt = false; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); } } } } else { Debug.Log("No puede construir tan lejos"); } } else { //Do nothing, can't instantiate tile over the other layers } } else//not hit something { if (!EventSystem.current.IsPointerOverGameObject())//isn't over an UI element { //We transform de mouse position on a World position Vector2 mousePositionInWorldSpace = new Vector2(Camera.main.ScreenToWorldPoint(mousePosition).x, Camera.main.ScreenToWorldPoint(mousePosition).y); //We verify if the click is on player destry Limit radius if (Vector2.Distance(myCharacter.transform.position, mousePositionInWorldSpace) <= myCharacter.destroyLimitRadius) { if (myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex] != null && myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].TypeOfItem.Equals(ItemType.Placeable)) { GameObject tilePrefab = Resources.Load("Tiles/" + myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName) as GameObject; Vector3 objecPos = builtTilePosition(mousePositionInWorldSpace); GameObject tile = Instantiate(tilePrefab, objecPos, Quaternion.identity) as GameObject; myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemQuantity--; tile.name = myCharacter.PlayerInventory[myCharacter.selectedInventoryIndex].ItemName; tile.transform.SetParent(GameObject.Find("World").transform); } } else { Debug.Log("No puede construir tan lejos"); } } } } else { //We release Long press if (hit) { if (hit.transform.tag.Equals("Tile")) { if (Vector2.Distance(myCharacter.transform.position, hit.transform.position) <= myCharacter.destroyLimitRadius) { Tile tile = hit.transform.GetComponent <Tile>(); tile.ReleasedTile(); } } } } } #endif }
/// <summary> /// Reads level file and load tiles in world space /// </summary> /// <param name="fileName">The level file</param> private void loadLevel(string fileName) { tilesGameObject = new GameObject("Tiles"); if (runningLevel.levelType == LevelType.SokobanLevel) { //worldsFilesPath = Application.dataPath + "/Resources/Files/Level Files"; //Reading a txt file inside resources folder of the project in adroid build (Android), also works on editor so no problem TextAsset path = Resources.Load <TextAsset>("Files/Levels Files/" + fileName); using (StreamReader sr = new StreamReader(new MemoryStream(path.bytes))) { string line = sr.ReadLine(); int columns = int.Parse(line.Split('x')[0]); int rows = int.Parse(line.Split('x')[1]);//if needs int row = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); string[] cells = line.Split(';'); for (int colum = 0; colum < columns; colum++) { string tileName; string[] cellsTiles = cells[colum].Split('-');//The two tiles in this position: 0 if there is nothing if (cellsTiles[0] != "0") { tileName = TileCodification.getTileName(cellsTiles[0]); instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); if (tileName != "Spawn Point") { if (tileName.Contains("Crate Point")) { runningLevel.levelCratesPoints++; } instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { spawnPoint = new GameObject("Spawn Point"); spawnPoint.transform.position = new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row)); } } else { //Instantiate nothing } } else { if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); if (tileName != "Spawn Point") { if (tileName.Contains("Crate Point")) { runningLevel.levelCratesPoints++; } instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { spawnPoint = new GameObject("Spawn Point"); spawnPoint.transform.position = new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row)); } } else { //Instantiate nothing } } } row++; } sr.Close(); } } else if (runningLevel.levelType == LevelType.MyLevel) { StreamReader sr = new StreamReader(SettingsManager.LevelsFilesPath + "/" + fileName); string line = sr.ReadLine(); int columns = int.Parse(line.Split('x')[0]); int rows = int.Parse(line.Split('x')[1]);//if needs int row = 0; while (!sr.EndOfStream) { line = sr.ReadLine(); string[] cells = line.Split(';'); for (int colum = 0; colum < columns; colum++) { string tileName; string[] cellsTiles = cells[colum].Split('-');//The two tiles in this position: 0 if there is nothing if (cellsTiles[0] != "0") { tileName = TileCodification.getTileName(cellsTiles[0]); instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); if (tileName != "Spawn Point") { if (tileName.Contains("Crate Point")) { runningLevel.levelCratesPoints++; } instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { spawnPoint = new GameObject("Spawn Point"); spawnPoint.transform.position = new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row)); } } else { //Instantiate nothing } } else { if (cellsTiles[1] != "0") { tileName = TileCodification.getTileName(cellsTiles[1]); if (tileName != "Spawn Point") { if (tileName.Contains("Crate Point")) { runningLevel.levelCratesPoints++; } instantiateTile(tileName, new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row), 0f)); } else { spawnPoint = new GameObject("Spawn Point"); spawnPoint.transform.position = new Vector3(TileCodification.TileSize * (colum), TileCodification.TileSize * ((rows - 1) - row)); } } else { //Instantiate nothing } } } row++; } sr.Close(); } }
/// <summary> /// Saves the world file at worlds folder /// </summary> /// <param name="tilesPlaced">The List of tiles placed at the world</param> /// <param name="sizeX">Number of Columns</param> /// <param name="sizeY">Number of rowns</param> /// <param name="worldName">The world Name (World file name)</param> public static void saveWorld(List <mapEditorMenuScript.TileInWorldSpace> tilesPlaced, int sizeX, int sizeY, string worldName) { if (Directory.Exists(worldsFilesPath))//If the folder already exist { if (worldName != "") { #if UNITY_ANDROID && !UNITY_EDITOR string worldPath = worldsFilesPath + "/" + worldName + ".txt"; #elif UNITY_EDITOR string worldPath = worldsFilesPath + "\\" + worldName + ".txt"; #endif if (!File.Exists(worldPath))//If there isn't the same world { //Debug.Log("Bien, el mundo no existe"); if (verifHasSpawnPoints(tilesPlaced))//If there is at least one spawn point { //Debug.Log("Tiene Spawn Point"); try { StreamWriter sw = new StreamWriter(worldPath); sw.WriteLine(sizeY + "x" + sizeX); sw.WriteLine("Sky;Underground");//Top background and bottom background for (int i = sizeY - 1; i >= 0; i--) { string line = string.Empty; for (int j = 0; j <= sizeX - 1; j++) { bool swt1 = false; int k = 0; while (k < tilesPlaced.Count && swt1 == false) { if (tilesPlaced[k].Position.Equals(new Vector3(blockSize * j, blockSize * i, 0)))//Look for the actual tile, placed at the same position { swt1 = true; } else { k++; } } if (swt1) //If found one { if (TileCodification.getTileLayer(tilesPlaced[k].TileName) != LayerMask.NameToLayer("Front Tile")) //Solo se revisa si hay otro tile en la misma psicion si no es un Front Tile { //We make the second Search omiting the one we found bool swt2 = false; int l = 0; while (l < tilesPlaced.Count && !swt2) { if (tilesPlaced[l].Position.Equals(new Vector3(blockSize * j, blockSize * i, 0)) && l != k)//Look for the actual tile, placed at the same position { swt2 = true; } else { l++; } } if (swt2)//Encontro otra tile en la misma posicion { string tile1Code = TileCodification.getTileCode(tilesPlaced[k].TileName); string tile2Code = TileCodification.getTileCode(tilesPlaced[l].TileName); if (tile1Code.Substring(0, 1) == "b" && (tile2Code.Substring(0, 1) == "s" || tile2Code.Substring(0, 1) == "f")) { if (j == 0) { line = tile1Code + "-" + tile2Code; //line = tile1Code.Substring(0, 1) + "xx-" + tile2Code.Substring(0, 1) + "xx"; } else { line = line + ";" + tile1Code + "-" + tile2Code; //line= line+";"+ tile1Code.Substring(0, 1) + "xx-" + tile2Code.Substring(0, 1) + "xx"; } } else if (tile2Code.Substring(0, 1) == "b" && (tile1Code.Substring(0, 1) == "s" || tile1Code.Substring(0, 1) == "f")) { if (j == 0) { line = tile2Code + "-" + tile1Code; //line = tile2Code.Substring(0, 1) + "xx-" + tile1Code.Substring(0, 1) + "xx"; } else { line = line + ";" + tile2Code + "-" + tile1Code; //line= line+";"+ tile2Code.Substring(0, 1) + "xx-" + tile1Code.Substring(0, 1) + "xx"; } } else if (tile1Code.Substring(0, 1) == "s") //se infiere que la otra es f porque es la unica posibilidad { if (j == 0) { line = tile1Code + "-" + tile2Code; //line = tile1Code.Substring(0, 1) + "xx-" + tile2Code.Substring(0, 1) + "xx"; } else { line = line + ";" + tile1Code + "-" + tile2Code; //line= line+";"+ tile1Code.Substring(0, 1) + "xx-" + tile2Code.Substring(0, 1) + "xx"; } } else if (tile2Code.Substring(0, 1) == "s") //Se infiere que la otra es f { if (j == 0) { line = tile2Code + "-" + tile1Code; //line= tile2Code.Substring(0, 1) + "xx-" + tile1Code.Substring(0, 1) + "xx"; } else { line = line + ";" + tile2Code + "-" + tile1Code; //line= line+";"+ tile2Code.Substring(0, 1) + "xx-" + tile1Code.Substring(0, 1) + "xx"; } } else { Debug.Log("Error, condicion no validada"); Message.showMessageText("Error, condicion no validada"); } } else//Dind't found the posible second Tile { if (j == 0) { line = TileCodification.getTileCode(tilesPlaced[k].TileName) + "-0";//Codigo del tile //line = "xxx-0"; } else { line = line + ";" + TileCodification.getTileCode(tilesPlaced[k].TileName) + "-0"; //line = line + ";xxx-0"; } } } else//Found a Front Tile { if (j == 0) { line = "0-" + TileCodification.getTileCode(tilesPlaced[k].TileName);//Codigo del tile //line = "0-xxx"; } else { line = line + ";0-" + TileCodification.getTileCode(tilesPlaced[k].TileName); //line = line + ";0-xxx"; } } } else//There is no tile there, so it's 0 { if (j == 0) { line = "0-0"; } else { line = line + ";0-0"; } } } //Debug.Log(line); sw.WriteLine(line); } sw.Close(); Message.showMessageText("World Saved Succesfully", MessageType.OK); } catch (Exception e) { Message.showMessageText(e.ToString()); } } else { Message.showMessageText("There is no spawn point on the world, must be at least one", MessageType.Error, 5); } } else { Message.showMessageText("This World Already Exists, Change the Name", MessageType.Error, 3); } } else { Message.showMessageText("Invalid Name", MessageType.Error); } } else { try { #if UNITY_ANDROID && !UNITY_EDITOR if (!Directory.Exists("/storage/emulated/0/SquadCraft")) //If there is no SquadcraftBattles folder on sd (Usually when first installed) { Directory.CreateDirectory("/storage/emulated/0/SquadCraft"); //Creates the folder } #elif UNITY_EDITOR //On the editor the folder "always exist", dont erase anaything, I create them manually #endif Directory.CreateDirectory(worldsFilesPath);//Creates the My worlds where worlds are storage } catch (Exception e) { Message.showMessageText(e.ToString()); } saveWorld(tilesPlaced, sizeX, sizeY, worldName); } }