How do I make it possible for two different files to use the same dictionary

I’m trying to establish a basic control scheme for my game, for this I try to use a dictionary which relates strings to keycodes. But I don’t know how to use the dictionary which I already have defined in one script in others.

I tried to load to use namespaces, but those only exist in higher versions of c# and using ‘using static filename’ didn’t work. What could I do instead?

You can make the Dictionary field public, then make a public reference to that class containing it in other files, and drag the GameObject in.

Another way would be with ScriptableObjects, which might be better suited as they are on-disk assets rather than in any given scene, which a GameObject would be.

Referencing GameObjects, Scripts, variables, fields, methods (anything non-static) in other script instances or GameObjects:

It isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.

1 Like

How would I do that?

Start with some basic tutorials for Unity, like this guy:

Imphenzia: How Did I Learn To Make Games:

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

If you’re asking “how to use an instance from another script,” you should first learn the basics of C# since object management is a core concept in the language. However, if you’re looking for the easiest solution, using a static class or member can simplify access across scripts:

public static class InputController
{
    public static Dictionary<string, KeyCode> KeyBindings = new Dictionary<string, KeyCode>
    {
        { "Jump", KeyCode.Space },
        { "Shoot", KeyCode.LeftControl },
        { "Sprint", KeyCode.LeftShift }
    };
}

But there is far better ways to approach this, specifically creating an instance of your Input Controller where it’s needed.

  1. Singletons are another option (I also don’t reccomend)
  2. Using Dependency Injection (what I would suggest using) Zenject