Search Unity

Question Unity 2021.3.20f1 Transform.position doesn't move character

Discussion in 'Scripting' started by Macrollat, Mar 11, 2023.

  1. Macrollat

    Macrollat

    Joined:
    Aug 5, 2019
    Posts:
    4
    Hello to all. I'm new to coding and I've been having troubles trying to get my ship to move in a Schmup mockup project I'm currently developing. I've searched the forums for days now but can't seem to find out what I'm doing wrong (could be something REALLY obvious, but like I said I'm new to this). I've stored the transform of my GameObject in a Vector2 variable and incremented it with input from the player, but even if in the Debug.Log I get visible changes to the coordinates, the ship doesn't move at all. Any help would be appreciated.

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class Ship : MonoBehaviour
    7. {
    8.     [SerializeField] private float moveSpeed = 10f;
    9.  
    10.     void Update()
    11.     {
    12.         ShipMovement();
    13.        
    14.     }
    15.     private void ShipMovement()
    16.     {
    17.         float horInput = Input.GetAxisRaw("Horizontal");
    18.         float verInput = Input.GetAxisRaw("Vertical");
    19.         Vector2 shipPos = transform.position;
    20.         Vector2 movInput = new Vector2(horInput, verInput) * moveSpeed * Time.deltaTime;
    21.         shipPos += movInput;
    22.         Debug.Log(shipPos);
    23.     }
    24.  
    25. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Macrollat likes this.
  3. Macrollat

    Macrollat

    Joined:
    Aug 5, 2019
    Posts:
    4
    Thank you SO much! This is perfect, I'll read more on that, bless you :D
     
    Kurt-Dekker likes this.
  4. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    720
    A related note: it being a value type is also why this doesn't work:

    Code (CSharp):
    1. whatever.transform.position.y += 3;
    whatever.transform.position
    is giving you a value type, so trying to modify its
    y
    field is nonsense: you'd be modifying the copy, leaving the original untouched!
     
    Macrollat and Kurt-Dekker like this.