What exactly is "this"?

Did the this.img = img; line trip you up? Here's what's going on with that.

The Card class has an instance variable called img. We're also passing an argument to its constructor function with the exact same name, img. If we simply wrote img = img;, that means we'd be setting the value of the argument to the value of the argument. Hunh! That's not quite what we're after.

By specifying this.img = img;, we're saying that we want the img variable attached to this, the Card class, to have the same value as the argument called img.

It's a smidge confusing, I'll admit. So, why not just call the argument something different? You absolutely could! We did it this way because it's very common to see variables passed to the constructor ...

Get Unity 4.x Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.