I’ve searched up the plethora of threads regarding this topic and for whatever reason, can’t get it to work. I’m guessing it’s going to be something super simple that I overlooked so thank you in advance for your patience.
Basically:
I have “CurrentHealth” as a public int on my Player Script (the script itself is called “PlayerScript” and is attached to my “Player” game object)
I have my enemy game objects with their attached “Enemy” script. Upon collision, the enemy script calls “PlayerHit()”.
I want “PlayerHit()” to find the PlayerScript (which is on the Player), access the “CurrentHealth” variable within the PlayerScript, and change it to whatever.
This compiles without error, but upon collision in-game, it crashes with the error “Object reference not set to an instance of an object”. I guess I figured that this would find the “Player” game object, get the PlayserScript component on it, and change the “CurrentHealth” public int by -10.
Would appreciate some pointers for what I’m getting wrong here.
Don’t use GameObject.Find(), it’s wasteful and there are always other ways to do it. The Enemy collides with the Player, so you can get a reference to the script that way:
I have heard about the evil that is gameObject.Find and it turns out that it was also responsible for the error I was getting. Instead of preserving my player between scenes, I simply had a Player GameObject in each scene. I’m using an Editor Script to spawn at a certain scene and the GameObject.Find was searching for “Player” in a different scene.
In any case, I do like your method of getting the PlayerScript better and I’ll change to that. Thank you for the advice!