What Does SharedInstance = this; mean?

I was doing this unity tutorial: Introduction to Object Pooling - Unity Learn, and I do not understand the code in the Awake function.

public static ObjectPool SharedInstance;
public List<GameObject> pooledObjects;
public GameObject objectToPool;
public int amountToPool;

void Awake()
{
    SharedInstance = this;
}

void Start()
{
    pooledObjects = new List<GameObject>();
    GameObject tmp;
    for(int i = 0; i < amountToPool; i++)
    {
        tmp = Instantiate(objectToPool);
        tmp.SetActive(false);
        pooledObjects.Add(tmp);
    }
}

I have trouble understanding this part:

void Awake()
{
SharedInstance = this;
}

I’ve googled this, and come up with nothing, I can’t wrap my head around what it means, or why it’s necessary. Could someone please explain?

The “this” keyword is simply a class’s reference to itself. A common usage of “this” is being able to differentiate between a global variable & a local variable with the same name:

public class Example
{
  int myVar;

  void SetMyVar(int myVar)
  {
    //Without "this", C# wouldn't know you meant the global "myVar" variable,
    //and not the local "myVar" variable passed into this method.
    this.myVar = myVar;
  }
}

In your particular example here, “this” is being used in what’s known as the singleton pattern, which states that there can only be one global instance of ObjectPool that other classes can reference by just calling the static ObjectPool.SharedInstance property.

What’s happening in Awake is that as soon as a new instance of ObjectPool is created, it will set SharedInstance to itself by using “this”. Basically meaning, “I am the SharedInstance”.

1 Like

Oh, I see, thank you!

Thanks for asking this question and thanks for a very well explained answer!