How to replace EnableObjectPool with one line of code

manually iterating through a collection with for loops can lead to errors. You can get an early exit with one line of code

pool.FirstOrDefault(x => !x.activeInHierarchy)?.SetActive(true);

In this example we find the first item in pool that has activeInHierarchy as false. The OrDefault part of the method will return null IF activeInHierarchy is true for all the objects. Then we call the method SetActive(true) on the object ONLY if it’s not null (that’s the ?. part. The ? will only call the method if the returned object in not null)

3 Likes

This is cool. I didn’t know you can do that.

Not particularly fond of nullables in this case, but yes, this totally works.

Privacy & Terms