Hi everyone! I recently started using unity after some headaches with android development using LibGDX.
I am still completely new to Unity and it may just be user error, but I have searched everywhere and couldn’t find a proper solution to this. I am also primarily a Java programmer, so this may just have something to do with the way C# works.
Basically I am trying to add basic character movement, but I am unable to change the speed of my character by using a variable. Here is an example of what I’m doing and what my issue is:
public float speed = 50;
void Update()
{
if (Input.GetKey(KeyCode.D))
{
Vector3 myVector = new Vector3(speed, 0, 0);
gameObject.transform.position += myVector;
}
}
The above code sends my character moving across the screen at the speed of light. But when I change the value of speed to something lower, the speed of my character isn’t changed.
But if I insert a number instead of a variable into the x parameter of myVector, it works.
It’s as if if it ignores the value of the variable speed and decides to use it’s own default value unless I specify my own value without using a variable.
void Update()
{
if (Input.GetKey(KeyCode.D))
{
Vector3 myVector = new Vector3(.1f, 0, 0);
gameObject.transform.position += myVector;
}
}
The above code works. I set a value and the character’s movement speed is different based on the value entered
So basically:
// Does not work
float speed = .1f;
Vector3 myVector = new Vector3(speed, 0, 0);
gameObject.transform.position += myVector;
// Does Work
Vector3 myVector = new Vector3(.1f, 0, 0);
gameObject.transform.position += myVector;
Using transform.Translate() has similar effects.
If I use my speed variable, it doesn’t move my character at incredible speed, but at a good fast speed. But changing the value of speed has no effect, I have to use a number instead of a variable to change the speed.
What am I doing wrong?