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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Getting a variable from my game controller

Discussion in 'Scripting' started by TheForsaken95, Jun 13, 2015.

  1. TheForsaken95

    TheForsaken95

    Joined:
    Aug 29, 2014
    Posts:
    30
    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)
    Code (CSharp):
    1.     private float gravity;
    2.    
    3.     void Start () {
    4.         gravity = GameObject.FindWithTag ("GameController").GetComponent<GameController> ().gravity;
    5.     }
    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?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    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:

    Code (csharp):
    1.  
    2. public class GameConstants
    3. {
    4.      public const float gravity = 9.1f;
    5. }
    6.  
    Then access it:
    Code (csharp):
    1.  
    2. void Start() {
    3.    gravity = GameConstants.gravity;
    4. }
    5.  
     
    TheForsaken95 likes this.
  3. TheForsaken95

    TheForsaken95

    Joined:
    Aug 29, 2014
    Posts:
    30
    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 :)