效果演示
实现思路
使用Unity的一些自身的控制键搭建UI,使用自带的UI组件实现自适应,读取StreamingAssets里某个文件的内容,并显示到在Resources中加载的的预制体的text组件上。
全部代码
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class MySizeCreat : MonoBehaviour
{
private string _toxicInfoPath = Application.streamingAssetsPath + "/ReadMyLine.txt";
private string _lineItemPath = @"lineItem"; //item预制体的路径
private GameObject _goLineItem = null; //加载出来的预制体
private Transform _btnClickOK; //确认
private Transform _trItemParents; //创建的item的父物体
private Transform _trBtnItem;
void Start()
{
StartCoroutine(InitCommpoent());
}
IEnumerator InitCommpoent()
{
_goLineItem = Resources.Load<GameObject>(_lineItemPath);
if (_goLineItem == null)
{
Debug.LogError("未能加载出物体,请确认路径是否正确");
yield return null;
}
_trItemParents = FindTheChildNode(gameObject.transform, "ItemParents");
_trBtnItem=FindTheChildNode(gameObject.transform, "btnItem");
_btnClickOK = FindTheChildNode(gameObject.transform, "Button");
_btnClickOK.gameObject.GetComponent<Button>().onClick.AddListener(() =>
{
//todo:点击确认需要做的事情
gameObject.SetActive(false);
});
foreach (string line in System.IO.File.ReadLines(_toxicInfoPath))
{
var goitem = GameObject.Instantiate(_goLineItem, _trItemParents);
goitem.gameObject.GetComponentInChildren<Text>().text = line;
}
_trBtnItem.SetAsLastSibling();
yield return null;
}
/// <summary>
/// 查找子节点对象
/// </summary>
/// <param name="goParent">父对象</param>
/// <param name="childName">子节点名称</param>
/// <returns></returns>
public static Transform FindTheChildNode(Component goParent, string childName)
{
Transform searchTrans = goParent.transform.Find(childName);
if (searchTrans == null)
{
foreach (Transform trans in goParent.transform)
{
searchTrans = FindTheChildNode(trans, childName);
if (searchTrans != null)
{
return searchTrans;
}
}
}
return searchTrans;
}
}
源文件分享
文件名:ListWindowScaledAccording2Content
链接:
https://pan.baidu.com/s/1KQ-Du0qdOrzkbp1dFdGflA?pwd=c826
提取码: c826
需要将StreamingAssets放到Assets下才会跑