读取Txt和实例化Txt内信息物体

txt内容

Cube_0,0,0_0,45,0
Cylinder_1,0,2_90,0,45
Sphere_2,2,2_45,45,45
Cylinder_1,2,2_90,0,45
Sphere_2,3,2_45,45,45
Cube_0,4,0_0,45,0
Cylinder_1,5,2_90,0,45
Sphere_2,6,2_45,45,45
Cube_0,7,0_0,45,0
Cylinder_1,8,2_90,0,45

在这里插入图片描述

代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//多态
//抽象类
public abstract class AbsObjClass : MonoBehaviour
{
      //虚方法
    public abstract void AbsDeath();
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjClass : AbsObjClass
{

    private float _blood;
    void Awake()
    {
        //Cube(Clone)   if(gameObject.name)
        _blood = Random.Range(10, 15);
    }

//定义一个子类 重写父类抽象方法 
    public override void AbsDeath()
    {
        Debug.LogWarningFormat("打击血量为:{0}",_blood);
        Destroy(gameObject);
    }

     void OnDestroy()
    {
        Debug.LogWarningFormat("Death  position is {0}",this.gameObject.transform.position);
    }

    
}

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;


/// <summary>
/// 存储信息的 
/// </summary>
class  CopyInfo
{
    public string     CopyName;//实例化对象名字
    public Vector3 CopyPosition;//坐标
    public Quaternion CopyRotation;//旋转角度

    public CopyInfo(string name, Vector3 postion, Vector3 rotation)//构造方法
    {
        CopyName = name;//赋值
        CopyPosition = postion;
       CopyRotation = Quaternion.Euler(rotation);
    }

}
public class CreateManager : MonoBehaviour
{

    private List<GameObject> _copyList;//储存实例化物体信息
    private List<CopyInfo>      _copyInfoList;//储存读取的信息

    private string _path;//定义路径
    //1. 读文件
    //2. 解析文件信息
    //3. 实例化
        //4. 实例化6个
        //4.1 在3s中销毁一个并且添加一个
	void Start () {
    //初始化
	    _copyInfoList = new List<CopyInfo>();
        _copyList = new List<GameObject>();
        //Application.streamingAssetsPath   文件夹 streamingAssets
	    _path = Application.streamingAssetsPath + "/CopyInfo.txt";//路径
        ReadFileToList(_copyInfoList,_path);//读取TXT内容和添加进List的方法
     Debug.LogWarning(_copyInfoList.Count);//读取添加进的List的内容行数
	    for (int i = 0; i < 6; i++)//实例化6个预制体
	    {
	        GameObject tmp = Resources.Load<GameObject>(_copyInfoList[i].CopyName);//tmp=加载资源(List下标为i的名字信息)
	        tmp.AddComponent<ObjClass>();//添加ObjClass脚本,用于调用方法
            //添加进实储存例化信息的List(游戏物体=实例化(名字,下标为i的坐标,下标为i的旋转信息))
	        _copyList.Add(Instantiate(tmp, _copyInfoList[i].CopyPosition, _copyInfoList[i].CopyRotation));
	    }
        _copyInfoList.RemoveRange(0,6);//实例化6个出来之后从_copyInfoList里删除(下标[0],6个),
	    StartCoroutine("IEMethod");//开启协程
	}


    IEnumerator IEMethod()
    {
        while (_copyList.Count >0)//_copyList行数大于0时执行
        {
            yield return  new WaitForSeconds(3);//间隔3秒
            int deleteIndex = Random.Range(0, _copyList.Count);//定义随机删除的下标
            AbsObjClass absObjClass = _copyList[deleteIndex].GetComponent<ObjClass>();//多态父类调用子类方法,获取要删除的的游戏物体并获取之前添加的脚本
            absObjClass.AbsDeath();//调用子类方法AbsDeath()删除此物体
            _copyList.RemoveAt(deleteIndex);//从储存游戏物体的LIst删除这个物体信息
            if (_copyInfoList.Count > 0)//再实例化出来一个物体
            {
                //加载出资源
                GameObject tmp = Resources.Load<GameObject>(_copyInfoList[0].CopyName);
                tmp.AddComponent<ObjClass>();//添加脚本
                //加进_copyList
                //相当于GameObject tm=Instantiate(tmp,_copyInfoList[0].CopyPosition,_copyInfoList[0].CopyRotation);
                //_copyList.Add(tm);
                _copyList.Add(Instantiate(tmp,_copyInfoList[0].CopyPosition,_copyInfoList[0].CopyRotation));
                _copyInfoList.RemoveAt(0);//删除此信息
            }
          
        }
    }

	// Update is called once per frame
	void Update () {
		
	}



    // 访问类型 返回值   方法名称 方法参数 
    private void ReadFileToList(List<CopyInfo> list, string path)//读取信息
    {
        using (StreamReader reader = new StreamReader(path,Encoding.UTF8))
        {
            string tmpStr = string.Empty;//定义空字符串承接读取的内容
            //        非   判断是否为空字符串( 读取时不为空(false),读完为空(true))
            while (  !   string.IsNullOrEmpty(tmpStr = reader.ReadLine()))//读完跳出循环
            {
              string[] tmpInfos = tmpStr.Split('_');//读取的内容以'_'隔开
              //添加进 (方法CopyInfo(分隔开的字符串第一个,转化为V3后的位置信息,转化为V3后的旋转信息)
              CopyInfo tm=new CopyInfo(tmpInfos[0], StrToV3(tmpInfos[1]), StrToV3(tmpInfos[2]));
              list.Add(tm);
            }
        }
    }


    //strng --> v3
    //1,2,3
    private Vector3 StrToV3(string str)//字符串转换为V3
    {
        Vector3 tmp = new Vector3();
        string[] infos = str.Split(',');//字符串以','隔开
        tmp.Set(//写入V3参数
            System.Convert.ToSingle(infos[0]),
            System.Convert.ToSingle(infos[1]),
            System.Convert.ToSingle(infos[2])
            
            );


        return tmp;//返回V3信息
    }

}

List使用

  • RemoveAll()删除所有匹配到的项,参数是一个Predicate
    委托,用于定义要删除的元素应满足的条件。返回类型为int型,表示删除的个数。例如:

  • RemoveRange()删除指定索引段的项,第一个参数为删除的起始索引,第二个参数为删除的个数。范围类型为void。例如:

  • RemoveAt()删除指定索引的一项。参数为int ,表示索引。返回类型为void。例如:

  • Remove()删除List中匹配到的第一个项,参数为List中的T,返回类型为bool,成功删除返回True,失败或者没有找到返回False。

猜你喜欢

转载自blog.csdn.net/luxifa1/article/details/83062772