Code working for tutorial guy but not for me.

hatebin Here is the code, it is supposed to move the character left and right when pressing A and D but it doesn’t. Is something wrong with my code?

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

public class PlayerController : MonoBehaviour
{
    public Rigidbody2D rb;
    public float speed = 7;
    public float moveInput;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void FixedUpdate()
    {
        moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    }
}

Did you add the script to your game object? Does that gameobject have a Rigidbody2D?

Nothing seems wrong with your code, I added it to a project and it worked for me. Is nothing happening at all? Make sure to add a RigidBody2D component to the object that has this script. The speed could also be set to 0 in the inspector which would be a problem.


Some tips on the code:
Every variable that you have there could (and probably should) be private.
The Rigidbody2D variable rb could be private because you set it in the Start function.
The moveinput could be private because you set it in the FixedUpdate function.
The speed could be private but you probably want it as a SerializeField to still be able to change it in the inspector.

I would change it to :

private Rigidbody2D rb;
[SerializeField] private float speed = 7;
private float moveInput;