using UnityEngine;
public class SoundAndMessageOnInterssaction : MonoBehaviour
{
public float interactionDistance = 1.0f;
public AudioClip soundToPlay;
public string interactionMessage = "Press E to Open";
private AudioSource audioSource;
private bool canInteract = false;
public GameObject objectToDisable;
private Transform player;
private bool hasPlayedInitialSound = false; // Flag to track if the initial sound has been played
private void Start()
{
audioSource = GetComponent<AudioSource>();
player = Camera.main.transform; // Assuming the player has a "Player" tag
}
private void Update()
{
if (player != null)
{
float distanceToPlayer = Vector3.Distance(player.position, transform.position);
// Check if the player is close enough to interact with the object
if (distanceToPlayer <= interactionDistance)
{
canInteract = true;
if (canInteract && Input.GetKeyDown(KeyCode.E))
{
if (!hasPlayedInitialSound)
{
// Play the initial sound only if it hasn't been played before
audioSource.PlayOneShot(soundToPlay);
hasPlayedInitialSound = true;
objectToDisable.SetActive(false);
}
}
}
else
{
canInteract = false;
}
}
}
private void OnGUI()
{
if (canInteract)
{
GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2, 200, 40), interactionMessage);
}
}
}
ليست هناك تعليقات:
إرسال تعليق
عادة يتم الرد خلال ساعات