Displaying and storing screen co-ordinates of an object

Hello all,

I am novice here. I created a 3D game object (which is a sphere) that moves in circular direction. I have made the object move along x and z axis, with y axis remaining constant as following:

x = Mathf.Cos(angleRad) * radius;
y = 0.5f;
z = Mathf.Sin(angleRad) * radius;

My question is: When I press the ‘Play’ button or when the game object starts to move in a circle, Is there a method in unity that helps to display and store (in a .txt file) the screen co-ordinates of the game object as it moves along in the circle ?
How do I achieve this ?
Thank you

So there’s a few options for what you’re asking.

If you want to use the simple position of the object, you would use

float xPos = transform.position.x;
float zPos = transform.position.z;

If you want to use the true camera coordinates of the object, you would have to turn these into camera space:

Camera camera; //this needs to be assigned elsewhere


    Vector3 relPos = camera.WorldToScreenPoint(transform.position);
    float xPos = relPos.x;
    float zPos = relPos.y; //not a typo. Camera screen position is x and y, even though your object moves x and z

There’s two good ways that I know of to store this data. The first is PlayerPrefs:

PlayerPrefs.SetFloat("object x", xPos);
PlayerPrefs.SetFloat("object z", zPos);

float x = PlayerPrefs.GetFloat("object x");
float z = PlayerPrefs.GetFloat("object z");

The second is text files, as you said before:

System.IO.File.WriteAllText(Application.dataPath + "/Resources/Text/" + "xpos.txt", xPos.ToString());
System.IO.File.WriteAllText(Application.dataPath + "/Resources/Text/" + "zpos.txt", zPos.ToString());

float x = System.Single.Parse(System.IO.File.ReadAllText(Application.dataPath + "/Resources/Text/" + "xpos.txt"));
float z = System.Single.Parse(System.IO.File.ReadAllText(Application.dataPath + "/Resources/Text/" + "zpos.txt"));

Hope that helps.



Hey @Nomenokes ,
Many thanks for your help.
Just one thing for clarification though:

Vector3 relPos = camera.WorldToScreenPoint(transform.position);
float xPos = relPos.x;
float zPos = relPos.y;

The “camera.WorldToScreenPoint” gives the exact position (x and y position) of the game object (Sphere) in the co-ordinates that correspond to the x and y position of my laptop screen (that runs Unity game engine), right ?