Home > OS >  Unity comparing gameobjects
Unity comparing gameobjects

Time:03-20

I'm learning Unity by trying to do things and then when ofc failing (Because that's life about XD) then I'll try to find some scripts to learn from.

I was trying to make a smooth platformer controller and then ran into a video from Brackeys

I'm having trouble understanding this line of code:

        if (colliders[i].gameObject != gameObject)
        {
            m_Grounded = true;
            if (!wasGrounded)
                OnLandEvent.Invoke();
        }
    

(Full script can be found here: https://github.com/Brackeys/2D-Character-Controller/blob/master/CharacterController2D.cs)

It's that line 54 the one that is making me have problems.

if (colliders[i].gameObject != gameObject)

What is he comparing? The first one is the gameobject attached to the collider but the second one is the default class, can someone explain what is he trying to do here?

CodePudding user response:

Notice that Monobehvaiour inherits from component. So it has access to all its properties gameObject, transform ..etc. Check component documentation

So in the snippet

if (colliders[i].gameObject != gameObject)
    {
        m_Grounded = true;
        if (!wasGrounded)
            OnLandEvent.Invoke();
    }

you are comparing the specific array's object (colliders[i].gameObject) with the current monobehaviour the code is running in (gameObject or this.gameObject). In a class, you can access all the public and protected members it inherits from skypping the this keyword, as it can be understood you refer to the current instance by default.

Hope that makes sense.

  • Related