- Home /
How can I get gameObject's all script components?
Is there a way to get a gameObject's all script components? For example, a gameObject is "Player", it has two script attached as components: "PlayerControl.cs" and "PlayerStatus.cs". How can I traverse all gameObject's script components? (different gameobjct has various script components..) I just want to traverse all gameObject's script components and then do a null reference check to make sure the game won't throw null reference exception... thanks in advance.
Answer by RudyTheDev · Dec 25, 2014 at 08:34 PM
To find all (public) Object-derived fields and check/report if they are null
:
void Awake()
{
#if UNITY_EDITOR
foreach (FieldInfo fieldInfo in GetType().GetFields())
if (fieldInfo.FieldType.IsSubclassOf(typeof(Object)))
if ((Object)fieldInfo.GetValue(this) == null)
Debug.LogError("Field " + fieldInfo.FieldType.Name + " " + fieldInfo.Name + " is null!");
#endif
}
Note: This won't work at runtime on iOS and probably some other platforms.
Get all components (technically, scripts):
gameObject.GetComponents<MonoBehaviour>();
Iterate with something like:
foreach (MonoBehaviour script in gameObject.GetComponents<MonoBehaviour>())
{
// ...
}
But they won't ever be null though, because they are attached properly. Perhaps this is not what your are asking? Any script that fails to reference another script would still throw NullRefExc-s.
If you are just looking for missing scripts:
if (gameObject.GetComponent<RequiredScript>() == null)
Debug.LogError("Missing RequiredScript!");
There are fancier (more optimized) ways to do this, but if you only do it once, it probably won't matter.
Edit: update per comment
Thanks for your answer! I really didn't describe this clearly. As you can see in the screenshot, the "CardSet" missed attached. so this will cause a nullRefExc.. cause there are so many game objects. I just want to traverse all the gameObjects' $$anonymous$$onnoBehaviour component to see if any one missed initialization.
thank you again.
Oh I see, you want to check the actual class's fields for null
. I updated the answer. Note that reflection is slow and GetValue()
(I'm like 95% sure) won't work on AOT platform, like iOS.
Great thanks for your answer! It now works! I can check each object's $$anonymous$$onoBehaviour (scrpts) component. Reflection is really a good way. Thanks!
i try to get all scripts of a certain type but i get a nullReferenceException. please check my question for more details it would be great if i could get an answer. https://answers.unity.com/questions/1433213/getcomponents-is-not-working-for-scripts.html