0
votes

I'm trying to set my player's position to an cube's position in my scene.

I do this using the following function, which gets called when the object is selected:

public void PickCube ()
{
    Debug.Log(this.gameObject.transform.position); //this is different from the values in the editor
    Player p = GameObject.FindGameObjectWithTag ("Player").GetComponent<Player> ();
    p.SetPosition (gameObject.transform.position); //put the player at this cube
}

However, my cubes position in the scene is different from the position I'm attempting to get via gameObject.transform.position:

This is the position I see in the editor:

enter image description here

This is the position returned by Debug.Log:

(25.0, -6.9, 20.5)

Why am I getting different positions in the editor and code? I looked into global vs local position, and gameObject.transform.position.normalized, but neither of these were the problem or solution.

Update:

When I do Debug.Log(gameObject.name), it returns the name of the script "LevelCube". I thought gameObject was supposed to be the object the script is attached to?

1
what is setPosition? - Muhammad Faizan Khan
Does your object have parent, if it have then use localPosition. Also as mentioned by Mohammad what does SetPosition method do? - Ognjen Marceta
There is a difference between transform.position and transform.localPosition. Local position is relative to the parent, and I believe this is what shows up in the inspector. Try using localPosition or make sure that your gameObject has no parents. - pseudoabdul
My object does not have a parent that I'm aware of. And SetPosition is in my Player class. It sets my player's position at the object's position: this.transform.position = v; (where v is a Vector3). - Ethan Fischer
using gameObject or this is redundant. Just do transform.position. Is it neccesary to do it using SetPosition? Could you instead also directly set the position on the Player GameObject without that component? (GameObject.FindGameObjectWithTag("Player").transform.position = transform.position) - derHugo

1 Answers

0
votes

1.) Just use (this).transform.position rather than your function

2.) If problem persists, try transform.localPosition instead