wirm/Game/Assets/Scripts/StoryTyping.cs

88 lines
2.4 KiB
C#
Raw Permalink Normal View History

2025-02-14 13:20:02 +08:00
/*
2025-02-15 00:36:25 +08:00
* Author: Reza and Wai Lam
* Date: 14/2/25
* Description: For texts to appear themselves for storytelling
*/
2025-02-14 13:20:02 +08:00
using System.Collections;
using TMPro;
2025-02-15 00:36:25 +08:00
using UnityEngine;
2025-02-14 13:20:02 +08:00
using UnityEngine.SceneManagement;
public class StoryTyping : MonoBehaviour
{
[Header("Message Settings")]
// Custom message for this trigger
2025-02-15 00:36:25 +08:00
[TextArea(3, 5)]
public string[] storyLines;
2025-02-14 13:20:02 +08:00
public TMP_Text storyText;
// Speed at which text appears
2025-02-15 00:36:25 +08:00
public float typingSpeed = 0.05f;
2025-02-14 13:20:02 +08:00
2025-02-15 00:36:25 +08:00
public string nextSceneName = "NextScene";
2025-02-14 13:20:02 +08:00
public CanvasGroup fadeCanvasGroup; // Assign in Inspector
2025-02-15 00:36:25 +08:00
public float fadeDuration = 1f; // Duration for fade in/out
public float displayDuration = 5f;
private int _currentLine;
2025-02-14 13:20:02 +08:00
private void Start()
{
// Start typing the first line if there are any lines
2025-02-15 00:36:25 +08:00
if (storyLines.Length > 0) StartCoroutine(TypeText());
2025-02-14 13:20:02 +08:00
}
2025-02-15 00:36:25 +08:00
private IEnumerator TypeText()
2025-02-14 13:20:02 +08:00
{
// Loop through each line of text
2025-02-15 00:36:25 +08:00
while (_currentLine < storyLines.Length)
2025-02-14 13:20:02 +08:00
{
2025-02-15 00:36:25 +08:00
var fullText = storyLines[_currentLine];
var currentText = "";
2025-02-14 13:20:02 +08:00
// Type out the current line character by character
2025-02-15 00:36:25 +08:00
foreach (var t in fullText)
2025-02-14 13:20:02 +08:00
{
2025-02-15 00:36:25 +08:00
currentText += t;
2025-02-14 13:20:02 +08:00
storyText.text = currentText;
yield return new WaitForSeconds(typingSpeed);
}
2025-02-15 00:36:25 +08:00
_currentLine++; // Move to the next line
yield return new WaitForSeconds(displayDuration); // Wait briefly before displaying the next line
2025-02-14 13:20:02 +08:00
}
// After all lines are typed, trigger fade and load the next scene
StartCoroutine(FadeToBlack());
}
2025-02-15 00:36:25 +08:00
private IEnumerator FadeToBlack()
2025-02-14 13:20:02 +08:00
{
// Fade to black
yield return StartCoroutine(Fade(0f, 1f, fadeDuration));
// Load the next scene after fade
SceneManager.LoadScene(nextSceneName);
}
2025-02-15 00:36:25 +08:00
private IEnumerator Fade(float startAlpha, float endAlpha, float duration)
2025-02-14 13:20:02 +08:00
{
2025-02-15 00:36:25 +08:00
var elapsed = 0f;
2025-02-14 13:20:02 +08:00
fadeCanvasGroup.alpha = startAlpha;
// Fade over the specified duration
while (elapsed < duration)
{
elapsed += Time.deltaTime;
2025-02-15 00:36:25 +08:00
var t = elapsed / duration;
2025-02-14 13:20:02 +08:00
fadeCanvasGroup.alpha = Mathf.Lerp(startAlpha, endAlpha, t);
yield return null;
}
fadeCanvasGroup.alpha = endAlpha;
}
}