Search Unity

Question Difference between gameObject and this.gameObject in MonoBehaviour?

Discussion in 'Editor & General Support' started by pilfton, Apr 8, 2020.

  1. pilfton

    pilfton

    Joined:
    Mar 27, 2020
    Posts:
    2
    Beginner here, Following a course on 2D Unity development, I'm seeing my instructor uses for example
    Destroy(gameObject) but in the docs I see this.gameObject being used.

    Is there a difference? And what's the most C# method? (I'm coming from php/javascript)
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    Generally, they would mean the same thing. No difference.

    In C#, the word "this" refers to the current class. When you write:
    this.gameObject
    you're telling the compiler "I'm talking about the gameObject that's a member of this class", but you don't actually need to write "this" unless there is more than one variable with the same name in scope and you want to make sure the compiler knows which one you're talking about (That's an unusual situation, though).
    You could also just write
    gameObject
    as long as there's no other variable named gameObject in scope.
     
  3. tribaleur

    tribaleur

    Joined:
    Jan 19, 2017
    Posts:
    34
    Hello,

    I personnaly prefer to add this behind all my properties name in custom class because it's easier to read in my opinion.
    For the same purpose, i like to prefix all my properties name by "_". With auto completion you just need to write "this._" and then your IDE will list all your properties. It's very convenient ;)