Collider handling

Hi! I have 2 colliders on my player. Circle and Box Collider 2D. I need to switch between both when player jumps. I have the following implementation:

private BoxCollider2D Box;
private CircleCollider2D Circle;

void Start() {       
     BoxCollider2D = GetComponent<BoxCollider2D>();
     CircleCollider2D = GetComponent<CircleCollider2D>();
}

void update {
   if (Input.GetButtonDown("Jump")) {        
       Circle.enabled = true;    
       Box.enabled = false;
    } else {
       Circle.enabled = false;
       Box.enabled = true;
    }
}

Could someone inform, what’s wrong with my logic? It doesn’t work, the exchange doesn’t happen (I followed it through the inspector and there is no change when I execute the jump).

GetButtonDown is only true on the frame when the player presses the button. I assume you didn’t want to change the collider for only 16 milliseconds. if you use GetButton instead, then it will change the collider for as long as the player is holding the button down.

Edit: also, Update not update.

2 Likes

You never actually define Circle or Box either. I’m surprised that compiled for you.

1 Like

This is exactly the mistake made (GetButton). A detail that I missed without noticing. Update went wrong when adding the code, there in the project is correct with the capital U. With GetButton it is working the way you would like. Thanks.

Why shouldn’t I define them?

I meant this part in your code

private BoxCollider2D Box;
private CircleCollider2D Circle;
void Start() {    
     BoxCollider2D = GetComponent<BoxCollider2D>();
     CircleCollider2D = GetComponent<CircleCollider2D>();
}

You see where you define the names of BoxCollider2D as Box and CircleCollider2D as Circle. Yet in the Start function, you didn’t reference Box with Box = GetComponent<BoxCollider2D>(); but its type with BoxCollider2D = GetComponent<BoxCollider2D>();. Just confused me why this worked for you.

With the way you have it typed, it should be throwing a null exception.

1 Like

I doubt it’s even compiling. There is no variable named “BoxCollider2D”, at least not in the code we see, so there’ll be a compile error on that line. If the code is running at all, it’s an older version of the script from when it did compile.

Also… the Scripting section is the place to go for this. General Discussion is not a support area!

2 Likes

So, in my project code it’s correct, for that reason it compiles (I must have changed it I didn’t change it in this post, my fault). So it is corrected. The real doubt was even related to the collider.

Correct code (if anyone needs):

private BoxCollider2D Box;
private CircleCollider2D Circle;

void Start() {  
     Box = GetComponent<BoxCollider2D>();
     Circle = GetComponent<CircleCollider2D>();
}

void Update {
   if (Input.GetButton("Jump")) {    
       Circle.enabled = true;
       Box.enabled = false;
    } else {
       Circle.enabled = false;
       Box.enabled = true;
    }
}