简体   繁体   中英

How can I move item from end of list to the start?

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;
            }
        }
    }
}

In this part I want to take the last object in the list and move it to the start of the list:

if(distanceTravelled >= 50.0f)
                    {
                        objectsMoving.Remove(objectsMoving[objectsMoving.Count]);
                    }

The idea in general is to move the last item object from the list to the start of the list and keep moving the objects all the time but each time the last object in the list is distanceTravelled >= 50.0f move it to the start of the list. Same idea as cyclic if I'm not wrong.

Do something like this:

if(distanceTravelled >= 50.0f)
{
    var moveToFirst = objectsMoving.Last();
    objectsMoving.RemoveAt(objectsMoving.Count-1);
    objectsMoving.Insert(0, moveToFirst);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM