Home > OS >  can someone explain to me why my code dosen't work
can someone explain to me why my code dosen't work

Time:06-24

i was making code for a project (i'm new in c#) and i'm so confused as to why my code dosent work the code should make it so when a collider with the tag "floor" collides with my player it should change a variable, no errors are coming up but the variable dose not change , here's the code where the problem is

    void OnCollisionEnter2D()
{
    if (GetComponent<Collider2D>().tag == "FLOOR")
    {
        jump = false;
        Debug.Log("ITS A FLOOR");
    }
}

CodePudding user response:

Try this:

    void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "FLOOR")
    {
        jump = false;
        Debug.Log("ITS A FLOOR");
    }
}

My experience is mostly in 3D environments so I'm really not sure if I'm missing something, but your attempt to get a component doesn't make sense to me for two of reasons:

  1. You didn't mention for which game object you would like the collider
  2. The tag is found on the game object and not on the collider

CodePudding user response:

Considering you want the variable jump to change. Debug with a breakpoint at the line


jump=false

Make sure the program reaches that line and make sure the scope of the variable is what you expect.

CodePudding user response:

Going off the difference between "floor" in your description and then in your code, the string you are searching for may have different casing: "floor" != "FLOOR".

Try the following, if you need a case invariant string comparison:

if (string.Equals(GetComponent<Collider2D>().tag,"FLOOR", StringComparison.InvariantCultureIgnoreCase))

CodePudding user response:

There is no void OnCollisionEnter2D() in Unity, only void OnCollisionEnter2D(Collision2D collision) where Collision2D collision is the collision that your object (player) entered.

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "FLOOR")
    {
        jump = false;
        Debug.Log("ITS A FLOOR");
    }
}

CodePudding user response:

Aight, answers above already told the answer to the problem

void OnCollisionEnter2D()
{
    if (GetComponent<Collider2D>().tag == "FLOOR")
    {
        jump = false;
        Debug.Log("ITS A FLOOR");
    }
}

Is this code attached to the player? Or to the floor? I assume it's attached to the player, in this case GetComponent() will try to get the Collider2D from the player's entity or whatever, but not from the collision And you didn't declare the Collision2D parameter. Intellisense usually knows Unity's methods, might help you a lot

So, the right way to access tag from the collision would be

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "FLOOR")
    {
         //your code
    }
}

Hope you'll get around

  • Related