- Home /
Cannot get position of other objects
I am trying to get the position of the player each frame from another script but using public GameObject player
and then going in the editor and trying to change the player value to the player in scene did not work and I had to copy the player to the assets folder and then move it there. Annoyingly enough though, this gave (0, 0), (I'm working in 2D), because the object in the assets folder would not update its position. I know that the answer is probably really obvious but I am probably the newest you can get with Unity, I don't even have any other experience in C#.
Answer by Legend_Bacon · Aug 06, 2018 at 04:13 PM
Hello there,
"moving the player into the assets folder" in Unity, creates a prefab of that object. A prefab is used to quickly instantiate pre-set objects, that already have their own components, values etc. (For example, in an RPG you would have a goblin prefab, and create X instances of that prefab instead of making a brand new goblin every time).
If you reference your prefab in your script, that means you're getting the position of the PREFAB every frame, instead of your player in the game scene. To fix that, either assign your player (the one in the scene, not the assets folder) to your script manually, or have your program find it at the beginning.
Here's an example:
public GameObject go_player = null;
//This is called ONCE automatically on any Monobehaviour Object, at the beginning
private void Start()
{
if (go_player == null)
go_player = GameObject.FindGameObjectWithTag("MyPlayer");
}
//This is called EVERY FRAME automatically on any Monobehaviour Object
private void Update()
{
Debug.Log("Player POS: " + go_player.transform.position.ToString());
}
The only thing left to do is to give your player object the tag "MyPlayer", so your program can find it. For that, click on your object, then in the top-left of the inspector hit the "Tag" dropdown. You can then add a new tag, and give it to your player.
I hope that helps!
Cheers,
~LegendBacon
Thanks so much now I can continue on my game again, I didn't even know prefabs existed.
Also, ONE THOUSAND THREE HUNDRED TEN REPUTATION??????? HOW
Hey there, thank you for accepting my answer. I'm glad I could help!
If you're impressed with 1000 points, wait until you see some of the true experts on this page...
Answer by MT369MT · Aug 06, 2018 at 04:07 PM
Hi, player is only a variable. Before using it you must assign it. You can do it in the inspector (drag and drop the player in your "none (GameObject)" field or you can assign it in script for example:
public GameObject player;
public Vector2 playerPosition;
void Start ()
{
player = GameObject.Find("Player");
}
void Update ()
{
playerPosition = player.transform.position;
}
This will assign the variable player with the object in the scene called "Player". Ask if you need something else.
Thanks for the answer but no offense Legend_Bacon made his/her answer cleaner so I accepted his/hers.