printed transform position doesn't match inspector transform position

I had a fairly complicated script that wasn’t behaving as I expected it to. After tearing my hair out trying to debug it for an hour, I decided to see what the simplest project I could reproduce my problem in was. Here we go:

New scene. Add a cube. Add a script to the cube with this code:

function Start() {
    transform.position = Vector3(Random.Range(-8.0, 8.0), Random.Range(-4.0, 4.0), 0.0);
    transform.rotation = Random.rotationUniform;
    print(transform.position);
}

I run that. It prints out: (2.6, -0.4, 0.0). I check the cube in the inspector: it gives a position of (5.182528, -0.9276977, 0), a rotation of (60.77962, 320.3119, 74.68745) and a scale of (1, 1, 1).

I’ve watched several hours of Unity lecture videos and now I’m attempting my first project… so I have maybe 10 hours of experience actually using Unity myself. I feel like there must be something really simple I’m missing here. Why is the position that’s being printed so different from the position that the inspector gives?

1 Like

Sounds like a difference between local and world positions.

Looking at or modifying transform.position will always return where the object is in World space, this is a position completely unrelated to any other object in the game.

What the inspector shows is the transform.localPosition of the object, which is where the object is located relative to its parent (or, if it has no parent, it’s the same as the world position).

I had the same issue where one of my objects was getting the wrong initial value at runtime, but had the right value in the inspector at design time.

My problem was that I had the object parented to an empty (to simulate organizing things into folders), and the empty’s transform was not located at (0,0) like I had assumed it was.

Resetting the empty parent’s transform and then moving everything back into position (and correcting related values) worked for me.

With a blank project and your script on a cube I get inaccuracy but it seems it’s due to rounding on the print function to 1dp. The figures you are getting are due to something else, not your script. You seem to have some extra factor of 2 in there. Do you have 2 instances of the script or something?

Try this

function Start() {
    transform.position = Vector3(Random.Range(-8.0, 8.0), Random.Range(-4.0, 4.0), 0.0);
    transform.rotation = Random.rotationUniform;
    print(transform.position);
	Debug.Log(transform.position.x.ToString()+" "+transform.position.y.ToString()+" "+transform.position.z.ToString());
    }

And post your results. As I say, looks like you have a factor of 2 in there…