I am trying to order a list of objects by their y-axis posistion. I have tried the following line:
objectsInScene = objectsInScene.OrderBy(x => x.transform.position.y);
, but I receive the following error:
error CS0266: Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<UnityEngine.GameObject>' to 'System.Collections.Generic.List<UnityEngine.GameObject>'. An explicit conversion exists (are you missing a cast?)
All help is appreciated. I have pasted my script below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
public class spawner : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<GameObject> objectsInScene = new List<GameObject>();
foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[])
{
if (!EditorUtility.IsPersistent(go.transform.root.gameObject) &&
!(go.hideFlags == HideFlags.NotEditable ||
go.hideFlags == HideFlags.HideAndDontSave))
objectsInScene.Add(go);
}
foreach (GameObject temp in objectsInScene){
if (temp.tag == "Populate"){
temp.SetActive(false);
}
}
objectsInScene = objectsInScene.OrderBy(x => x.transform.position.y);
StartCoroutine(Example(objectsInScene));
}
}
CodePudding user response:
Try calling ToList()
, as in
objectsInScene = objectsInScene.OrderBy(x => x.transform.position.y).ToList();
CodePudding user response:
I found another solution:
objectsInScene.Sort((o, o1) => o.transform.position.y.CompareTo(o1.transform.position.y));