Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity comparing gameobjects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading