Unity3D序列化ScriptableObject

一、应用

把策划数值转为游戏数值


二、序列化类及数据结构类

public class HeroAssetObject: ScriptableObject{

	public Hero[] heroList;

}

注意前面的序列化标识:[System.Serializable]
[System.Serializable]
public class Hero{
	public int id;
	public int hp;
	public int ap;
	public int mp;
	public string name;
	public int age;
}



三、编辑器下创建序列化文件

public class CreateAssetFile{


	[MenuItem("Age/CreateHeroAsset")]
	public static void CreateHeroAsset()
	{
		if(!Directory.Exists(Application.streamingAssetsPath))
		{
			Directory.CreateDirectory(Application.streamingAssetsPath);
		}
		HeroAssetObject obAsset=new HeroAssetObject();
		obAsset.heroList=readHeroAssetData();
		AssetDatabase.CreateAsset(obAsset,"Assets/StreamingAssets/a.asset");


		BuildPipeline.BuildAssetBundle(obAsset,null,Application.streamingAssetsPath+"/a.assetbundle"
		                               ,BuildAssetBundleOptions.CollectDependencies,EditorUserBuildSettings.activeBuildTarget);

		AssetDatabase.Refresh();

	}

	public static Hero[] readHeroAssetData()
	{
		Hero[] heroList=null;
		string[] heroAssData= File.ReadAllLines(Application.dataPath+"/HeroAssets.csv");
		if(heroAssData!=null)
		{
			heroList=new Hero[heroAssData.Length-1];
			for(int i=1;i<heroAssData.Length;i++)
			{
				heroList[i-1]=new Hero();
				string[] infors=heroAssData[i].Split(',');
				heroList[i-1].id=int.Parse(infors[0]); 
				heroList[i-1].hp=int.Parse(infors[1]);
				heroList[i-1].ap=int.Parse(infors[2]);
				heroList[i-1].mp=int.Parse(infors[3]);
				heroList[i-1].age=int.Parse(infors[4]);
				Debug.Log("I:"+i+"  heroAssData:"+heroAssData[i]);
			}
		}
		return heroList;
	}
}

四、游戏中动态加载资源

public class Main : MonoBehaviour {
	
	public HeroAssetObject assObject;

	// Use this for initialization
	void Start () {
		StartCoroutine(loadHeroAsset());
	}

	IEnumerator loadHeroAsset()
	{
		WWW www=new WWW("file://"+Application.streamingAssetsPath+"/a.assetbundle");
		yield return www;
		if(www.error==null)
		{
			AssetBundle ab=www.assetBundle;
			HeroAssetObject heroAssOb=(HeroAssetObject)ab.mainAsset;

			assObject=heroAssOb;

			ab.Unload(false);
			ab=null;
		}
		else
		{
			Debug.Log("error:"+www.error);
		}

		www.Dispose();
		www=null;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zuig2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值