- Home /
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
Answer by meat5000 · Jul 07, 2014 at 03:19 PM
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 worked! can you make that as an answer so I can give it the thumbs up.
Working code:
private static Transform _playerTransform;
public static Transform PlayerTransform
{
get
{
if (_playerTransform == null)
{
_playerTransform = GameObject.FindWithTag ("Player").GetComponent<Transform>();
}
return _playerTransform;
}
}
and just using PlayerTransform.position to get the updated position
Answer by Sigmac13 · Jul 25, 2017 at 10:18 PM
That answer is amazing! Works perfect. Thanks for the Working code too!
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Launching local Unity API Reference from MonoDevelop 7 Answers
Using C# how can I setup a "database" script? 1 Answer
creating reference via script 2 Answers
transform.Find(string)? 2 Answers