- Home /
GetComponent C#
I want to take the mass value from the object that the script is attached to, (the rigidbody), and then divide it by 5 and use it to change the range:
public static float range = 1000;
This is in C# and I don't really know what to do.
So what is your question exactly? You seem to know that you can use 'rigidbody.mass' to get the mass of the game object, and it's trivial to divide by 5. What is it specifically that you're trying to do?
That is exactly what I'm trying to do, but I get errors when I try: public static float range : rigidbody.mass/5;
I don't think you can do calculations like that when simply defining a variable outside of any functions, you'll most likely have to set that value in the Start function or just hardcode the calculated value.
Answer by aldonaletto · Nov 03, 2013 at 01:31 PM
@Josh707 is right: properties of Unity objects can't be used to initialize member variables (variables declared outside any function) - I suppose that these properties aren't initialized yet by that time. You must simply declare the variable, and assign to it in Start or Awake:
public static float range;
void Start(){
range = rigidbody.mass / 5;
}
By the way, be aware that static variables are unique: if you have more than one object with this script, range will keep the value assigned by the last Start executed.
I apologies for the late reply. I tried this an it worked great. Thanks!