Search Unity

Access static classes in subfolders... how?

Discussion in 'Getting Started' started by Sparticus, Oct 15, 2020.

  1. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Hey all,

    If I add a EnemyConstants.cs file to the root of my unity folder that looks like :

    Code (CSharp):
    1. public static class EnemyConstants
    2. {
    3.     public const int hitpoints = 10;
    4. }
    I can access the variables from within that file from anywhere in any script by doing :

    Code (CSharp):
    1. int hp = EnemyConstants.hitpoints;
    However, I'd like to create other similar constant files as well. So I made a "Constants" subfolder, moved the constant file into it and I can no longer access that variable the same way. How do I get this to work?

    I tried other things like :

    Code (CSharp):
    1. in hp = Constants.EnemyConstants.hitpoints;
    Any advice you can give would be appreciated! :)
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    You don't need to reference the name of the folder that the script is in.
    You always reference static objects the same way no matter what directory the script is in.

    Perhaps what you want to do is make another static class called "Constants" that contains "EnemyConstants" inside of it:
    Code (CSharp):
    1. public static class Constants {
    2.    public static EnemyConstants EnemyConstants;
    3. }
    The "EnemyConstants" class cannot be static in this case though.
     
  3. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Thanks fore the info. I found the issue. Visual Studio code claimed it didn't see the Constants file... I tried ignoring it's error message and just ran the unity game anyways it it ran successfully.... Then magically VSCode stopped complaining...