#GetComponent on null references

1 messages · Page 1 of 1 (latest)

crystal prism
#

when you do playerRB.GetComponent<Rigidbody2D>(), you're asking playerRB to check the game object it's attached to for a Rigidbody2D component.

#

but playerRB is null

#

so it throws an error

#

GetComponent<Rigidbody2D>() is equivalent to writing this.GetComponent<Rigidbody2D>()

#

This makes your component ask its game object if it has a Rigidbody2D on it

harsh coyote
#

yeah no im seeing it now notlikethis

#

the playerrb.

crystal prism
#

all of these are equivalent, assuming that the references are non-null

#
playerRB.GetComponent<Foo>();
gameObject.GetComponent<Foo>();
GetComponent<Foo>();
#

(assuming that we're writing these lines of code inside of a MonoBehaviour)