Hello!
My first script in Unity. I have a block that I can move, alright. Now I thought I’d fetch the speed of the rigidbody I have on that object, and if the speed is lower than 3, make it 10. Then it would obviously speed up quickly and then speed down again.
The moving part works. Everything works fine, but when I do this:
#pragma strict
var moveSpeed : float = 3; //speed of the player
var maxSpeed : float = 3;
var currentSpeed = rigidbody.velocity.magnitude;
//called at start
function Start () {
}
//called every frame
function Update () {
//Fetch the input from the player, and convert
//it into realtime movement
if(currentSpeed < maxSpeed){
moveSpeed = 10;
}
//translates the input into movement
var translationZ : float = Input.GetAxis ("Horizontal") * moveSpeed;
var translationX : float = Input.GetAxis ("Vertical") * moveSpeed;
//We don't want to let the player speed be dependent
//on the frames per second, so let's fix the speed to
//Time.deltaTime. By multiplying it, we basically
//make it frame-independent. (At least, that's the plan).
translationZ *= Time.deltaTime;
translationX *= Time.deltaTime;
//move desired creature along Z+X axis
transform.Translate (translationX, 0, translationZ);
}
This is the code. But as soon as I type the
if(currentSpeed < maxSpeed){
moveSpeed = 10;
}
line, it gives me this:
UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
get_rigidbody can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
PlayerMovement…ctor () (at Assets/Scripts/PlayerMovement.js:5)
Any help would be extremely appreciated. Thank you.
perfect summary +1
– Bunny83That's a great answer. Thank you.
– SherlockHolmes