Unity开发笔记-Unity2019使用AssetDatabase.CreateAsset创建TimelineAsset保存不正常的问题
问题
当通过AssetDatabase创建TimelineAsset时,Timeline上的Track都丢失了
下面的代码TimelineAsset不会被正确的创建出来:
`TimelineAsset timeline = ScriptableObject.CreateInstance<TimelineAsset>();
timeline.name = "test_timeline";
if (!Directory.Exists(TIMELINE_SAVE_PATH))
{
Directory.CreateDirectory(TIMELINE_SAVE_PATH);
}
string assetPath =TIMELINE_SAVE_PATH+timeline.name+".playable";
timeline.CreateTrack<AnimationTrack>();
timeline.CreateTrack<AnimationTrack>();
AssetDatabase.CreateAsset(timeline,assetPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();`
虽然生成完毕,点击查看timeline没有什么问题
但是
运行一下Unity,然后再查看timeline,会变成这样
另外会有报错提示:
MissingReferenceException: The object of type 'AnimationTrack' has been destroyed but you are still trying to access it.
我们使用文本编辑器打开这个timeline文件,发现文件确实没有被正确创建
原因:
创建track之前,timline需要已经存在于assetdatabase中
否则track信息会丢失,报错
解决方法:
1.先createAsset
2.再创建timeline上的track
需要先CreateAsset一个空的TimelineAsset
上面的代码调换顺序之后如下:
`
TimelineAsset timeline = ScriptableObject.CreateInstance<TimelineAsset>();
timeline.name = "test_timeline";
if (!Directory.Exists(TIMELINE_SAVE_PATH))
{
Directory.CreateDirectory(TIMELINE_SAVE_PATH);
}
string assetPath =TIMELINE_SAVE_PATH+timeline.name+".playable";
AssetDatabase.CreateAsset(timeline,assetPath); //先将timeline保存到assetdatabase中
AnimationTrack track = timeline.CreateTrack<AnimationTrack>(); //再创建track
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();`