GameObject.FindWithTag("Player").transform; not finding spawned player

I have a player that is spawned into the game on start, and the “GameObject.FindWithTag(“Player”).transform;” is supposed to find it. The script only seems to update if I have the gameobject with the script for this selected in the hierarchy, otherwise it seems to not be able to find the player.

The spawned(or cloned) player most certainly has the player tag, i’m currently at a loss as to why it can’t be found.
When the gameobject is selected it does show that the cloned player is there. This script works perfectly fine if the player doesn’t need to be spawned in, but it does in my case.

   public Transform Player
        {
            get
            {
                return _player;
            }
            set
            {
                _player = GameObject.FindWithTag("Player").transform;
          
                if (_player != null)
                {
                    playerCharacterController = _player.GetComponent<CharacterController>();
                }
                else
                {
                   playerCharacterController = null;
                }
    
            }
        }

You can add a new Tag which named “myPlayer” to replace the “Player” Tag.
I fixed my problem that way.

A few things:

  • “The spawned(or cloned) player most certainly has the player tag” ← That doesn’t sound like you actually checked the tag…
  • The first part about it only working when you select the object in the hierarchy sounds too random, that probably has nothing to do with your problem.
  • You’re defining a setter for the property Player that’s not using the “value” keyword anywhere. Do you know how properties work? The setter is called ONLY when you assign a value to the property, and the value you assign is referenced by “value”.

So, it looks like you just defined the setter and you’re expecting it to just be executed automatically. If FindWithTag couldn’t find your player you’ll be getting a null pointer exception on that line, since you’ll be trying to access the transform field of a null GameObject reference, but you didn’t mention the null reference, so that code probably never runs in the first place.

You should share more code, but what you seem to be trying to do is this:

public Transform Player {
    get {
        if (_player == null)
            Player = GameObject.FindWIthTag("Player");
        return _player;
    }
    set {
        if (value != null) {
            _player = value.transform;
            playerCharacterController = _player.GetComponent<CharacterController>();
        } else {
            _player = null;
            playerCharacterController = null;
        }
    }
}