1

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>();
        }
    }
}
1
  • 2
    "but I need to through LINQ" - any particular reason why? Commented Dec 12, 2022 at 15:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.