I have only begun to use Unity a couple of months age, so I was learning with Unity Learn, under the course : Create With Code. While learning how to make code for player movement, I came across an issue. You see, while I am able to move forwards and backwards, I cannot turn left or right. I am writing the code according to the lesson. Please help me out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
private float speed = 20;
private float turnSpeed;
private float horizontalInput;
private float forwardInput;
// Update is called once per frame
void Update(){
horizontalInput = Input.GetAxis(“Horizontal”);
forwardInput = Input.GetAxis(“Vertical”);
// Move the car forward based on vertical input
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
// Rotates the car based on horizontal input
transform.Rotate(Vector3.up, turnSpeed * horizontalInput * Time.deltaTime);
}
}
With the code you have posted, you will have 0 (the C# default) for turnSpeed, and you won’t be able to change that in the Inspector because you declared the field as private. You need to use a public field or add SerializeFieldAttribute to make the field serializable and editable in the Inspector, following Unity’s rules for serialization. Also, it’s a good idea to set a default reasonable value for the fields, like you have done with the speed field, to ensure that newly created components start off with a usable value.