108 lines
2.6 KiB
C#
108 lines
2.6 KiB
C#
using UnityEngine;
|
|
using TMPro;
|
|
using UnityEngine.Events;
|
|
|
|
public class DestinationObject : MonoBehaviour
|
|
{
|
|
public Transform player;
|
|
public Transform nextDestinationPoint; // Single next destination point
|
|
public AudioClip destinationSound;
|
|
public float distanceThreshold = 1f;
|
|
public TextMeshPro textMeshPro;
|
|
|
|
// Use UnityEvent directly
|
|
[System.Serializable]
|
|
public class DestinationEvent : UnityEvent { }
|
|
|
|
public DestinationEvent onDestinationStart;
|
|
public DestinationEvent onDestinationEnd;
|
|
|
|
private AudioSource audioSource;
|
|
private bool destinationReached = false;
|
|
|
|
void Start()
|
|
{
|
|
InitializeAudioSource();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
float distance = Vector3.Distance(player.position, transform.position);
|
|
UpdateTextContent(distance);
|
|
|
|
if (distance < distanceThreshold && !destinationReached)
|
|
{
|
|
HandleDestinationReached();
|
|
}
|
|
|
|
transform.LookAt(transform.position + Camera.main.transform.rotation * Vector3.forward,
|
|
Camera.main.transform.rotation * Vector3.up);
|
|
}
|
|
|
|
private void InitializeAudioSource()
|
|
{
|
|
audioSource = gameObject.AddComponent<AudioSource>();
|
|
audioSource.clip = destinationSound;
|
|
}
|
|
|
|
private void UpdateTextContent(float distance)
|
|
{
|
|
if (textMeshPro != null)
|
|
{
|
|
float numericDistance = Mathf.Abs(distance);
|
|
string distanceText = numericDistance.ToString("F2");
|
|
textMeshPro.text = distanceText;
|
|
}
|
|
}
|
|
|
|
private void HandleDestinationReached()
|
|
{
|
|
destinationReached = true;
|
|
onDestinationStart.Invoke();
|
|
|
|
Debug.Log("Destination Reached!");
|
|
|
|
if (audioSource != null && destinationSound != null)
|
|
{
|
|
audioSource.PlayOneShot(destinationSound);
|
|
}
|
|
|
|
if (textMeshPro != null)
|
|
{
|
|
textMeshPro.enabled = false;
|
|
}
|
|
|
|
onDestinationEnd.Invoke();
|
|
|
|
SetNextDestination();
|
|
}
|
|
|
|
private void SetNextDestination()
|
|
{
|
|
if (nextDestinationPoint != null)
|
|
{
|
|
transform.position = nextDestinationPoint.position;
|
|
destinationReached = false;
|
|
textMeshPro.enabled = true;
|
|
}
|
|
else
|
|
{
|
|
// If there is no next destination, destroy the object
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
private void OnTriggerEnter(Collider other)
|
|
{
|
|
if (other.CompareTag("Player"))
|
|
{
|
|
onDestinationStart.Invoke();
|
|
}
|
|
}
|
|
|
|
public void OnPlayerReached()
|
|
{
|
|
// Add logic to execute when the player reaches the destination
|
|
}
|
|
}
|