using System;
using UnityEngine;
///
/// Handles level switching when interacted with. Applies switch data and triggers scene transitions.
///
public class LevelSwitch : MonoBehaviour
{
///
/// Data for this level switch (target scene, icon, etc).
///
public LevelSwitchData switchData;
///
/// Renderer for the switch icon.
///
public SpriteRenderer iconRenderer;
private Interactable interactable;
private bool _isActive = true;
///
/// Unity Awake callback. Sets up icon, interactable, and event handlers.
///
void Awake()
{
_isActive = true;
if (iconRenderer == null)
iconRenderer = GetComponent();
interactable = GetComponent();
if (interactable != null)
{
interactable.StartedInteraction += OnStartedInteraction;
}
ApplySwitchData();
}
///
/// Unity OnDestroy callback. Cleans up event handlers.
///
void OnDestroy()
{
if (interactable != null)
{
interactable.StartedInteraction -= OnStartedInteraction;
}
}
#if UNITY_EDITOR
///
/// Unity OnValidate callback. Ensures icon and data are up to date in editor.
///
void OnValidate()
{
if (iconRenderer == null)
iconRenderer = GetComponent();
ApplySwitchData();
}
#endif
///
/// Applies the switch data to the level switch (icon, name, etc).
///
public void ApplySwitchData()
{
if (switchData != null)
{
if (iconRenderer != null)
iconRenderer.sprite = switchData.mapSprite;
gameObject.name = switchData.targetLevelSceneName;
// Optionally update other fields, e.g. description
}
}
///
/// Handles the start of an interaction (switches the level if active).
///
private async void OnStartedInteraction()
{
Debug.Log($"LevelSwitch.OnInteracted: Switching to level {switchData?.targetLevelSceneName}");
if (switchData != null && !string.IsNullOrEmpty(switchData.targetLevelSceneName) && _isActive)
{
// Optionally: show loading UI here
var progress = new Progress(p => Debug.Log($"Loading progress: {p * 100:F0}%"));
await SceneManagerService.Instance.SwitchSceneAsync(switchData.targetLevelSceneName, progress);
_isActive = false;
// Optionally: hide loading UI here
}
}
}