0
\$\begingroup\$

For my player controlling script, I have attempted to do it so the player can only jump two times, I've not had any errors in the script itself but when I save it and go back on Unity, the error I keep getting is this:

error CS0120: An object reference is required for the non-static field, method, or property Collision.gameObject

This is my code:

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

public class playerController : MonoBehaviour
{
    public float speed;
    public float power;
    private Rigidbody2D rb;
    int numberofJumps = 0;
    public int doubleJump = 2;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        numberofJumps = doubleJump;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(Vector3.right * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(Vector3.left * speed);
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            if (numberofJumps > 0)
            {
                Jump();
            }
        }
    }

    public void Jump()
    {
        rb.AddForce(Vector3.up * power, ForceMode2D.Impulse);
        numberofJumps -= 1;
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (Collision.gameObject.tag == "ground") 
        {
            numberofJumps = doubleJump;
        }

    }
}

The error seems to be specifically regarding this line:

if (Collision.gameObject.tag == "ground")
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You're attempting to make a static call on the Collision class. Try replacing this line

Collision.gameObject.tag == "ground"

With the reference to the object col passed in

col.gameObject.tag == "ground"
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Man, thank you so much. I can't believe it was that simple. \$\endgroup\$ Commented Apr 17, 2020 at 1:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.