Search Unity

Resolved What Does SharedInstance = this; mean?

Discussion in 'Getting Started' started by Gummi_Ghost, Mar 19, 2022.

  1. Gummi_Ghost

    Gummi_Ghost

    Joined:
    Sep 21, 2020
    Posts:
    35
    I was doing this unity tutorial: Introduction to Object Pooling - Unity Learn, and I do not understand the code in the Awake function.
    Code (CSharp):
    1. public static ObjectPool SharedInstance;
    2. public List<GameObject> pooledObjects;
    3. public GameObject objectToPool;
    4. public int amountToPool;
    5.  
    6. void Awake()
    7. {
    8.     SharedInstance = this;
    9. }
    10.  
    11. void Start()
    12. {
    13.     pooledObjects = new List<GameObject>();
    14.     GameObject tmp;
    15.     for(int i = 0; i < amountToPool; i++)
    16.     {
    17.         tmp = Instantiate(objectToPool);
    18.         tmp.SetActive(false);
    19.         pooledObjects.Add(tmp);
    20.     }
    21. }
    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?
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    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:
    Code (CSharp):
    1. public class Example
    2. {
    3.   int myVar;
    4.  
    5.   void SetMyVar(int myVar)
    6.   {
    7.     //Without "this", C# wouldn't know you meant the global "myVar" variable,
    8.     //and not the local "myVar" variable passed into this method.
    9.     this.myVar = myVar;
    10.   }
    11. }
    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".
     
    Last edited: Mar 19, 2022
    Gummi_Ghost likes this.
  3. Gummi_Ghost

    Gummi_Ghost

    Joined:
    Sep 21, 2020
    Posts:
    35
    Oh, I see, thank you!
     
  4. Serajio

    Serajio

    Joined:
    Sep 12, 2022
    Posts:
    1
    Thanks for asking this question and thanks for a very well explained answer!