myGaze/Assets/myScripts/EyeButtonSceneLoader.cs
2025-11-03 22:28:23 +01:00

118 lines
3.2 KiB
C#
Raw Permalink Blame History

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Rigidbody))]
public class EyeButtonSceneLoader : MonoBehaviour
{
public bool IsHovered { get; private set; }
[Header("Scene Loading")]
[SerializeField] private float lookDuration = 1.0f;
[Header("Materials")]
[SerializeField] private Material OnHoverActiveMaterial;
[SerializeField] private Material OnHoverInactiveMaterial;
[Header("Visual Feedback")]
[SerializeField] private GameObject selectionRing;
private MeshRenderer meshRenderer;
private Coroutine loadSceneCoroutine;
private bool isLoading = false;
private string sceneToLoad;
void Start()
{
meshRenderer = GetComponent<MeshRenderer>();
// Use the GameObject's name as the scene name
sceneToLoad = gameObject.name;
Debug.Log($"EyeButtonSceneLoader initialized on: {gameObject.name} - Will load scene: {sceneToLoad}");
if (selectionRing != null)
selectionRing.SetActive(false);
}
public void OnStartLooking()
{
if (isLoading) return;
Debug.Log("Started looking at button: " + gameObject.name);
IsHovered = true;
if (meshRenderer != null && OnHoverActiveMaterial != null)
meshRenderer.material = OnHoverActiveMaterial;
if (selectionRing != null)
selectionRing.SetActive(true);
if (loadSceneCoroutine == null)
loadSceneCoroutine = StartCoroutine(LoadSceneAfterDelay());
}
public void OnStopLooking()
{
if (isLoading) return;
Debug.Log("Stopped looking at button: " + gameObject.name);
IsHovered = false;
if (meshRenderer != null && OnHoverInactiveMaterial != null)
meshRenderer.material = OnHoverInactiveMaterial;
if (selectionRing != null)
selectionRing.SetActive(false);
if (loadSceneCoroutine != null)
{
StopCoroutine(loadSceneCoroutine);
loadSceneCoroutine = null;
}
}
private IEnumerator LoadSceneAfterDelay()
{
float timer = 0f;
while (timer < lookDuration)
{
if (!IsHovered)
{
Debug.Log("Gaze lost <20> cancelling scene load");
loadSceneCoroutine = null;
yield break;
}
timer += Time.deltaTime;
// Visual feedback of progress
float progress = timer / lookDuration;
if (selectionRing != null)
{
selectionRing.transform.localScale = Vector3.one * (1f + progress * 0.2f);
}
yield return null;
}
Debug.Log("Loading scene: " + sceneToLoad);
isLoading = true;
// Load the scene
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneToLoad);
if (asyncLoad == null)
{
Debug.LogError($"Scene '{sceneToLoad}' not found! Make sure it's added to Build Settings.");
isLoading = false;
}
else
{
Debug.Log("Scene loading started: " + sceneToLoad);
}
loadSceneCoroutine = null;
}
}