I am attempting to make a game manager that handles all variables in a simple game I am making and am currently testing it on a timer. However, the var keyword is the only issue I am coming across regarding this so far. What changes would I need to make to get this to work? Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class timer : MonoBehaviour
{
public Slider Timer;
var gameManager;
// Use this for initialization
void Start ()
{
Timer = GetComponent<Slider>();
GameObject gameManager = GameObject.Find("GameManager");
Functions functions = gameManager.GetComponent<Functions>();
}
// Update is called once per frame
void Update ()
{
gameManager.startTime -= Time.deltaTime;
Timer.value = gameManager.startTime;
if (gameManager.startTime <= 0)
{
Timer.value = 0;
gameManager.startTime = 0;
}
}
}
You’re on the right track, I don’t like using the var keyword either. Here’s a few things I see:
Firstly, if you need a reference to the gameobject itself, I would use GameObject gameManager;
instead of var gameManager;
.
Secondly, if you need a reference to a SCRIPT on that gameobject (like your Functions class), I would keep a reference to the script instead of a reference to the gameobject (if you need both, I would still keep a reference to the script, as it’s faster to get a gameobject from the script reference than it is to get a script from the gameobject reference).
Thirdly, in your update function, you’re trying to access gameManager.startTime. Your gameManager field currently holds a GameObject. GameObjects don’t have any field called startTime. If that’s a field from your Function script, you should be accessing startTime from your Function script instead of from the gameObject (use functions.startTime
, if you have such a field).
Fourthly, it’s generally considered bad form to use GameObject.Find() except as an absolute last resort (and even then it’s considered bad form to put yourself in a position where it’s your last resort). If you have a game management script that you know you will only ever have one instance of, a better alternative would be to put a static field containing the only instance of it, e.g. public static Functions instance;
in your Functions script (there are also bad ways to do this, see HERE for a safe way to do this).