Is a static appropriate here?

I have a system where character names are chosen at random from an array of strings. To avoid dependencies I put the array of names in the character class itself. However, we don’t want every character to be running around with the whole name database stored in it, so I made the names array a protected static. At no point can this data ever be edited. I know the rule of thumb for statics is to avoid them, but would this be a case where it is appropriate? Is there another method I could use?

EDIT: I suppose one method would just be to make a function that the database is in, that way it would only be loaded into memory when it is actually needed and each character wouldn’t have its own copy of it.

Or make a separate static object that contains a static name getter function.

After that, you don’t care where those names come from. In the future you could change that function to access a database, pull it off the web, read it from the online New York Times horoscopes, etc. and the rest of your code doesn’t change because it uses that one static name getter function.

If you really wanna be spiffy, make it asynchronous so that you call this static function and supply a System.Action function pointer that it will call when it finally decides the random name, which could take time if it is over the net, for example.

Ultimately, the “best” way would probably be to have the list of names in a file in Resources, and have a static function access that file. Failing that, a protected static array is good too.

sure, static would be fine there, why not.

If I were you though, I’d make the static member private and just use a protected member to get a random name. This ensures that the static array can’t be edited:

public abstract class Character : MonoBehaviour {

    static string[] names = new string[] { "Jerry", "Steve", "Ashley", "Chris" }
   
    static protected GetRandomName()
    {
        int key =  Random.Range(0, names.Length);
       
        return names[key];
    }

}

public class Rouge : Character {
   
    void Awake()
    {
        name = GetRandomName();
    }

}
1 Like