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

Making some constants global?

Discussion in 'Physics' started by Nanako, Jun 28, 2015.

  1. Nanako

    Nanako

    Joined:
    Sep 24, 2014
    Posts:
    1,047
    So i have a few constants that i'm using across several different classes. Their values are just small ints, 1/2/3 etc, but i like having them centralised so i can change them later.

    Right now i have them all in one of my classes, and every other class where i use them calls thatclass.myconstant

    That's starting to feel cumbersome though. I'm using them more than i originally intended across many different parts of my code, and i feel like having them bound to any specific class isn't appropriate.

    Is there any way to have constants made global somehow, to orphan them off from a class? so that from any class i can just use myconstant to get its value?
     
  2. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    any constant/enum declared outside of a class is global. Of course, avoid some of the example names I use (stay away from anything thats system name in nature)

    I have a dedicated c# file for these sorts of things usually... ie.

    DataType.cs

    Code (csharp):
    1.  
    2.  
    3. public class Functions
    4. {
    5.   public const string Execute = "Execute";
    6.   public const string Destroy = "Destroy";
    7. }
    8.  
    9. public class Layers
    10. {
    11.   public const string Default = "Default";
    12. }
    13.  
    14.  
    then from anyclass I can access them

    Code (csharp):
    1.  
    2. //pretend this is a normal class in some other file
    3.  
    4. void Start()
    5. {
    6.    Invoke(Functions.Destroy, 2);
    7. }
    8.  
    9.  
     
  3. dylanjosh

    dylanjosh

    Joined:
    Jun 1, 2015
    Posts:
    10
    I put them all into a class called "Constants"