系列文章目录
麦田物语第五天
一、(Editor)生成 ListView 列表
首先需要获取ItemDataList的数据,即先声明变量dataBase,接着是需要ItemDataList_SO的文件位置获取文件。同时需要定义存储数据的数组ItemList,对应着dataBase里面的List。
在这里我们使用的方法是获取到一个GUID数组(AssetDatabase.FindAssets);取得其中的第一个元素就是我们想要的物品的GUID;接着我们可以根据GUID获取该物品所在的文件路径(GUIDToAssssetPath),然后就可以根据该路径将Asset加载出来(LoadAssetAtPath);之后将dataBase的数据数组赋值给ItemList;最后一定将dataBase进行标记,如果不标记就无法保存数据。
代码如下
public void CreateGUI()
{
//加载数据
LoadDataBase();
}
private void LoadDataBase()
{
var dataArray = AssetDatabase.FindAssets("ItemDataList_SO");
if (dataArray.Length > 1)
{
var path = AssetDatabase.GUIDToAssetPath(dataArray[0]);
dataBase = AssetDatabase.LoadAssetAtPath(path, typeof(ItemDataList_SO)) as ItemDataList_SO;
}
itemList = dataBase.itemDetailsList;
//如果不标记则无法保存数据
EditorUtility.SetDirty(dataBase);
//Debug.Log(itemList[0].itemID);
}
上述方法可以通过查找Unity官方文档进行了解。
接着要实现在ListVIew中能看到对应的物品,我们可以在Windows->UI Toolkit->Sample中查找List View的使用方法。
// The "makeItem" function will be called as needed
// when the ListView needs more items to render
Func<VisualElement> makeItem = () => new Label();//当我们在绘制是数据到窗口时,会调用这个函数方法
// As the user scrolls through the list, the ListView object
// will recycle elements created by the "makeItem"
// and invoke the "bindItem" callback to associate
// the element with the matching data item (specified as an index in the list)
Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = items[i];//实际上的内容显示是在这个方法中进行实现的。
var listView = container.Q<ListView>("Name");//查找方式:从根目录root往下面的目录查找时,可以通过.Q方法得到组件,如果存在相同的组件,可以通过Name进行查找
listView.makeItem = makeItem;
listView.bindItem = bindItem;
listView.itemsSource = items;//itemSource资源就是我们定义的List数组
listView.selectionType = SelectionType.Multiple;
我们现在要做的就是生成ListView:我们首先需要得到我们获取的ItemRowTemplate组件,那么需要定义,并且通过绝对路径拿到这个组件(LoadAssetAtPath方法,绝对路径我们可以右键我们创建的ItemRowTemplate然后CopyPath即可);接着使用上述代码的第一句,将ItemRowTemplate的模板文件赋值给makeItem;然后也是默认样例中的写法,在bindItem的方法中,我们首先要判断是否itemList的数组大小为空,不为空才能继续下面的操作,然后找到Icon组件并将其背景图片设置成itemList的texture(也要判断是否为空),也要将Name组件的名称改为itemList的ItemName(也要判断是否为空);接着我们就可以生成ListView,我们需要对ItemEditor组件的ListView先进行声明,接着通过.Q的方法一步步获取到ListView,最后对ListView的ItemSource,makeItem,bindItem进行赋值并在CreateGUI中调用即可。
public void CreateGUI()
{
//拿到模板数据
itemRowTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/UIBuild/ItemRowTemplate.uxml");
//变量赋值
itemListView = root.Q<VisualElement>("ItemList").Q<ListView>("ListView");
//生成ListView
GenerateListView();
}
private void GenerateListView()
{
Func<VisualElement> makeItem = () => itemRowTemplate.CloneTree(