GameObject.FindWithTag is actually the least expensive method of finding the player, aside from creating a Player Singleton, which we have avoided in this course. It’s significantly (REALLY!) faster than FindObjectOfType<PlayerController>()
because FindWithTag simply calls CompareTag(“Player”) on each object in the scene in order. FindObjectOfType has to go through each GameObject in the scene and examine each component until it finds a PlayerController component.
That being said, it’s still possible to utilize a Player Singleton while still not having that player persist between scenes (which complicates our saving system, and creates the potential for null references that have to be addressed). One’s first thought would be to have the PlayerController responsible for containing the Singleton, but I actually prefer to make a PlayerTag class
using UnityEngine;
namespace RPG.Core
{
public class PlayerTag : MonoBehaviour
{
public PlayerTag instance;
void Awake()
{
instance = this;
}
void OnDestroy()
{
if(instance==this) instance = null;
}
}
}
That’s it, that’s the whole class, and you slip it on the Player,
Then you can call
PlayerTag.instance
instead of
GameObject.FindWithTag("Player");