Sometimes a bit quirky…
How can I cast GO to a GameObject to access as default?
foreach (var GO in FindObjectsOfType(SourceComponent) as GameObject)
foreach (GameObject GO in FindObjectsOfType(SourceComponent))
or var g = (GameObject)GO;
doesn’t work again :-/
foreach ( ??? GO in FindObjectsOfType(SourceComponent)) {
}
The method doesn’t know the return type at compile time since the type is a variable.
But all unity objects inherit from the type UnityEngine.Object, so they’re returned as that.
You can cast to some type you know they are after that… if you know the type going in. In your case you know it’s going to be a Component, so you can cast it to Component. (or at least I assume, since you named the variable ‘SourceComponen’).
Yes, I want to sort GOs by name and component into other game objects with a specified name and components.
If you have working generic example for the upper one would be great. Is there any benefit in a generic solutions?
With generics, there are often fewer type casts. And if you try to avoid them, the overall design becomes often more maintainable.
WARNING: UNTESTED CODE
void SelectGOByComponent <T> () where T : MonoBehaviour {
foreach (T yourComponent in FindObjectsOfType <T>()) {
// yourComponent can directly be used or yourComponent.gameObject if you need the game object of it.
}
}