SanAndreasUnity/Assets/Scripts/Behaviours/OutOfRangeDestroyer.cs

51 lines
1.2 KiB
C#
Raw Normal View History

2020-05-31 19:07:22 +02:00
using UnityEngine;
2019-06-24 02:04:34 +02:00
namespace SanAndreasUnity
2020-05-31 19:07:22 +02:00
{
2019-06-24 02:04:34 +02:00
public class OutOfRangeDestroyer : MonoBehaviour
2020-05-31 19:07:22 +02:00
{
2019-06-24 02:04:34 +02:00
public float timeUntilDestroyed = 5;
public float range = 250;
public Transform targetObject = null;
2020-05-31 19:07:22 +02:00
2019-06-24 02:04:34 +02:00
private float timeSinceOutOfRange = 0;
private void Start()
2020-05-31 19:07:22 +02:00
{
2019-06-24 02:04:34 +02:00
if (targetObject == null)
{
if (Camera.main != null)
targetObject = Camera.main.transform;
}
2020-05-31 19:07:22 +02:00
}
2019-06-24 02:04:34 +02:00
private void Update()
2020-05-31 19:07:22 +02:00
{
2019-06-24 02:04:34 +02:00
if (targetObject == null)
{
if (Camera.main != null)
targetObject = Camera.main.transform;
}
2019-06-24 02:04:34 +02:00
if (targetObject != null)
2020-05-31 19:07:22 +02:00
{
2019-06-24 02:04:34 +02:00
// only increase time if target object exists
timeSinceOutOfRange += Time.deltaTime;
float distanceSq = (transform.position - targetObject.position).sqrMagnitude;
if (distanceSq <= range * range)
{
timeSinceOutOfRange = 0;
}
2020-05-31 19:07:22 +02:00
}
2019-06-24 02:04:34 +02:00
if (timeSinceOutOfRange >= timeUntilDestroyed)
{
Destroy(gameObject);
}
2020-05-31 19:07:22 +02:00
}
}
2019-06-24 02:04:34 +02:00
}