首页 技术 正文
技术 2022年11月15日
0 收藏 561 点赞 3,805 浏览 1912 个字

我们知道,在Unity当中的文件都可以称之为Asset文件,在项目开发当中需要把数据读取来之后存放起来,而有的数据是不可以改变的,今天就来写一个demo处理一下这些数据,在这里就不写读取Excal数据的方法了,如果需要了解就百度一下,关于这样的帖子和文章有很多

首先我们需要一个类来“模仿”一下Excal数据,可以定义一下类:

Excal数据转化成Asset数据文件

using UnityEngine;
using System.Collections;/// <summary>
/// 数据类
/// </summary>
[System.Serializable]
public class ItemData
{ //换句话说就是每一行就是一个类
public string id;
public string name;
public int addAttack;
public int addHp;
public int addDefense;
}

因为一个Excal里面有很多行,也就是说有很多类,所以这一个类是满足不了我们的,我们需要吧数据读出来之后把数据放起来,在这里我用的是List。如下:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;/// <summary>
/// 存放Asset数据
/// </summary>
public class ItemDataList : ScriptableObject
{
public List<ItemData> itemData; //表示一个Excal表格
}

紧接着就是生成数据了,如下,需要说明的是,此类事编辑器类,需要放在Editor里面,把下面的脚本放在Unity里面之后会在Unity的菜单栏里面出现一个Demo-CreateAsset,单击一下就可以生成Asset数据了,该数据是放在Resources,所以前提是需要有一个Resources文件,点击生成的文件就可以看到数据了

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;/// <summary>
/// 把数据打包成为Asset文件
/// </summary>
public class CreateAssetData
{
[MenuItem("Demo/CreateAsset")]
static void CreateAsset()
{
ItemDataList list = ItemDataList.CreateInstance<ItemDataList>();
list.itemData = DataTest();
AssetDatabase.CreateAsset(list,"Assets/CreateAsset/Resources/ItemData.asset");
} public static List<ItemData> DataTest() //测试数据
{
List<ItemData> data = new List<ItemData>();
for (int i = ; i < ; i++)
{
ItemData d = new ItemData();
d.id = "" + i;
d.name = "" + i;
d.addHp = i;
d.addDefense = i*;
d.addAttack = i*;
data.Add(d);
}
return data;
}
}

最后就是用这些数据了,因为之前我是在Resources里面放着的,所以我是用Resources类来加载数据,如下,

using UnityEngine;
using System.Collections;
using System.Collections.Generic;/// <summary>
/// 加载数据
/// </summary>
public class AssetLoad : MonoBehaviour
{ [SerializeField]
private List<ItemData> itemData; void Awake()
{
StartCoroutine(LoadAssetData());
} IEnumerator LoadAssetData()
{
ItemDataList list = Resources.Load<ItemDataList>("ItemData");
itemData = list.itemData;
yield return null;
}
}

附:也可以把该数据打包成AssetBundle文件,然后用WWW类来加载,之后转化成为ItemDataList类型就可以拿到数据了。另外这个数据打成Asset文件之后就一定固定了,不能再改变了。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,075
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,893