Moving an object a specific amount of units.

When I click on a game object, I’d like it to move a specific amount of units on my X axis. For Example, I have a cylinder, that when clicked on moves exactly 20 units on my X axis.

I don’t want it to move to another object, just 20 units in a certain direction. If anyone could help me with this problem I’d be forever grateful.

1 Answer

1

When you detect the click just change the x position:

transform.position.x += 20;

This will change the position on the x axis 20 units, just make sure ‘transform’ is the transform of the object you want to move.

Thanks for your answer. When I put that in I get this error: Assets/Scripts/Navigation.cs(35,35): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable I'm 100% clueless on what this means. I'd reckon when I get this to work, the object would instantly blink to that position. I'd like to slide it 20 units with a certain amount of speed. Any ideas? Thanks.

well I dont use C I'm more of a javascript guy :D I've never seen that error before. For the sliding effect you could use a lerp, check this page for reference: http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Lerp.html

In C#, you have to do it this way: Vector3 v3 = transform.position; v3.x += 20.0f; transform.position = v3; Or you can do it this way: transform.position += Vector3.right * 20.0f; Or: transform.Translate(20.0f,0.0f, 0.0f, Space.World);