Check for Missing Component

hi

I am getting an error about my object not having an Animation component - which is correct, it is on the object’s parent

how can I do a check to see if the Animation component exists so I can redirect before it throws an error?

if I ask for GetComponent(Animation), it returns UnityEngine.Animation (in the console) when I was expecting “null” -like I get if I ask for a script that doesn’t exist on it

am guessing this is really simple- but so far I can’t seem to figure this out

thanks in advance!

You could use a try catch if your using C# not sure how to do it in java

try
{
//return or play animation 

}
Catch
{
//if error do this
}

Does the RequireComponent attribute help you out here?

You could try:
if (animation != null) {

I believe it’s one of the linked components on a transform, so the above should work just fine.

Ya

should work i was thinking of more of a null pointer exception.

:slight_smile: [/code]

thanks for all of the ideas!

“try” worked until I actually tried an animation in the try section, then errored again

RequireComponent wouldn’t work because the animation was on the parent

if (animation != null) {
worked fine! - which is odd because I could have sworn that’s what I originally tried :slight_smile:

I must have messed up the syntax (it was late…)- still learning javascript, Unity’s implementation of it, and all the other little gotchas

thanks much everyone- my code is all neat and tidy now- at least that part!