I have a list of spawned enemies in my Canvas. The list is a stack of buttons that are spawned when the enemies spawn.
-
Canvas
-
Panel
-
Text
-
ScrollView
-
Viewport
-
Content
-
Scrollbar Horizontal
-
Scrollbar Vertical
I wish to sort them by distance from the player.
I have managed to accomplish the sorting of the list, but I can’t see how to reorder the children in the ScrollView.ViewPort.Content list.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
public class sortEnemies : MonoBehaviour
{
private Transform mytransform;
private List<ButtonScript> buttons = new List<ButtonScript>();
private ScrollView view;
private GameObject ContentPanel;
// Use this for initialization
void Start()
{
mytransform = transform;
view = mytransform.GetComponentInChildren<ScrollView>();
ContentPanel = GameObject.Find("Content");
InvokeRepeating("Sort", 10f, 3.0f); //call sort every 3 seconds, every frame is too much
}
// Update is called once per frame
void Sort()
{
buttons.Clear();
buttons.AddRange(GetComponentsInChildren<ButtonScript>());
//DistanceFromPlayer is a read-only property on my ButtonScript Script, calculated on call.
buttons = buttons.OrderBy(d => d.DistanceFromPlayer).ToList();
//this list looks like it sorts correctly.
List<GameObject> ButtonList = buttons.Select(d => d.gameObject).ToList();
//NOW HOW DO I LOAD THE LIST BACK INTO THE ScrollView->Viewport->Content?
}
}
This is the Button Script (so far):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour {
public GameObject myEnemyObject;
private Transform Player;
private Text myText;
public float DistanceFromPlayer
{
get
{
float answer = Vector3.Distance(Player.position, myEnemyObject.transform.position);
myText.text = string.Format("{0} {1:0}", myEnemyObject.name, answer);
return answer;
}
}
// Use this for initialization
void Start () {
Player = GameObject.FindGameObjectWithTag("Player").transform;
myText = GameObject.FindObjectOfType<Text>();
}
// Update is called once per frame
void Update () {
}
public void SetEnemy(GameObject Enemy)
{
myEnemyObject = Enemy;
}
}