- Home /
How to get all components in scene which inherit a class
How to get all components from gameobjects in scene where those components inherit the same class?
For example: FindObjectsOfType(); // I'd like it to return components of type MachineGun, GrenadeLauncher, etc. which inherit CarWeapon
if you use C# then I just gave you the solution?
$$anonymous$$achineGun[] mgs = FindObjectsOfType<$$anonymous$$achineGun>();
foreach($$anonymous$$achineGun mg in mgs)
{
if(typeof(mg).IsSubclassOf(typeof (CarWeapon)))
{
//yes it inherits from CarWeapon
}
}
I believe this should work.
Answer by Huacanacha · Mar 29, 2015 at 09:11 PM
For components on active GameObjects:
BaseClass[] components = GameObject.FindObjectsOfType<BaseClass>();
For all active and inactive:
BaseClass[] components = Resources.FindObjectsOfTypeAll<BaseClass>();
These will find all BaseClass components as well as derived classes. In your case BaseClass would be CarWeapon.
Thanks. I was doing that, but didn't realized I was getting an error before it was called, so it didn't even get to that point. Dumb mistake.
Answer by DanBarreno · Jul 24, 2020 at 07:16 AM
Active and inactive components:
List<GameObject> rootObjectsInScene = new List<GameObject>();
Scene scene = SceneManager.GetActiveScene();
scene.GetRootGameObjects(rootObjectsInScene);
for (int i = 0; i < rootObjectsInScene.Count; i++)
{
BaseClass[] allComponents = rootObjectsInScene[i].GetComponentsInChildren<BaseClass>(true);
for (int j = 0; j < allComponents.Length; j++)
{
allComponents[j].DoSomething();
}
}
required namespaces:
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
Exactly what I was looking for - didn't occur to me to travel from the active scene.
Nifty LINQ equivalent:
var baseComponents = Scene$$anonymous$$anager.GetActiveScene()
.GetRootGameObjects()
.Select$$anonymous$$any(gameObject => gameObject
.GetComponentsInChildren<BaseClass>())
.ToList();
Answer by jean-noellevels3d · Sep 04, 2017 at 07:22 AM
Unfortunately, it does not work with other classes than Unity Objects... So if you want all interfaces derived classes, forget.
It does work with interfaces, however you probably have to use the non generic version that takes a System.Type as parameter. The generic parameter has a constraint to UnityEngine.Object
ps: of course the method can only find either $$anonymous$$onobehaviour derived or ScriptableObject derived classes which implement that interface. "Normal" classes are not trackable classes.
Your answer
![](https://koobas.hobune.stream/wayback/20220613191608im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
FindObjectsOfType not find all objects and code not do anything 0 Answers
Where is ScriptableObject.CreateInstance stored? 2 Answers
FindObjectsOfType for abstract generic class 0 Answers
Find all components of specific type, as fast as possible 0 Answers
FindObjectsOfType doesn't find instantiated objects 0 Answers