Home > Net >  unity dictionary value return null
unity dictionary value return null

Time:09-10

i have Dictionary "DebugCommands" in DebugCommandBase

    public class DebugCommandBase
{
    private string _id;
    private string _description;
    private string _format;

    public static Dictionary<string, DebugCommandBase> DebugCommands;

    public DebugCommandBase(string id, string description, string format)
    {
        if (DebugCommands == null)
            DebugCommands = new Dictionary<string, DebugCommandBase>();
        string mainKeyword = format.Split(' ')[0];
        DebugCommands[mainKeyword] = this;
    }

    public string Id => _id;
    public string Description => _description;
    public string Format => _format;
}

new DebugCommand("test_command", "test", "test_command", () =>
        {
            //any command
        });

In general, everything works well, but when I try to get a value from a dictionary, I get null

foreach (DebugCommandBase command in DebugCommandBase.DebugCommands.Values)
        {
            print(command.Description);
            //return null
        }

OR

print(DebugCommandBase.DebugCommands["test_command"].Format); //return null

what is the correct way to get the value from such a dictionary?

CodePudding user response:

Did you in fact check the command has a populated Description?

Normally, your approach of accessing the values in a dictionary is correct. A similar opportunity to access the values of a dictionary entry is possible by a slight change of code. You'd access each dictionary entry as a keyvaluepair.

foreach (KeyValuePair<string, DebugCommandBase> dEntry in DebugCommamdBase.DebugCommands)
{
    print(dEntry.Value.Description);
}
  • Related