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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Adding game manager using standard assets FPSController

Discussion in 'Scripting' started by dhenion65, Dec 24, 2019.

  1. dhenion65

    dhenion65

    Joined:
    Dec 17, 2019
    Posts:
    21
    I have a scene to which I've added the standard assets FPS Controller - it all works great but I want to add a separate Game Manager script that I can make calls to for end game, restart game, etc (still learning a lot of this.)

    My GameManager.cs file to start with is this:
    using System;
    using UnityEngine;
    namespace UnityStandardAssets.Characters.FirstPerson
    {
    public class GameManager : MonoBehaviour
    {
    public void RestartGame()
    {
    Debug.Log("GAME RESTART");
    }
    }
    }

    And in the FirstPersonController.cs file I've added this line:
    FindObjectOfType<GameManager>().RestartGame();

    I think the namespaces are set up correctly as the editor recognizes both the GameManager type and the RestartGame procedure.

    However, when I run the game and it gets to that line I get this error:
    NullReferenceException: Object reference not set to an instance of an object
    UnityStandardAssets.Characters.FirstPerson.FirstPersonController.FixedUpdate () (at Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs:162)

    The Game Controller object is in the scene but not sure what I am doing wrong, any ideas?
     
  2. dhenion65

    dhenion65

    Joined:
    Dec 17, 2019
    Posts:
    21
    Argh - right after posting this I thought I should double check the game manager script is plugged in the game manager object - and it wasn't, doh! I had deleted and rebuilt this trying to get it to work and missed that, its working now.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Glad you got it to work! Generally a GameManager is marked as
    DontDestroyOnLoad()
    and sticks around either permanently, or for the duration of the game, or just the duration of the game.

    Therefore you have to define "how long does this GameManager hang around?"

    Luckily there are dozens of examples out there as far as GameManagers to help you make decisions going forward.

    Good luck!