Luke Jones
Luke Jones

Reputation: 11

Jumping in Unity 2d

I got the moving left and right thing figured out, but i can't seem to get my player to jump. I have the code but i keep getting an error that says "The variable Player of Player.controller has not been assigned."

Here's the code:

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

public class Player_controller : MonoBehaviour
{
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    public Rigidbody2D Player;
    float JumpHeight = 10f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            Debug.Log("Moving Right");

            transform.Translate(Vector3.right * Time.deltaTime * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("Moving Left");

            transform.Translate(Vector3.left * Time.deltaTime * speed);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("Jumping");

            Player.AddForce(Vector2.up * JumpHeight, ForceMode2D.Impulse);
        }    
    }
}

Upvotes: 0

Views: 211

Answers (1)

Geeky Quentin
Geeky Quentin

Reputation: 2508

If the player has a rigidbody component, you can reference it in the Awake() method. If there isn't, just add the component

private void Awake() {
    Player = GetComponent<Rigidbody2D>();
}

Or else just drag the rigidbody component to its slot in the inspector

Upvotes: 1

Related Questions