Hello,
I want to be able to try and get a component, but still continue through the code if it fails. Then use a check later before doing stuff with it, in case it didn’t work. However it asserts out if it can’t get a valid component. Here’s some code:
targetEnemy = ( Enemy ) transform.parent.GetComponent( typeof ( Enemy ) );
if( targetEnemy != null )
{
targetEnemy.SendMessage( "BlowUp" );
}
I tried to do a check before trying the GetComponent call, but I don’t know how to check without using GetComponent, which of course breaks it in the same way.
Any input would be great. I hope my issue makes sense! :shock:
Thanks,
-d
I don’t know what the problem is… A function returning Null if it didn’t find the component is pretty standard. It’s better than some random memory address in RAM somewhere.
If you’re getting Null and there really is a component attached of that type, then I would be concerned.
If you don’t want Null maybe you could get a list/array of all components of that type, and check if it’s there.
GameObject.GetComponents
I personally like working with Null and think it’s a fine solution, except I get a NullReferenceException error when this happens. I like to use Error pause in the console and generally try to keep red ! icons out of the mix. I guess this NullReferenceException may not technically break anything as I was saying before, but it would be nice to be able to stop it from showing up in this case.
Thanks for the help!
-d
a null ref exception or generally any exception you don’t handle means the rest of the whole callstack (so rest of the function and all that was meant to be called) is not called.
So you better do checks if its null or not unless you don’t care if your application is running 
depending on the platform and severity an exception means an instantly crashing app
Cool, this makes sense. How would you suggest I check for a null without actually getting a null and killing the callstack? 
Thanks you!
-d
Your original code won’t cause any null reference exception errors, but you seem to be missing the point of SendMessage. Instead of the GetComponent stuff, just do
transform.parent.SendMessage( "BlowUp", SendMessageOptions.DontRequireReceiver );
–Eric
Good point about SendMessage! These are the kinds of issues I’m sure it was designed to avoid. 
Thanks guys, this thread has cleared up a lot.
Cheers,
-d