Your second code is absolutely right. Some people use FindGameObjectWithTag()
but others do use a public variable. That's the whole reason for Unity to offer them in the editor, to start with. So you can just drag stuff to scripts :)
I personally use the public variable when I'm in a situation that is just like yours, that is, you have one script and one Player that you want it to be attached to the script.
I consider that in this case, using a public variable is actually the right thing to do. Imagine if you decide later to make another Player prefab, switch to that, do some tests, switch back later... you could easily change them in the editor. If you used FindGameObjectWithTag()
, you'd have to change tags on both prefabs. Error prone.
Now imagine if you have multiple scripts using the Player. In this case, if you want to change the Player prefab, you'd have to change manually all the references in the editor. That's a lot of work, so maybe you'd just want to re-tag stuff.
In terms of performance, using the public variable is actually faster because it's a direct reference to the object, while FindGameObjectWithTag()
would look for the object. But this doesn't matter really, because FindGameObjectWithTag()
is very fast.