- Home /
The question is answered, right answer was accepted
Why won't ExpressionEvaluator work with variables?
In my game, I wanted a string of equation objects (e.g. 1, +, 5, etc.) to be calculated into an answer. For example, the string "4 + 5" should produce the result 9. The numbers and operations change throughout the game. I found this function named ExpressionEvaluator, and thought it would work by placing the string variable like this:
public int output;
private string calcsString;
void Update()
{
output = ExpressionEvaluator.Evaluate<int>(calcsString);
}
However, Unity kept on returning me this error:
error CS0305: Using the generic type 'List<T>' requires 1 type arguments
What am I doing wrong here?
Answer by Bunny83 · Jan 18, 2021 at 09:54 AM
Well, there's a lot wrong here. First of all the error you showed is completely unrelated to the code you showed.
Second the class ExpressionEvaluator is an editor class and therefore can not be used by your game, only by editor scripts.
In your title you mention variables but in your description it looks like you have expressions with just literal values.
If you need an expression evaluator solution that works at runtime you can use my LogicExpressionParser which is an improved version of by old ExpressionParser. It's a very simply straight forward implementation. Though they support variables and custom functions. The created expression tree can be re-evaluated later when the variables have changed. Variables can be introduced as closures of actual C# variables.
Note that those parsers only work on double values. However you can always cast the result to an integer if required.
Are there any examples for LogicExpressionParser? I have found some for ExpressionParser in the unify link you've sent me but nothing for LogicExpressionParser.
Hmm I homehow got distracted ^^ I had already searched for an older answer where I gave some examples. I've found this one.
It has been mentioned in a couple of places, though I think I should mention it once more. Be careful with unary $$anonymous$$us signs. Expressions like "5 + -3"
won't work as unary $$anonymous$$us does not work this way. Unary $$anonymous$$us values have to be enclosed in brackets:
"5 + (-3)"
Everything else should work as expected. Note that ^
is the power operator in a numerical expression but also xor in a logical expression.
Follow this Question
Related Questions
Writing maths expressions 1 Answer
Optimising projectile continuously calculated impact point 2 Answers
Need help with easing effects which respect Time.deltaTime, MATH 0 Answers
Any Ideas on how to solve this? 1 Answer
Explosion damage script only deals damage in the first explosion and none afterwards 0 Answers