只需使用AssetDatabase.Refresh
刷新Unity中的assets资源 .
However
当玩家创建一个新关卡时,我使用这个
请注意,这些都不适用于内置应用程序!
构建应用程序后,Resources
是read-only.不管怎样,请注意Best practices -> Resources
Don't use it!
您可能更希望将默认文件存储在StreamingAssets
中,使用Application.streamingassetsPath
,然后在构建中使用Application.persistentDataPath
,并回退到streamingAssetsPath
以实现只读(同样,构建后StreamingAssets
是只读的)
比如说
public string ReadlevelsFile()
{
try
{
#if UNITY_EDITOR
// In the editor always use "Assets/StreamingAssets"
var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
#else
// In a built application use the persistet data
var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");
// but for reading use the streaming assets on as fallback
if (!File.Exists(filePath))
{
filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
}
#endif
return File.ReadAllText(filePath);
}
catch (Exception e)
{
Debug.LogException(e);
return "";
}
}
public void WriteLevelsFile(string content)
{
try
{
#if UNITY_EDITOR
// in the editor always use "Assets/StreamingAssets"
var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
// mke sure to create that directory if not exists yet
if(!Directory.Exists(Application.streamingAssetsPath))
{
Directory.CreateDirectory(Application.streamingAssetsPath);
}
#else
// in a built application always use the persistent data for writing
var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");
#endif
File.WriteAllText(filePath, content);
#if UNITY_EDITOR
// in Unity need to refresh the data base
UnityEditor.AssetDatabase.Refresh();
#endif
}
catch(Exception e)
{
Debug.LogException(e);
}
}