Accessing instance of prefab from its own script

Hi, I’m trying to build a turn-based game in which a player can build units and move them around on subsequent turns. I’m doing this by instantiating the different kinds of units from prefabs, and having the different kinds of units all implement the same interface, so I can access their different behaviors from their own scripts.

I’m having trouble accessing the prefab’s own instance from its script. This is probably an easy fix but I just don’t know it - I’ve been breaking my game for hours trying to figure it out lol. Here’s the script for a unit “Runner” that handles what I mentioned. It has a lot more code but I think the problem is exemplified in this sample.

public class Runner : MonoBehaviour, ICharacter
{
    private Tile currentTile;

    private void Start()
    {
        currentTile = TileManager.FindTile(this.transform.position);
    }

As you can see, “this.transform.position” is not what I would like it to be: it’s accessing the prefab’s position, not the instance’s, so the FindTile method returns as null. Is the only way to fix my issue to assign a GameObject to the “Runner” class and assign it to its instance on instantiation? This seems unnecessarily clunky. Thanks a bunch.

The keyword you’re looking for is ‘this’. It’s actually a C# keyword, and it’s a reference to the self-object.

Ex:

  • this.transform = {stuff};
  • this.Start();
  • this.currentTile

Note that ‘this’ doesn’t point to a prefab. It points to an instance of a Monobehavior on an instantiated object. So once a prefab is instantiated, the Runner behavior on that instantiated object can act on itself using ‘this.’

You can also use the keyword ‘gameObject’ with a lower-case ‘g’ to refer to the GameObject that the script is attached to.