最近新开始了一个新游戏,2D像素养成经营。地图是Tilemap制作的,需求为更换场景中建筑的样式。我这里是直接使用了Tilemap.SetTile来进行更换
自定义瓦片
Unity 自带的瓦片没有任何属性,肯定是不够用的。所以需要自定义瓦片。自定义很简单,只需要继承TileBase类就可以了,这里自定义了一个枚举,当前的瓦片是哪个部位。
更换场景中的Tile
在用Tilemap更换Tile需要一个vector3int 的位置,这里需要遍历整个Tilemap里面寻找自定义的Tile再去更改,如果每次更新都需要遍历一遍,很蠢。所以这里就提前给当前Tilemap所有自定义的Tile位置信息存储起来
更换Tile,这里的AnimalRoomTileData 是读取json获得
工具提前存储位置
遍历Tilemap中所有自定义Tile 将位置信息储存为Json,直接贴代码了
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;
public class AnimalRoom2Json :EditorWindow
{
private Tilemap currentAnimalRoomMap;
private Vector2 scrollPosition;
[MenuItem( "Tool/AnimalRoom2Json" )]
public static void ShowWindow( )
{
AnimalRoom2Json window = GetWindow<AnimalRoom2Json>( );
window.titleContent = new GUIContent( "笼舍地图转为json" );
window.minSize = new Vector2( 540 , 520 );
window.maxSize = new Vector2( 540 , 520 );
window.Focus( );
}
private void OnGUI( )
{
currentAnimalRoomMap = (Tilemap)EditorGUI.ObjectField( new Rect( 20 , 20 , 500 , 20 ) , "笼舍TileMap:" , currentAnimalRoomMap , typeof( Tilemap ) );
if( null == currentAnimalRoomMap )
{
return;
}
BoundsInt bounds = currentAnimalRoomMap.cellBounds;
TileBase[] allTiles = currentAnimalRoomMap.GetTilesBlock( bounds );
List<AnimalRoomTileData> tempList = new List<AnimalRoomTileData>( );
for( int x = bounds.xMin ; x < bounds.xMax ; x++ )
{
for( int y = bounds.yMin ; y < bounds.yMax ; y++ )
{
AnimalRoomTile animalRoomTile = currentAnimalRoomMap.GetTile<AnimalRoomTile>( new Vector3Int( x , y ) );
if( null == animalRoomTile )
{
continue;
}
AnimalRoomTileData animalRoomTileData = new AnimalRoomTileData( x , y , (int)animalRoomTile.part );
tempList.Add( animalRoomTileData );
}
}
scrollPosition = GUI.BeginScrollView( new Rect( 20 , 60 , 500 , 380 ) , scrollPosition , new Rect( 20 , 60 , 400 , tempList.Count * 20 + 20 ) );
{
int height = 40;
int i = 0;
foreach( var data in tempList )
{
height += 20;
i += 1;
EditorGUI.LabelField( new Rect( 20 , height , 50 , 20 ) , "位置: X: " + data.x );
EditorGUI.LabelField( new Rect( 150 , height , 50 , 20 ) , "Y:" + data.y );
EditorGUI.LabelField( new Rect( 280 , height , 150 , 20 ) , "Part:" + ( (AnimalRoomTile.RoomPart)data.part ).ToString( ) );
}
}
GUI.EndScrollView( );
if( GUI.Button( new Rect( 20 , 460 , 500 , 50 ) , "转为Json" ) )
{
string message = AnimalRoomTileDataProxy.ToJson( new AnimalRoomTileDataProxy( tempList ) );
string defaultName = "AnimalRoom" + currentAnimalRoomMap.GetComponent<AnimalRoomBuild>( ).id;
string path = EditorUtility.SaveFilePanel( "储存" , Application.dataPath + "Asset/Resources/Json" , defaultName , "txt" );
if( string.IsNullOrEmpty( path ) )
{
return;
}
path = Path.GetFullPath( path );
File.WriteAllText( path , message );
AssetDatabase.Refresh( );
EditorUtility.DisplayDialog( "储存成功" , path , "确定" );
}
}
}
版权声明:本文为weixin_45675094原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。