Peyton - 8 months ago 110

C# Question

My value stays the same rather than being pingponged

`IEnumerator CrossHairScale(){`

float size = 0;

float finalsize = Mathf.Lerp (minSize, maxSize, Mathf.PingPong(size, 1));

while (transform != null) {

transform.localScale = new Vector3 (finalsize, finalsize, finalsize);

yield return null;

}

}

Answer

You have misunderstood the usage of `Mathf.PingPong(float t, float length)`

. It accepts two arguments: `t`

is the value to be limited, `length`

is the maximum value that can be returned. When `t`

is outside the range of [0, `length`

], that's when the ping-pong effect occurs.

**Here's what's going on**

In your code, the only `t`

value you ever pass into `Mathf.PingPong()`

is an unchanging value of 0, given by

```
float size = 0;
```

That means, the next line of code is basically

```
float finalsize = Mathf.Lerp (minSize, maxSize, Mathf.PingPong(0, 1));
```

And `Mathf.PingPong(0, 1) = 0`

, so all your code is really doing is

```
float finalsize = Mathf.Lerp (minSize, maxSize, 0);
```

Ultimately, you're always going to get back

```
float finalsize = minSize;
```

**So, how do you fix this?**

What you need to be doing is incrementing the `t`

value (in this case, `size`

) you pass into `Mathf.PingPong()`

- otherwise, it's always going to evaluate to the same value each time, and the value you assign to `localScale`

won't change. Consider trying this code instead:

```
IEnumerator CrossHairScale(){
float size = 0;
while (transform != null) {
// Here, we change size according to the time since the last frame
size += Time.deltaTime;
// Now, Mathf.PingPong() will return a value bouncing between 0 and 1
float finalsize = Mathf.Lerp (minSize, maxSize, Mathf.PingPong(size, 1));
transform.localScale = new Vector3 (finalsize, finalsize, finalsize);
yield return null;
}
}
```

Hope this helps! Let me know if you have any questions.

Source (Stackoverflow)