Getting a variable from my game controller

I’ve done a bit of browsing in the documentation, and I found that using GameObject.FindWithTag is far more efficient than most other methods of locating an object. I have a game object within my game called “GameController”, I tagged it as “GameController”, and the script within it is called “GameController”. The purpose of the game controller script is to keep certain constants organized, and so that if I need to change them, they are all in one place.

Here is the part of my code that I am having trouble with.
(I am basically trying to access the public gravity variable from within the gamecontroller script)

    private float gravity;
   
    void Start () {
        gravity = GameObject.FindWithTag ("GameController").GetComponent<GameController> ().gravity;
    }

For whatever reason, I am getting an error that says “GameController does not contain a definition for ‘gravity’, and no extention method for ‘gravity’ of type ‘GameController’ could be found”.

Also, am I approaching this from the wrong angle? Is there a better way to hold global constants such as gravity?

If all you’re doing is creating constants in this class, there’s no real reason to make it a component at all. Just create a new source file with something like this:

public class GameConstants
{
     public const float gravity = 9.1f;
}

Then access it:

void Start() {
   gravity = GameConstants.gravity;
}
1 Like

Thanks for the help! Works like a charm, I am still new C# and Unity. I’m glad to see the people on these forums are so patient and friendly :slight_smile: