Helper properties get reference to player position

What im trying to do is create a standard static “helper” class that tracks the most used variables in my project so that I can find them quickly and easily, the first one i’m trying to setup is a way to get the player’s current position in the gameworld since it would be used often for enemy ‘AI’, i thought I would be able to do this with the following code.

basically I want the following:

private static Vector3? _playerPosition;
	public static Vector3? playerPosition
	{
		get 
		{
			if (_playerPosition == null)
			{
				_playerPosition = GameObject.FindWithTag ("Player").transform.position;
			}
			return _playerPosition;
		}
	}

if _playerPosition is nothing then use the expensive GameObject.FindWithTag to get a reference to the players position and then from now on when I need to retrieve this position then use the reference I have with _playerPosition instead of having to use the more expensive GameObject.FindWithTag function every single time I just need to get the players position.

unfortunately I only seem to get the hard value of the Vector3 the first time I call the GameObject.FindWithTag.

is there a way I can get the reference to the player’s position to do what I want here instead of what appears to be a copy of the value at that instant

The Red Triangle is Stationary The Green Triangle has moved position but there is no reported change when I do a debug.log(globals.PlayerPosition) after moving to a different location

(I am certain the call to GameObject.FindWithTag(“Player”) is correct as when I call it every time instead of trying to store the reference in the private field, the variable updates to reflect the correct current player position every time I request the current position to output to console)

Thanks

Use GetComponent to cache the transform you are trying to read. You can access the up to date info after this with the dot operator.

_playerTransform = GameObject.FindWithTag ("Player").GetComponent(transform);

Debug.Log(_playerTransform.position);

Perform the GetComponent once for each object.

That answer is amazing! Works perfect. Thanks for the Working code too!