Search Unity

GameManager class error

Discussion in '2D' started by gkraken333, Oct 7, 2019.

  1. gkraken333

    gkraken333

    Joined:
    Sep 16, 2019
    Posts:
    7
    Hi, im working with a game manager who gets a player transform and a player prefab, i can assign these variables in the inspector directly, i worked with it in one scene and it work perfectly, but i tried to use in another scene and i have an Unassigned Reference Exception it says my variable PlayerSpawnPoint has not been assigned and probably need to assign in the inspector, but i don´t know why, because in the inspector te transform is assigned.

    Here is the code of my class:

    Code (CSharp):
    1.  
    2.     public Transform playerSpawnPoint;
    3.     public GameObject player;
    4.     public static GameManager instance { get; private set; }
    5.  
    6.     private void Awake()
    7.     {
    8.         if (instance == null)
    9.             instance = this;
    10.     }
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         instance = this;
    16.         player = GameObject.FindGameObjectWithTag("Player");
    17.         player.transform.position  = playerSpawnPoint.position;
    18.     }
     
  2. coidevoid

    coidevoid

    Joined:
    Oct 26, 2017
    Posts:
    55
    You should check if an instance of the GameManager is already loaded, just add
    Code (CSharp):
    1.  
    2. else
    3.     Destroy(gameObject);
    4.  
    to the Awake method.

    also you don't need to do it again in the Start method.

    Maybe that's where you issue comes from ?
     
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Your "PlayerSpawnPoint" is a reference to a scene object, so when you change scenes, that object is gone, and the variable becomes null. You'll need to get a reference to the spawn point in the next scene.
     
  4. gkraken333

    gkraken333

    Joined:
    Sep 16, 2019
    Posts:
    7
    Actually I already solved it, the problem was that I had assigned my game manager to another object and Unity didn't know which game manager prefers, but thanks for the reply and the time to read