Unity Movement Issue

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?

is the issue when you change the speed value in your script? Mid so it will be because you made the variable public. When you do that it ‘sets’ it in the inspector & the inspector value over rides what you have in your script. If you want to test different speed values change it in the inspector, then when you are happy put that value in your code & take the public out unless you really need it

2 Likes

That’s it! It works!!!

I didn’t know that Unity worked that way, but it makes sense.

Thanks a bunch!

No prob, it still catches me after a year of it. Good luck