Files
AppleHillsProduction/Assets/Scripts/LevelS/LevelSwitch.cs

90 lines
2.7 KiB
C#
Raw Normal View History

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