help with player movement speed

i have this code for player movemant:

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

public class charcontroller : MonoBehaviour {

    [SerializeField]
    float Movespeed = 4f;

    Vector3 forward, right;

    // Start is called before the first frame update
    void Start()
    {
        forward = Camera.main.transform.forward;
        forward.y = 0;
        forward = Vector3.Normalize(forward);
        right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.anyKey)
            Move();
    }

    void Move()
    {
        Vector3 direction = new Vector3(Input.GetAxis("HorizontalKey"), 0, Input.GetAxis("VerticalKey"));
        Vector3 rightMovement = right * Movespeed * Time.deltaTime * Input.GetAxis("HorizontalKey");
        Vector3 upMovement = forward * Movespeed * Time.deltaTime * Input.GetAxis("VerticalKey");

        Vector3 heading = Vector3.Normalize(rightMovement + upMovement);

        transform.forward = heading;
        transform.position += rightMovement;
        transform.position += upMovement;
    }
}

How the heck do I change the player movement speed? I’ve tried to change the float value at the beginning but I’m so new at coding that the “f” in there is giving me an aneurysm if I change just the number nothing happens if I remove the “f” nothing changes ether. help.

Field initializers versus using Reset() function and Unity serialization:

I’m sorry but I might need it spelled out. I understand the problem but not the solutions you provided. how would I fix it in my situation? I’m sorry I’m EXTREMELY new at this (aka I started learning both unity and C# last night.)

  1. remove the 4f from your code utterly.

  2. go to the Unity inspector

  3. select the object with this script on it

  4. change the field there in the editor, NOT in code.

THANK YOU! I didn’t even notice that It added a movespeed field in the inspector.

The gist of those links I sent you is, “choose one mechanism: either code OR inspector.”

If you want to do it in code, remove the serialization decorator and make it private.

Doing both is only going to lead to confusion and inconsistency.

1 Like