I’ve just switched to C#, and that’s what the documentation says, but I don’t fully understand it. Text is below. So does that mean I’m not supposed to do this:
public class RotateAroundSelf : MonoBehaviour {
Vector3 speed = new Vector3(0,0,0); //this is evil
void Start () {
speed = new Vecto3(0,0,0); // this is good
}
}
Documentation:
"Never initialize any values in the constructor or variable initializers in a MonoBehaviour script. Instead use Awake or Start for this purpose. Unity automatically invokes the constructor even when in edit mode. This usually happens directly after compilation of a script because the constructor needs to be invoked in order to retrieve default variable values. Not only will the constructor be called at unforeseen times, it might also be called for prefabs or inactive game objects.
Using the constructor when the class inherits from MonoBehaviour, will make the constructor to be called at unwanted times and in many cases might cause Unity to crash. Only use constructors if you are inheriting from ScriptableObject. "
@BBoulder 's answer while correct if the RotateAroundSelf is derived from Monobehaviour, did not address your question. First this restriction of having to initialize in Start() only applies to classes that are derived from MonoBehaviour. The code you have is just fine, since the code is not in a constructor. What you cannot do is is this:
public class RotateAroundSelf : MonoBehaviour {
public RotateAroundSelf(float foo) // Class class constructor
{
Vector3 speed = new Vector3(0,foo,0); //now it's evil
}
}
If you create your own classes that are not derived from Monobehaviour, then a constructor works just fine.
Nope, you got it. it’s telling you not to do this:
RotateAroundSelf myRotateAroundSelf = new RotateAroundSelf();
That’ll give you an error. You gotta attach the script with AddComponent. Then Unity will call the Start function for you automatically, and you do all your setup there.
Okay, not sure if I got 2. right, would be nice if we could initialize variables on creation, would shorten the code:
-
“Never initialize any values in the constructor”
like this:
public class RotateAroundSelf : MonoBehaviour { public RotateAroundSelf(float foo) // Class class constructor {5. Vector3 speed = new Vector3(0,foo,0); //now it’s evil }}
2,. “Never initialize any value initializers in a MonoBehaviour script”
public class RotateAroundSelf : MonoBehaviour {
Vector3 speed = new Vector3(0,0,0); //this is evil
}
Side note: we’re only talking about children of MonoBehaviour, which makes sense, if we had a completely independent class it wouldn’t be affected by unitys quirks.