Reputation: 15
I want to sort 5 spheres in Unity by using sorting algorithms. They will swap places in sorted order after I click sort button. I manage to create a list for gameobjects but as I understand it is only sorting the list then do nothing. How to create such script that I want? It will swap objects by gameobject name. The Envrioment, the code that I made so far;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Gameobjects : MonoBehaviour
{
public Button s_YourButton;
[SerializeField]
private GameObject[] deck;
public List<GameObject> instanciatedObjects;
void Start()
{
Button btn = s_YourButton.GetComponent<Button>();
//Calls the TaskOnClick method when you click the Button
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
Fill();
instanciatedObjects = instanciatedObjects.OrderBy(Sphere => Sphere.name).ToList();
}
public void Fill()
{
instanciatedObjects = new List<GameObject>();
for (int i = 0; i < deck.Length; i++)
{
instanciatedObjects.Add(Instantiate(deck[i]) as GameObject);
}
}
}
}
Any idea is welcome for me to do futher research, I am new to Unity.
Upvotes: 0
Views: 583
Reputation: 490
First you can do is store a list of Vector3 of the old one. basicly List.Add(spawnedObject.transform.position);
inside the for loop in Fill()
.
Then after you sorted them, you loop the instanciatedObjects
and set them in the same order as the Vector3 list.
List<Vector3> vectorList = new List<Vector3>();
void TaskOnClick()
{
Fill();
instantiatedObjects = instantiatedObjects.OrderBy(Sphere => Sphere.name).ToList();
for(int i = 0; i < instanciatedObjects.Count; i++)
{
instantiatedObjects[i].transform.position = vectorList[i];
}
}
public void Fill()
{
vectorList.Clear();
instantiatedObjects = new List<GameObject>();
for (int i = 0; i < deck.Length; i++)
{
GameObject spawnedObject = Instantiate(deck[i]) as GameObject;
instantiatedObjects.Add(spawnedObject);
vectorList.Add(spawnedObject.transform.position);
}
}
btw, a typo in your code: instanciatedObjects
should be instantiatedObjects
Upvotes: 2