1
\$\begingroup\$

In my Player script, I initialize my FirePoint transform using GameObject.Find in the Awake function. In the editor, I purposely misspelled the name of FirePoint to test if the null check inside of my Fire function will print an error to the console. The only error that shows up is from the Awake function giving a NullReferenceException, but why don't I see my Debug.LogError? Instead, the else statement prints that the FirePoint is not null.

public class Player : MonoBehaviour
{

   [HideInInspector] public Transform FirePoint;

   private void Awake()
   {     
       FirePoint = GameObject.Find("FirePoint").transform;
   }

   private void Fire()
   {
       if (FirePoint == null)
       {
           Debug.LogError("FirePoint is null.");
       }
       else
       {
           print("FirePoint is NOT null.");
       }
   }       
}
\$\endgroup\$
0
3
\$\begingroup\$

A possible explanation could be that you set FirePoint to something in the inspector before you added the [HideInInspector] attribute. Adding that attribute makes it impossible to change the inspector value, but if there is already one set it won't get cleared.

If GameObject.Find("FirePoint").transform throws a NullReferenceException, then that method gets aborted before a new value gets assigned to FirePoint. So it would retain the original value.

\$\endgroup\$
3
  • \$\begingroup\$ That worked. I removed the [HideInInspector] attribute and found that the original FirePoint transform was still in the serialized field. When I removed it, the problem went away. Thank you. \$\endgroup\$ – Sean Carey Jan 10 '20 at 3:20
  • 1
    \$\begingroup\$ You can also use the Reset option in the menu you get when you click on the top-right corner of the component in the inspector to forget all serialized values and re-initialize it from scratch. \$\endgroup\$ – DMGregory Jan 10 '20 at 13:11
  • \$\begingroup\$ @DMGregory I didn't know you could do that. Thank you. \$\endgroup\$ – Sean Carey Jan 11 '20 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.