Unity .Asset文件出现"The associated script can not be loaded. Please fix any compile errors and assi…"如图所示
问题背景:
用到Unity Asset 发现PC-Editor运行正常 但是一打包安卓就发现找不到文件的情况
处理方案:
只要保证如图三个地方名称一致即可 问题核心代码:
MyAssetEditor.cs:
public class MyAssetEditor : UnityEditor.Editor
{
[MenuItem("MyAsset/CreateAsset")]
static void Create()
{
CreateAsset();
}
/// <summary>
/// 创建Asset
/// </summary>
public static void CreateAsset()
{
// 判断目录是否存在
if (!Directory.Exists(MyAssetHelper.GetFolderPath()))
{
Directory.CreateDirectory(MyAssetHelper.GetFolderPath());
}
// 创建.asset文件
MyAsset _asset = MyAsset.CreateInstance<MyAsset>();
AssetDatabase.CreateAsset(_asset, MyAssetHelper.GetFilePath());
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("Asset create success");
}
}
MyAsset.cs
[Serializable]
public enum UserAgeType
{
Unknown, // 错误类型
Child, // 儿童
Adult, // 成人
Elder, // 老人
}
[Serializable]
public enum UserSexType
{
Unknown, // 错误类型
Male, // 雄性
Female, // 雌性
}
[Serializable]
public class User
{
public string Name;
public UserAgeType AgeType;
public UserSexType SexType;
public User(string name, UserAgeType ageTp, UserSexType sexTp) {
this.Name = name;
this.AgeType = ageTp;
this.SexType = sexTp;
}
public override string ToString()
{
return this.Name + "," + this.AgeType + "," + this.SexType;
}
}
public class MyAsset : ScriptableObject
{
[SerializeField]
public User Author = new User("东宝",UserAgeType.Adult,UserSexType.Male);
}
public static class MyAssetHelper
{
private const string FolderPath = "Assets/Resources";
private const string FileName = "MyAsset";
public static string GetFilePath()
{
return string.Format("{0}/{1}.asset", FolderPath, FileName);
}
public static string GetFileName()
{
return FileName;
}
public static string GetFolderPath()
{
return FolderPath;
}
}
Sample.cs
public class Sample : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
MyAsset.MyAsset _asset = Resources.Load<MyAsset.MyAsset>(MyAsset.MyAssetHelper.GetFileName());
Debug.Log(_asset.Author.ToString());
}
// Update is called once per frame
void Update()
{
}
}
项目地址:
MyAsset
|