-1

I am confused how I can Lerp from inputDirection to targetInput when inputDirection has not yet been initialized, only defined. This piece of code is from a tutorial and I know it works, but I don't know why. My guess is that inputDirection is a special type of Vector3 that is a reference to user input or that the default value for Vector3 is (0, 0, 0), but my research so far has been unsuccessful.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.InputSystem;
 
 public class PlayerMovement : MonoBehaviour
 {
  private PlayerInputActions inputActions;
  private Vector2 movementInput;
  [SerializeField]
  private float moveSpeed = 10f;
  private Vector3 inputDirection;
  private Vector3 moveVector;
  private Quaternion currentRotation;
  void Awake()
  {
   inputActions = new PlayerInputActions();
   inputActions.Player.Movement.performed += context => movementInput = context.ReadValue<Vector2>();
   //Reads a Vector2 value from the action callback, stores it in the movementInput variable, and adds movementInput to the performed action event of the player
  }
  void FixedUpdate()
  {
   float h = movementInput.x;
   float v = movementInput.y;
 
   //y value in the middle
   //0 since no jump
   Vector3 targetInput = new Vector3(h, 0, v);
   inputDirection = Vector3.Lerp(inputDirection, targetInput, Time.deltaTime * 10f);
  }
 }
Jorge Morgado
  • 1,148
  • 7
  • 23
Wonjae Oh
  • 33
  • 7
  • Jorge gave you the correct answer. But to further elaborate: **ValueTypes** (like structs like Vector3 or int) copy their values whenever passed. Meaning if you change the value after you passed it to another method, you do not change the original value. **ReferenceTypes** (like classes like List) merely provide a reference when passed as parameters, thus you will alter the original object. If you do *not* want it to happen, you'd use the 'new' keyword to create a new instance of it. Understanding this is quite important and will solve a lot of problems. Also read into Structs. – Battle Oct 08 '20 at 06:52

1 Answers1

1

Vector3 is a struct (not a class) which means that all the fields inside of it are initialized with their default values. That's why it is (0, 0, 0) if you don't initialize by yourself with other value (because the default value of float, which is the type of x, y and z, is 0).

Jorge Morgado
  • 1,148
  • 7
  • 23