GetComponent Error

Updated on June 27, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on June 27, 2018

Hi, I’m making a sidescroller 3D game with the breakable script. I’ve attached a desrtuctible.cs script. Now when I fire through a FireBullet script, I’m looking for the destructible component on the hit variable in the raycast. The code is below


Destructible destructible = hit.GetComponent<Destructible>();
if(destructible != null){
//check health and replace the object with the breakable object

If the raycast hits anything without the destructible code, a null reference error pops out. Though this isn’t game breaking error, I still can’t clear out the error with a error check. please help



  • Liked by
0 on June 27, 2018

Try returning immediately if it’s null.

Destructible destructible = hit.GetComponent<Destructible>();
if(destructible == null) return;
// continue with the rest of the code here


It is weird that you’re getting the error though. This way, it makes sure nothing else happens if destructible is null, in case destructible is getting accessed somewhere else.

  • Liked by