Transform of object working improperly

I have an object called Enemy Spawner, and I want to simply get two values from the script, the X and Y position. The x is clamped at -20 to 20 and the y is clamped at -12 to 12. Those values work fine but I want to set the transform.position of the object to the x and y values on the script with the z not changing. The transform.position changes but it does not change correctly. The video here has more info

And here is the code in the script. It is very simple yet I cannot understand why it is not working.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{

    //X and Y locations for the spawner
    [SerializeField] int xLocation;
    [SerializeField] int yLocation;
   
    //Get enemy types
    //Need to make more enemies


    // Update is called once per frame
    void Update()
    {
        ClampLocationValues();
        MoveSpawner();
    }

    void MoveSpawner() {
        //Set the transform x and y coords
        transform.position = new Vector3(xLocation, yLocation, 0);
    }
   
    void ClampLocationValues() {
        yLocation = Mathf.Clamp(yLocation, -12, 12);
        xLocation = Mathf.Clamp(xLocation, -20, 20);
    }

}

Thanks for any help that can be provided!

The position (and rotation and scale) values you see in the object’s inspector are it’s local position. Meaning, its position relative to its parent. When you set transform.position you are setting its world space position.

If the parent of this object has any nonzero position, rotation, or scaling, the world position and local position will not appear as the same values.

If you want to set the local position, use transform.localPosition.

1 Like