using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveObjects : MonoBehaviour
{
public float speed = 3f;
private GameObject[] objectstoMove;
private List<GameObject> objectsMoving = new List<GameObject>();
private float distanceTravelled = 0;
private Vector3 lastPosition;
// Use this for initialization
public void Init()
{
objectstoMove = GameObject.FindGameObjectsWithTag("Test");
objectsMoving = new List<GameObject>(objectstoMove);
lastPosition = objectstoMove[objectstoMove.Length].transform.position;
}
// Update is called once per frame
void Update()
{
if (objectstoMove != null)
{
float step = speed * Time.deltaTime;
for (int i = 0; i < objectstoMove.Length; i++)
{
if(distanceTravelled >= 50.0f)
{
objectsMoving.Remove(objectsMoving[objectsMoving.Count]);
}
objectsMoving[i].transform.Translate((objectsMoving[i].transform.up + objectsMoving[i].transform.forward) * step);
distanceTravelled += Vector3.Distance(objectsMoving[objectsMoving.Count].transform.position, lastPosition);
lastPosition = objectsMoving[objectsMoving.Count].transform.position;
}
}
}
}
在这一部分中,我要获取列表中的最后一个对象并将其移动到列表的开头:
if(distanceTravelled >= 50.0f)
{
objectsMoving.Remove(objectsMoving[objectsMoving.Count]);
}
通常的想法是将最后一个项目对象从列表移动到列表的开头,并一直保持移动对象,但是每次列表中的最后一个对象距离为DistanceTravelled> = 50.0f时,都将其移动到列表的开始。如果我没记错的话,与循环相同。
答案 0 :(得分:2)
执行以下操作:
if(distanceTravelled >= 50.0f)
{
var moveToFirst = objectsMoving.Last();
objectsMoving.RemoveAt(objectsMoving.Count-1);
objectsMoving.Insert(0, moveToFirst);
}