I did a search for an element of the required data type in the GameObject[] array, but I would like to do it via LINQ, how do I do it?
I did it through the foreach loop, but I need to through LINQ
private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
if (scene.buildIndex == 2)
{
var sceneObjects = scene.GetRootGameObjects();
foreach (var obj in sceneObjects)
{
if(obj.GetComponent<SumoUIManager>())
sumoUIManager = obj.GetComponent<SumoUIManager>();
}
}
}
CodePudding user response:
Using the LINQ First
or FirstOrDefault
method, you should be able to filter the sumoUIManager
from the array:
var sumoUIManager = sceneObjects.FirstOrDefault(x => x is SumoUIManager);
Note: First
will throw an exception if there is no object of the SumoUIManager
type in the array whereas FirstOrDefault
will return null.
CodePudding user response:
In LINQ, the above code would be as follows:
var sceneObjects = scene.GetRootGameObjects();
var sumoUIManager = sceneObjects
.Where(obj => obj.GetComponent<SumoUIManager>() != null)
.Select(obj => obj.GetComponent<SumoUIManager>())
.FirstOrDefault();