Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How does putting return; at line 12 solve my prob of creating an xtra gameObj ,script is attached to

Discussion in 'Scripting' started by sahilsharma220202004, Jun 15, 2021.

  1. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    Code (CSharp):
    1. public class MainManager : MonoBehaviour
    2. {
    3.     public static MainManager Instance;
    4.  
    5.     public Color TeamColor;
    6.  
    7.     private void Awake()
    8.     {
    9.         if (Instance != null)
    10.         {
    11.             Destroy(gameObject);
    12.             return;
    13.         }
    14.  
    15.         Instance = this;
    16.         DontDestroyOnLoad(gameObject);
    17.  
    18.         LoadColor();
    19.     }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
  3. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    When I put return; at line12 , the gameobject this script is attached to is not created extra times during scene change.How?
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    If you don't return there, then here's what happens:

    1) Object A starts, sets "instance" to itself, and runs as expected.
    2) Object B starts. It sees "instance", so destroys itself. But because it continues running, it also sets "instance" to itself. So you now have object A (exists, but is not "instance") and object B is destroyed (leaving "instance" to point to nothing)
    3) Object C starts. Because B was destroyed, it sees that "instance" is null, and sets "instance" to itself. You now have A nd C in the scene, with C being "instance".
    4) Object D starts, and does the same thing as B did. You now have objects A and C, neither of which is "instance".

    And so on. So basically, every other copy of this will be left behind.
     
  5. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    So basically what did return; do here.
     
  6. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256