導入
復帰地点の位置と回転を保持し、RetryでPlayerを戻してRigidbodyの速度を0にします。CharacterControllerは移動中だけ無効にします。
準備と配置
常に有効なGameObjectへRetryManagerを付け、playerと初期spawnPointを登録します。チェックポイント到達時にSetCheckpointへ地点Transformを渡し、RetryをButtonへつなぎます。
Unity 6向けの例です。[SerializeField]を付けた参照や設定値をInspectorで登録します。
処理の流れ
- 到達: 復帰地点を更新
- 失敗: Retry
- 位置 / 回転 / 速度を戻す
完成版
以下は記事内の最小例です。機能の範囲は後述の「この例の範囲」で確認してください。
RetryManager.cs
using UnityEngine;
public class RetryManager : MonoBehaviour
{
[SerializeField]
Transform player, spawnPoint;
Vector3 savedPosition;
Quaternion savedRotation;
void Start()
{
SetCheckpoint(spawnPoint != null ? spawnPoint : player);
}
public void SetCheckpoint(Transform point)
{
if (point == null)
return;
savedPosition = point.position;
savedRotation = point.rotation;
}
public void Retry()
{
CharacterController controller = player.GetComponent<CharacterController>();
bool wasEnabled = controller != null && controller.enabled;
if (wasEnabled)
controller.enabled = false;
player.SetPositionAndRotation(savedPosition, savedRotation);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null)
{
body.linearVelocity = Vector3.zero;
body.angularVelocity = Vector3.zero;
}
if (wasEnabled)
controller.enabled = true;
}
}
Inspectorと呼び出しの接続
登録する参照・設定値: player、spawnPoint。
検証用Buttonを作る場合は、On Click()の+からスクリプトを付けたGameObjectを登録し、Retry()を選びます。引数がある関数は、各Buttonに渡す値も設定します。コード側でonClickへ登録する例では、Inspectorへ同じ処理を重ねて登録しません。
動作確認
初期地点でRetryし、その後別地点をSetCheckpointしてRetryすると最新地点へ戻ることを確認します。
この例の範囲
HP、敵、所持品の復元は含みません。ゲーム全体の巻き戻しと位置だけの復帰を区別します。
まとめ
復帰地点の位置と回転を保持し、RetryでPlayerを戻してRigidbodyの速度を0にします。CharacterControllerは移動中だけ無効にします。
この記事のまとめ
失敗から次の挑戦までを短くし、初心者向けゲームでも納得感のある難しさを作るためのチェックポイント設計ガイドです。
