Replacement.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Replacement : MonoBehaviour
  5. {
  6. [Tooltip("The distance from the GameObject's spawn position at which will trigger a respawn ")]
  7. public float DistanceThreshold = 20.0f;
  8. private Vector3 RespawnPoint;
  9. private Quaternion RespawnOrientation;
  10. private Rigidbody rigidBody;
  11. private void Start() {
  12. rigidBody = GetComponent<Rigidbody>();
  13. LockSpawnPoint();
  14. }
  15. private void LateUpdate() {
  16. float distanceSqr = (RespawnPoint - this.transform.position).sqrMagnitude;
  17. if(distanceSqr > DistanceThreshold * DistanceThreshold) {
  18. // Reset any velocity from falling or moving when respawning to original location
  19. if(rigidBody != null) {
  20. rigidBody.velocity = Vector3.zero;
  21. rigidBody.angularVelocity = Vector3.zero;
  22. }
  23. this.transform.SetPositionAndRotation(RespawnPoint, RespawnOrientation);
  24. }
  25. }
  26. public void LockSpawnPoint() {
  27. RespawnPoint = this.transform.position;
  28. RespawnOrientation = this.transform.rotation;
  29. }
  30. }