首页 > 编程语言 > 详细

Unity中多个物体交换位置

时间:2021-05-17 21:48:51      阅读:25      评论:0      收藏:0      [点我收藏+]

在做新需求的时候,遇到了一个棘手的问题,自己再用各种方式都无法解决,并且写的代码很难阅读,而且复杂度是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)就能解决了...非常感谢大神的帮助..

Unity中多个物体交换位置

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!