Unity学习记录:list的应用案例
1、引言
在制作unity项目的时候,例如,照片墙项目时,点击图片查看大图和图片信息,但是,不能让所有的图片都能打开,这时候需要我们限制打开的个数,达到节约性能和让程序不卡。这时候就需要用到list列表(当然还有更好的方法,不过我用的是列表,以后遇到需要的情况再来补充)。
2、效果展示
有多个text,当点击的时候,只能显示最多三个文字,最先点开的文字会消失,从列表中移除,最后点开的文字,会移入列表。(类似于一个队列,先进先出。)
3、Hierarchy面板
4、脚本
TestItem脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TestItem : MonoBehaviour { Button btn; public Text text; void Start() { //组件设置 btn = GetComponent<Button>(); text = transform.GetChild(0).GetComponent<Text>(); //默认文字隐藏 text.gameObject.SetActive(false); //按钮监听 btn.onClick.AddListener(ButtonEvent); } #region 按钮事件 //点击按钮,文字出现,再点一次,文字消失 void ButtonEvent() { if (!text.gameObject.activeSelf) { text.gameObject.SetActive(true); //打开文字个数的限制 TestManager.GetInstance().Show(this); } else { text.gameObject.SetActive(false); TestManager.GetInstance().DisShow(this); } } #endregion }
TestManager脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestManager : MonoBehaviour { public List<GameObject> textList; #region 单例 static TestManager instance; public static TestManager GetInstance() { return instance; } private void Awake() { instance = this; } #endregion public void Show(TestItem _testItem) { textList.Add(_testItem.text.gameObject); if (textList.Count>3) { //最先出现的文字消失 textList[0].SetActive(false); //从列表中移除 textList.RemoveAt(0); } } public void DisShow(TestItem _testItem) { textList.Remove(_testItem.text.gameObject); } }
ok,结束了,再给大家推荐一个链接,这里比较详细的讲了list的用法,可以学习一下哦
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
交叉验证,五次五折,十次十折