Search Unity

Question Transform of object working improperly

Discussion in 'Scripting' started by Danteb132, Apr 1, 2021.

  1. Danteb132

    Danteb132

    Joined:
    Jan 26, 2021
    Posts:
    8
    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.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemySpawner : MonoBehaviour
    6. {
    7.  
    8.     //X and Y locations for the spawner
    9.     [SerializeField] int xLocation;
    10.     [SerializeField] int yLocation;
    11.    
    12.     //Get enemy types
    13.     //Need to make more enemies
    14.  
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         ClampLocationValues();
    20.         MoveSpawner();
    21.     }
    22.  
    23.     void MoveSpawner() {
    24.         //Set the transform x and y coords
    25.         transform.position = new Vector3(xLocation, yLocation, 0);
    26.     }
    27.    
    28.     void ClampLocationValues() {
    29.         yLocation = Mathf.Clamp(yLocation, -12, 12);
    30.         xLocation = Mathf.Clamp(xLocation, -20, 20);
    31.     }
    32.  
    33. }
    34.  
    Thanks for any help that can be provided!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    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.
     
    Madgvox likes this.