How to convert/cast sharedFloat to float?

VladD

New member
This might sound like a dumb question, but I am trying to set a variable of a class in one of my Actions that is derived from MonoBehavior. So it's data types are standard floats. When I try to set a pubilc float with a SharedFloat, I get errors about there being no implicit conversion between "SharedFloat" and "float".

I tried, based on the examples in the Documentation:

// tried grabbing it from the Behavior Tree itself...
C#:
float f_exampleFloat = (float)behaviorTree.GetVariable("MySharedFloatVariable") ;  //casting to float doesn't work
float f_exampleFloat = (float)behaviorTree.GetVariable("MySharedFloatVariable") as float;  //casting to float doesn't work


// tried mapping it to the shared float in the editor.
C#:
public SharedFloat MySharedFloatVariable; // mapped in Editor to correct global variable.
...
float f_exampleFloat = System.Convert.ToSingle(exampleFloat );//doesn't work, get invalid cast. MonoDevelop lets it build, but fails in Editor play.
float f_exampleFloat = System.Convert.ToDouble(exampleFloat );//doesn't work, get invalid cast. MonoDevelop lets it build, but fails in Editor play.

// The only way I can seem to get it to work is with the built-in "ToString()" conversion in BehaviorDesigner. Then convert the string to float.
C#:
public SharedFloat MySharedFloatVariable; // mapped in Editor to correct global variable.
...
float f_exampleFloat = (float)System.Convert.ToDouble( MySharedFloatVariable.ToString() );


This works...but I feel like it's slopping programming. Is there no direct cast? I hate to do a double-conversion any time I need to cast to float or Int, etc.
Do you folks have some thoughts on this?
Is this bad practice?
Is there a direct cast I'm missing? I'm not from a CS background, so sorry if it's obvious.
Thanks in advance for any help!!;)
 
I think you've got to get the value of the variable and then cast it to float. This should work:
Code:
float f_exampleFloat = (float)behaviorTree.GetVariable("MySharedFloatVariable").GetValue();
 
Thanks @almostchris! Another way that you can get the float value without any casts is to use the Value property:

Code:
float f_exampleFloat =behaviorTree.GetVariable("MySharedFloatVariable").Value;
 
Excellent, folks! That was exactly what I needed!

I guess I wasn't used to the pattern of using the "Value" property of a variable as a getter...since in MonoBehavior and standard C# the variable IS the value. I don't see the utility in having a variable reference saved as another variable. Some other folks just starting out with Behavior Designer might also make the same mistake...might want to put a sentence in the documentation making that clear. Could save some folks headaches.

Either way, thanks very much!
 
Top