UniTaskが入っていること前提になります。
[Header("片道の長さ")]
[Selializefield]private float _length = 3f;
[Header("速さ")]
[Selializefield]private float _speed = 2f;
private async UniTask PingPongMove()
{
float time = 0;
Vector3 firstDistance = transform.position;
while(true)
{
time += _speed * Time.deltaTime;
var offset = Mathf.PingPong(time, _length);
var currentDistance = firstDistance.x + offset;
transform.position = new(currentDistance, firstDistance.y, firstDistance.z);
await UniTask.Yield(PlayerLoopTiming.Update, this.GetCancellationTokenOnDestroy());
}
}
何かを往復させたい時に使えるコード。
_speedには動く速さ、_lengthには往復時の片道の長さを入れます。
後はPingPongMove.Forget();を好きなところで呼び出しましょう。