Not understanding collisionDisabled

Hi,

Really enjoying this course so far!

Could someone please explain to me how the boolen collisionDisabled works in this code? I’m aware it can be called anything and it will still work. I just don’t understand the logic behind it or how Rick would come to this conclusion to use it in the first place?

Hi,

In Unity, collisions happen between Collider components. When we disable a collider, nothing is able to collide with it anymore. Without a collision, the collision methods do not get called anymore.

With this in mind, check Rick’s code again. We have this line, which toggles the value of collisionDisabled:

collisionDisabled = !collisionDisabled;

If the value is true, it becomes not true, which is false. If the value is false, it becomes not false, which is true.

Next, let’s figure out where we use collisionDisabled in the code. It’s here:

void OnCollisionEnter(Collision other) 
{
    if (isTransitioning || collisionDisabled) { return; }

    // code
}

|| means ‘or’. return; terminates the method immediately. If collisionDisabled is true, we terminate the method immediately and do not execute the rest of the code.

As you can probably see, we do not disable the collision because we do not disable the Collider and/or the Rigidbody. OnCollisionEnter still gets called. What we do is to check if collisionDisabled is true.

Why did Rick name his variable collisionDisabled? Probably because it’s the simplest name for his idea. He skips the code we usually execute in our game if our rocket collides.

Is this what you wanted to know? :slight_smile:


See also:

1 Like

Thank you so much for the quick and detailed response! I understand it now!! I need to learn to break codes down into smaller chunks like in your explanation as it helps the learning process so much.

Yes, that’s a good idea. In fact, breaking down problems/ideas into little problems is exactly how object-oriented programming works. The earlier you start with it, the better. You could also use a pen and a sheet of paper to visualise the logic flow. Almost no experienced programmer writes a wall of code from scratch unless the problem is very simple. The code is getting developed. We “simply” add more and more little chunks until the main problem is solved. The difficult part is usually to break the problem down and identify the subproblems to solve.

C# itself is a rather easy language because we have a bunch of things such as methods, variables, if-statements, loops and so on which we use almost everywhere. We just combine them different ways to get our problems solved. You’ll very likely notice that yourself when developing a few games.

Happy coding! :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms