- Home /
Addressable.LoadAssetAsync doesn't work but has no error
Hi, I'm Japanese. Please excuse me if you may not understand or you feel bad with my poor English.
I'm making some tools extending my unity editor to generate tilemaps automatically, and I wants to get TileBase
assets by Addressable.LoadAssetAsync
(on below source code, it's in the 414th line), but the function doesn't work and generates any error messages. And Debug.Log(tilebase);
in the next doesn't work, too. Does anyone know how to fix this?
Source Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Unity.EditorCoroutines.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.Tilemaps;
public class MapEditor : EditorWindow
{
private enum Tab
{
Base, Tile, AreaTransision, EventTrigger, Mob, Enemy
}
private Tab _tab = Tab.Base;
private string mapName;
private string displayMapName;
private string mapCode;
private string backgroundImage;
private string overlayImage;
[SerializeField]
private List<RPGClasses.StageData_TileData> tiles = new List<RPGClasses.StageData_TileData>();
[SerializeField]
private List<RPGClasses.StageData_Area_TransisionData> areaTransisions = new List<RPGClasses.StageData_Area_TransisionData>();
[SerializeField]
private List<RPGClasses.StageData_Event_TriggerData> eventTriggers = new List<RPGClasses.StageData_Event_TriggerData>();
[SerializeField]
private List<RPGClasses.StageData_MobData> mobs = new List<RPGClasses.StageData_MobData>();
[SerializeField]
private List<RPGClasses.StageData_EnemyData> enemies = new List<RPGClasses.StageData_EnemyData>();
private Vector2[] _scrollPositions = new Vector2[6];
[MenuItem("RPGEditor/MapEditor")]
private static void Create()
{
MapEditor mapEditor = GetWindow<MapEditor>("MapEditor");
mapEditor.minSize = new Vector2(640, 640);
}
private void OnGUI()
{
SerializedObject mpdt = new SerializedObject(this);
using (new GUILayout.HorizontalScope())
{
if (GUILayout.Button("New"))
{
New();
}
if (GUILayout.Button("Load"))
{
Load();
}
if (GUILayout.Button("Save"))
{
Save();
}
}
var splitterRect1 = EditorGUILayout.GetControlRect(false, GUILayout.Height(1));
splitterRect1.x = 0;
splitterRect1.width = position.width;
EditorGUI.DrawRect(splitterRect1, Color.Lerp(Color.gray, Color.black, 0.7f));
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
_tab = (Tab)GUILayout.Toolbar((int)_tab, Styles.TabToggles, Styles.TabButtonStyle, Styles.TabButtonSize);
GUILayout.FlexibleSpace();
}
var splitterRect2 = EditorGUILayout.GetControlRect(false, GUILayout.Height(1));
splitterRect2.x = 0;
splitterRect2.width = position.width;
EditorGUI.DrawRect(splitterRect2, Color.Lerp(Color.gray, Color.black, 0.7f));
switch (_tab)
{
case Tab.Base:
mapName = EditorGUILayout.TextField("MapName", mapName);
displayMapName = EditorGUILayout.TextField("DisplayMapName", displayMapName);
using (new EditorGUI.DisabledGroupScope(true))
{
mapCode = EditorGUILayout.TextField("MapCode", mapCode);
}
using (new EditorGUILayout.HorizontalScope())
{
backgroundImage = EditorGUILayout.TextField("Background", backgroundImage);
if (GUILayout.Button("Select"))
{
ImageSelect("Background");
}
}
using (new EditorGUILayout.HorizontalScope())
{
overlayImage = EditorGUILayout.TextField("Overlay", overlayImage);
if (GUILayout.Button("Select"))
{
ImageSelect("Overlay");
}
}
break;
case Tab.Tile:
GUILayout.Label("When you will save map tiles to this MapData, you have to change the scene in editing to \"MapEditorScene\" and create TileMap there.", new GUIStyle(GUI.skin.label) { wordWrap = true });
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Import Created Tiles"))
{
SaveTile();
}
if (GUILayout.Button("Generate Saved Tiles"))
{
EditorCoroutineUtility.StartCoroutineOwnerless(GenerateTile());
}
}
_scrollPositions[1] = EditorGUILayout.BeginScrollView(_scrollPositions[1]);
{
EditorGUILayout.PropertyField(mpdt.FindProperty("tiles"), true);
mpdt.ApplyModifiedProperties();
}
EditorGUILayout.EndScrollView();
break;
case Tab.AreaTransision:
_scrollPositions[2] = EditorGUILayout.BeginScrollView(_scrollPositions[2]);
{
EditorGUILayout.PropertyField(mpdt.FindProperty("areaTransisions"), true);
mpdt.ApplyModifiedProperties();
}
EditorGUILayout.EndScrollView();
break;
case Tab.EventTrigger:
_scrollPositions[3] = EditorGUILayout.BeginScrollView(_scrollPositions[3]);
{
EditorGUILayout.PropertyField(mpdt.FindProperty("eventTriggers"), true);
mpdt.ApplyModifiedProperties();
}
EditorGUILayout.EndScrollView();
break;
case Tab.Mob:
_scrollPositions[4] = EditorGUILayout.BeginScrollView(_scrollPositions[4]);
{
EditorGUILayout.PropertyField(mpdt.FindProperty("mobs"), true);
mpdt.ApplyModifiedProperties();
}
EditorGUILayout.EndScrollView();
break;
case Tab.Enemy:
_scrollPositions[5] = EditorGUILayout.BeginScrollView(_scrollPositions[5]);
{
EditorGUILayout.PropertyField(mpdt.FindProperty("enemies"), true);
mpdt.ApplyModifiedProperties();
}
EditorGUILayout.EndScrollView();
break;
}
}
private void New()
{
tiles.Clear();
areaTransisions.Clear();
eventTriggers.Clear();
mobs.Clear();
enemies.Clear();
string[] mapFiles = Directory.GetFiles(Application.dataPath + "/Datas/_map", "map_*.json", SearchOption.AllDirectories);
int nextCode = int.Parse(Path.GetFileNameWithoutExtension(mapFiles[mapFiles.Length - 1]).Replace("map_", "")) + 1;
mapCode = nextCode.ToString("D4");
}
private void Load()
{
tiles.Clear();
areaTransisions.Clear();
eventTriggers.Clear();
mobs.Clear();
enemies.Clear();
var filePath = EditorUtility.OpenFilePanel("Load map file", "Assets/Datas/_map", "json");
if (!string.IsNullOrEmpty(filePath))
{
string mapFile = File.ReadAllText(filePath);
RPGClasses.StageData mapData = JsonUtility.FromJson<RPGClasses.StageData>(mapFile);
mapCode = mapData.Map_Code;
mapName = mapData.Map_Name;
displayMapName = mapData.Display_Map_Name;
backgroundImage = mapData.Background;
overlayImage = mapData.Overlay;
foreach (RPGClasses.StageData_TileData t in mapData.Tile)
{
tiles.Add(t);
}
foreach (RPGClasses.StageData_Area_TransisionData a in mapData.Area_Transision)
{
areaTransisions.Add(a);
}
foreach (RPGClasses.StageData_Event_TriggerData e in mapData.Event_Trigger)
{
eventTriggers.Add(e);
}
foreach (RPGClasses.StageData_MobData m in mapData.Mob)
{
mobs.Add(m);
}
foreach (RPGClasses.StageData_EnemyData e in mapData.Enemy)
{
enemies.Add(e);
}
}
}
private void Save()
{
RPGClasses.StageData newStageData = new RPGClasses.StageData();
newStageData.Map_Name = mapName;
newStageData.Display_Map_Name = displayMapName;
newStageData.Map_Code = mapCode;
newStageData.Background = backgroundImage;
newStageData.Overlay = overlayImage;
newStageData.Tile = new RPGClasses.StageData_TileData[tiles.Count];
for (int a = 0; a < tiles.Count; a++)
{
newStageData.Tile[a] = tiles[a];
}
newStageData.Area_Transision = new RPGClasses.StageData_Area_TransisionData[areaTransisions.Count];
for (int a = 0; a < areaTransisions.Count; a++)
{
newStageData.Area_Transision[a] = areaTransisions[a];
}
newStageData.Event_Trigger = new RPGClasses.StageData_Event_TriggerData[eventTriggers.Count];
for (int a = 0; a < eventTriggers.Count; a++)
{
newStageData.Event_Trigger[a] = eventTriggers[a];
}
newStageData.Mob = new RPGClasses.StageData_MobData[mobs.Count];
for (int a = 0; a < mobs.Count; a++)
{
newStageData.Mob[a] = mobs[a];
}
newStageData.Enemy = new RPGClasses.StageData_EnemyData[enemies.Count];
for (int a = 0; a < enemies.Count; a++)
{
newStageData.Enemy[a] = enemies[a];
}
File.WriteAllText(Application.dataPath + $"/Datas/_map/map_{ mapCode }.json", JsonUtility.ToJson(newStageData));
}
private void ImageSelect(string type)
{
var filePath = EditorUtility.OpenFilePanel($"Load { type.ToLower() } image file", $"Assets/Resources/{ type }", "png,jpg");
if (!string.IsNullOrEmpty(filePath))
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
if (type == "Background") backgroundImage = fileName;
else if (type == "Overlay") overlayImage = fileName;
}
}
private void SaveTile()
{
bool returns = EditorUtility.DisplayDialog("Attention", "If you continue this function, the saved tile detas will lose. If you want to continue, click \"continue\".", "continue", "cancel");
if (!returns)
{
return;
}
tiles.Clear();
Tilemap[] tilemaps = new Tilemap[8];
tilemaps[0] = GameObject.Find("Hit_Tilemap").GetComponent<Tilemap>();
tilemaps[1] = GameObject.Find("Shadow1_Tilemap").GetComponent<Tilemap>();
tilemaps[2] = GameObject.Find("Top_Tilemap").GetComponent<Tilemap>();
tilemaps[3] = GameObject.Find("Over_Tilemap").GetComponent<Tilemap>();
tilemaps[4] = GameObject.Find("Items_Tilemap").GetComponent<Tilemap>();
tilemaps[5] = GameObject.Find("Shadow2_Tilemap").GetComponent<Tilemap>();
tilemaps[6] = GameObject.Find("Ground_Tilemap").GetComponent<Tilemap>();
tilemaps[7] = GameObject.Find("Below_Tilemap").GetComponent<Tilemap>();
Dictionary<string, string> setTiles = new Dictionary<string, string>();
for (int a = 0; a < tilemaps.Length; a++)
{
for (int b = 0; b < EventFunctions.TILEMAP_MAXRANGE_X; b++)
{
for (int c = 0; c < EventFunctions.TILEMAP_MAXRANGE_Y; c++)
{
TileBase tileBase = tilemaps[a].GetTile(new Vector3Int(b, c, 0));
if (tileBase != null)
{
string tileName = tileBase.name;
if (setTiles.ContainsKey(tileName)) setTiles[tileName] += $"{ a }:{ b }:{ c }/";
else setTiles.Add(tileName, $"{ a }:{ b }:{ c }/");
}
}
}
}
string[] keys = new string[setTiles.Count];
setTiles.Keys.CopyTo(keys, 0);
foreach (var key in keys)
{
setTiles[key] = setTiles[key].Substring(0, setTiles[key].Length - 1);
tiles.Add(new RPGClasses.StageData_TileData
{
Tile_Name = key,
Place = setTiles[key].Split('/')
});
}
}
private IEnumerator GenerateTile()
{
bool returns = EditorUtility.DisplayDialog("Attention", "If you continue this function, the tilemap detas will lose. If you want to continue, click \"continue\".", "continue", "cancel");
if (!returns)
{
yield break;
}
Tilemap[] tilemaps = new Tilemap[8];
tilemaps[0] = GameObject.Find("Hit_Tilemap").GetComponent<Tilemap>();
tilemaps[1] = GameObject.Find("Shadow1_Tilemap").GetComponent<Tilemap>();
tilemaps[2] = GameObject.Find("Top_Tilemap").GetComponent<Tilemap>();
tilemaps[3] = GameObject.Find("Over_Tilemap").GetComponent<Tilemap>();
tilemaps[4] = GameObject.Find("Items_Tilemap").GetComponent<Tilemap>();
tilemaps[5] = GameObject.Find("Shadow2_Tilemap").GetComponent<Tilemap>();
tilemaps[6] = GameObject.Find("Ground_Tilemap").GetComponent<Tilemap>();
tilemaps[7] = GameObject.Find("Below_Tilemap").GetComponent<Tilemap>();
for (int a = 0; a < tilemaps.Length; a++)
{
tilemaps[a].ClearAllTiles();
tilemaps[a].size = new Vector3Int(EventFunctions.TILEMAP_MAXRANGE_X, EventFunctions.TILEMAP_MAXRANGE_Y, 1);
}
string[,,] tileLayout = new string[tilemaps.Length, EventFunctions.TILEMAP_MAXRANGE_X, EventFunctions.TILEMAP_MAXRANGE_Y];
if (tiles.Count > 0)
{
for (int a = 0; a < tiles.Count; a++)
{
int startX, startY, endX, endY;
string[] places = tiles[a].Place;
foreach (string place in places)
{
startX = int.Parse(place.Split(':')[1].Split('-')[0]);
startY = int.Parse(place.Split(':')[2].Split('-')[0]);
if (place.Split(':')[1].Split('-').Length == 2)
endX = int.Parse(place.Split(':')[1].Split('-')[1]);
else endX = startX;
if (place.Split(':')[2].Split('-').Length == 2)
endY = int.Parse(place.Split(':')[2].Split('-')[1]);
else endY = startY;
string tileName = tiles[a].Tile_Name;
int layerNum = int.Parse(place.Split(':')[0]);
for (int b = startX; b <= Math.Min(endX, EventFunctions.TILEMAP_MAXRANGE_X); b++)
{
for (int c = startY; c <= Math.Min(endY, EventFunctions.TILEMAP_MAXRANGE_Y); c++)
{
tileLayout[layerNum, b, c] = tileName;
}
}
}
}
}
var _id1 = Progress.Start("GenerateTiles", "aaa");
int count = 0;
int maxVal = tilemaps.Length * EventFunctions.TILEMAP_MAXRANGE_X * EventFunctions.TILEMAP_MAXRANGE_Y;
// Generate Tiles
for (int a = 0; a < tilemaps.Length; a++)
{
for (int b = 0; b < EventFunctions.TILEMAP_MAXRANGE_X; b++)
{
for (int c = 0; c < EventFunctions.TILEMAP_MAXRANGE_Y; c++)
{
Debug.Log(tileLayout[a, b, c]);
count++;
if (!string.IsNullOrEmpty(tileLayout[a, b, c]))
{
Debug.Log("tilename is " + tileLayout[a, b, c]);
// This
AsyncOperationHandle<TileBase> tilebase = Addressables.LoadAssetAsync<TileBase>(tileLayout[a, b, c]);
yield return tilebase;
Debug.Log(tilebase);
if (tilebase.Status == AsyncOperationStatus.Succeeded)
{
tilemaps[a].SetTile(new Vector3Int(b, c, 0), tilebase.Result);
}
Addressables.Release(tilebase);
}
Progress.Report(_id1, count / maxVal, $"a ({count} / {maxVal})");
}
}
}
Progress.Finish(_id1);
yield break;
}
private static class Styles
{
private static GUIContent[] _tabToggles = null;
public static GUIContent[] TabToggles
{
get
{
if (_tabToggles == null)
{
_tabToggles = System.Enum.GetNames(typeof(Tab)).Select(x => new GUIContent(x)).ToArray();
}
return _tabToggles;
}
}
public static readonly GUIStyle TabButtonStyle = "LargeButton";
public static readonly GUI.ToolbarButtonSize TabButtonSize = GUI.ToolbarButtonSize.Fixed;
}
}
Your answer
Follow this Question
Related Questions
Fix for offset tiles in tilemap and palette 1 Answer
2D: Best way to group a type of tile based on their neighbors similar type? 1 Answer
Tile collision by sprite is not accurate with Tilemap Collider 0 Answers
2D Tilemap prefab brush doesn't paint the tile in the right place 0 Answers
How to create coin templates for spawning in 2D game 1 Answer