c# Movement

Hi everyone.
I want to make a vehicle move toward a certain point and backward and I want the vehicle to move forward and backward until I exit play mode. here is the code I tried and it don’t work, any ideas ?

Are you getting any errors or is it just not moving? Did you attach the C# script to the object that is moving inside of the unity editor?

it’s not moving and yes.

Update method is called every frame and on first frame, it is going to run transform.position = Vector3.MoveTowards(transform.position, endPosition, movementSpeed * Time.deltaTime); and moves your car a tiny bit then it is going to run next statement and set ok = false. Since ok = false, it is also going to run the below statements transform.position = Vector3.MoveTowards(transform.position, startPosition, movementSpeed * Time.deltaTime); and your car will be back to start position again. That’s why your car is not moving. What you can do is, change your script to something like

void Update()
{
	if(ok == true)
	{
		if(transform.position != endPosition)
		{
			transform.position = Vector3.MoveTowards(transform.position, endPosition, movementSpeed * Time.deltaTime);
			if(transform.position == endPosition)
				ok = false;
		}
	}
	else if(ok == false)
	{
		if(transform.position != startPosition)
		{
			transform.position = Vector3.MoveTowards(transform.position, startPosition, movementSpeed * Time.deltaTime);
			if(transform.position == startPosition)
				ok = true;
		}
	}
}