Unity中多个物体交换位置

在做新需求的时候,遇到了一个棘手的问题,自己再用各种方式都无法解决,并且写的代码很难阅读,而且复杂度是O(n^2),在大神的帮助下解决了,特此记录..

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UITest : MonoBehaviour
{
    public List<GameObject> obj = new List<GameObject>();

    private int[] preArray = {0, 1, 2, 3, 4};
    private List<Vector3> posList = new List<Vector3>();

    private void Start()
    {
        for (int i = 0; i < obj.Count; i++)
        {
            Vector3 pos = obj[i].GetComponent<RectTransform>().anchoredPosition;
            posList.Add(pos);
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            int[] curArray = {4, 3, 1, 2, 0};
            SortObj(curArray);
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            int[] curArray = {3, 4, 2, 1, 0};
            SortObj(curArray);
        }
    }

    void SortObj(int[] curArrayInt)
    {
        for (int curIndex = 0; curIndex < curArrayInt.Length; curIndex++)
        {
            //获取当前下标中新数组的位置信息 比如 [0] = 4,这个时候GameObj4 就需要换到 posList[0]的位置
            int tgtIndex = curArrayInt[curIndex];
            GameObject objT = obj[tgtIndex];
            objT.transform.localPosition = posList[curIndex];
        }
    }
}

代码和界面逻辑如上,其实一个O(n)就能解决了...非常感谢大神的帮助..

原文地址:https://www.cnblogs.com/jbw752746541/p/14778457.html