im making a simple game were you move a ball from platform to platform by balancing on beams so how would i make it so when you reach a platform you check point and when you fall off you respawn at that check point
Something like this might work (not tested).
CheckPoint.cs
public class CheckPoint : MonoBehaviour
{
public static CheckPoint LastCheckPoint
{
get;
private set;
}
private void OnTriggerEnter(Collider other)
{
LastCheckPoint = this;
gameObject.SetActive(false);
}
}
DeathCheck.cs
public class DeathCheck : MonoBehaviour
{
public float deathBarrier = 0.0f;
private void Update()
{
if(this.transform.position.y > this.deathBarrier)
{
var lastCheckPoint = CheckPoint.LastCheckPoint;
if(lastCheckPoint != null)
{
this.transform.position = lastCheckPoint.transform.position;
}
else
{
Debug.LogError("Player is dead but have not reach a check point.");
}
}
}
}
Attach CheckPoint.cs and a trigger enabled collider to your checkpoints.
Attach DeathCheck.cs to the player.
Edit: added a simpler death check script
SimpleDeathCheck.cs
using UnityEngine;
/// <summary>
/// Component to put player at start position of player gets below the death barrier.
/// </summary>
public class SimpleDeathCheck : MonoBehaviour
{
/// <summary>
/// The minimum Y position the player is allowed to have before being moved back to start.
/// </summary>
[SerializeField]
private float deathBarrier = -10.0f;
/// <summary>
/// The position to apply to the player if player gets below the death barrier.
/// </summary>
[SerializeField]
private Vector3 startPosition = new Vector3(0.0f, 0.5f, 0.0f);
/// <summary>
/// Checks if player is below death barrier and repositions the player back to start if so.
/// </summary>
private void Update()
{
if (this.transform.position.y < this.deathBarrier)
{
this.transform.position = this.startPosition;
}
}
}