I'm having issues only in the build for the game I'm working on. I have a simple script that moves a ball back and forth in a straight line. Pretty simple. However, whenever I run into a ball, die, and get sent back to a spawn point, the movement of the ball gets thrown off. I'm not sure whether it is the position or one of the variables in the script, but this only seems to happen in the builds. Below is the code for the movement. Any thoughts?
var movement = 3.0;
var distance = 30;
var counter = 0;
function Update () {
if(counter < distance && counter >= 0){
transform.Translate(movement * Time.deltaTime, 0, 0);
counter++;
} else if(counter == distance){
counter = distance * -1;
}else{
transform.Translate(-1 * movement * Time.deltaTime, 0, 0);
counter++;
}
}
I don't really understand what your script is trying to do, and the description of what's going wrong "gets thrown off" isn't terribly helpful. But if I had to guess, I would ask if your ball had a rigid body on it that was being affected by physics.
For your movement script I would suggest getting rid of the "counter" variable and just checking distance from your start point or something to determine when to switch directions.
I'm going to be honest with you, this is an extremely messy script and I can't really make head or tails of it. I think you might not be resetting your counter variable, but I'm not sure.
This sort of thing is much better suited for Unity's Animation Component, which lets you do things like this with relative ease.
The other thing you could use is a looping coroutine, with way-cleaner code:
`// C#
public float movement = 3;
public float distance = 30;
void Start()
{
StartCoroutine(MoveBall());
}
IEnumerator MoveBall()
{
while (true)
{
for (int i = 0; i < distance; i++)
{
transform.Translate(movement * Time.deltaTime, 0, 0);
yield return WaitForEndOfFrame();
}
yield return WaitForEndOfFrame();
for (int i = 0; i < distance; i++)
{
transform.Translate(-1 * movement * Time.deltaTime, 0, 0);
yield return WaitForEndOfFrame();
}
}
}
`
By using a Coroutine, you eliminate the need for a counter entirely, as well as the if/else logic for moving it in a negative direction.