0

TryGet<T> method for variables

Zefugi 2 years ago updated 2 years ago 1

Would be nice to have a TryGet<T> for all variable types.

bool Variables.Object(GameObject object).TryGet<T>(string variable, out T object)

This should return false if the variable doesn't exist or is of invalid type, true if it exists and is of valid type. out T object should of cause be the variable value, or if the variable doesn't exist or is of invalid type it should return default(T);

Here is my own implementation - would be nice if it was part of Bolt though.

using Bolt;

public static class BoltExtension
{
    public static bool TryGet<T>(this VariableDeclarations varDeclerations, string variable, out T value)
    {
        if(varDeclerations.IsDefined(variable))
        {
            object tmp = varDeclerations.Get(variable);
            if (tmp is T)
            {
                value = (T)tmp;
                return true;
            }
        }
        value = default(T);
        return false;
    }
}


Bolt Version:
Unity Version:
Platform(s):
Scripting Backend:
.NET Version (API Compatibility Level):

It makes the following possible:

bool canDoStuff;

if (Variables.Object(gameObject).TryGet<bool>("MyThingVarName", out canDoStuff) && canDoStuff)
{
    // Do the stuff that it does.
}