题目要求
1.在txt文件中读数据 并实例化对应游戏物体
2.场景中物体数量固定为6个,每三秒消失一个,并实例化下一个,直到消失完.
//AbsObj 类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class AbsObj : MonoBehaviour {
public abstract void DestroyObj();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjClass : AbsObj {
public override void DestroyObj()
{
Destroy(gameObject);
}
private void OnDestroy()
{
Debug.LogWarningFormat("DestroyObj position is {0}",this.gameObject.transform.position);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
public class ObjInfo
{
public string ObjName;
public Vector3 ObjPos;
public Quaternion ObjRot;
public ObjInfo(string name,Vector3 position,Vector3 rotation)
{
this.ObjName = name;
this.ObjPos = position;
this.ObjRot = Quaternion.Euler(rotation);
}
}
public class CreateManager : MonoBehaviour {
private List<GameObject> _ObjList;
private List<ObjInfo> _ObjInfoList;
private string _FilePath;
// Use this for initialization
void Start () {
_ObjList = new List<GameObject>();
_ObjInfoList = new List<ObjInfo>();
//Debug.LogError(StrTOVec3("1, 2, 1"));
_FilePath = Application.streamingAssetsPath + "/CopyInfo.txt";
ReadFileToList(_ObjInfoList, _FilePath);
for (int i = 0; i < 6; i++)
{
InstantObjInResourcesAddToList(_ObjInfoList[0], _ObjList);
_ObjInfoList.RemoveAt(0);
}
//_ObjInfoList.RemoveRange(0, 6);
StartCoroutine("LaLaLa");
}
IEnumerator LaLaLa()
{
while (_ObjList.Count > 0)
{
yield return new WaitForSeconds(3f);
int ranIndex = Random.Range(0, _ObjList.Count);
AbsObj abs = _ObjList[ranIndex].GetComponent<ObjClass>();
abs.DestroyObj();
_ObjList.RemoveAt(ranIndex);
if (_ObjInfoList.Count > 0)
{
InstantObjInResourcesAddToList(_ObjInfoList[0], _ObjList);
_ObjInfoList.RemoveAt(0);
}
}
}
private void InstantObjInResourcesAddToList(ObjInfo info,List<GameObject> Objlist)
{
GameObject tmp = Resources.Load<GameObject>(info.ObjName);
tmp.AddComponent<ObjClass>();
Objlist.Add(Instantiate(tmp, info.ObjPos, info.ObjRot));
}
private void ReadFileToList(List<ObjInfo> objInfos,string FilePath)
{
string readed = string.Empty;
using (StreamReader reader = new StreamReader(FilePath,Encoding.UTF8))
{
while (!string.IsNullOrEmpty(readed = reader.ReadLine()))
{
string[] infos = readed.Split('_');
ObjInfo info = new ObjInfo(infos[0],StrToVec3(infos[1]),StrToVec3(infos[2]));
objInfos.Add(info);
}
}
}
private Vector3 StrToVec3(string str)
{
Vector3 vec = new Vector3();
string[] strs = str.Split(',');
vec.Set(System.Convert.ToSingle(strs[0]),
System.Convert.ToSingle(strs[1]),
System.Convert.ToSingle(strs[2]));
return vec;
}
}