GameFlowManager
unknown
csharp
a year ago
9.4 kB
9
Indexable
using System.Collections;
using UnityEngine;
using UnityEngine.Playables;
using KartGame.KartSystems;
using UnityEngine.SceneManagement;
using System;
using System.IO;
using System.Collections.Generic;
using UnityEditor.UIElements;
using System.Linq;
using TMPro;
using UnityEngine.SocialPlatforms.Impl;
using PlasticGui.Configuration;
public enum GameState{Play, Won, Lost}
public class GameFlowManager : MonoBehaviour
{
[Header("Parameters")]
[Tooltip("Duration of the fade-to-black at the end of the game")]
public float endSceneLoadDelay = 3f;
[Tooltip("The canvas group of the fade-to-black screen")]
public CanvasGroup endGameFadeCanvasGroup;
[Header("Win")]
[Tooltip("This string has to be the name of the scene you want to load when winning")]
public string winSceneName = "WinScene";
[Tooltip("Duration of delay before the fade-to-black, if winning")]
public float delayBeforeFadeToBlack = 4f;
[Tooltip("Duration of delay before the win message")]
public float delayBeforeWinMessage = 2f;
[Tooltip("Sound played on win")]
public AudioClip victorySound;
//public string name = "Player 1";
public NameDef playerName;
[Tooltip("Prefab for the win game message")]
public DisplayMessage winDisplayMessage;
public PlayableDirector raceCountdownTrigger;
[Header("Lose")]
[Tooltip("This string has to be the name of the scene you want to load when losing")]
public string loseSceneName = "LoseScene";
[Tooltip("Prefab for the lose game message")]
public DisplayMessage loseDisplayMessage;
[SerializeField]
public TextMeshProUGUI display_scores;
public GameState gameState { get; private set; }
public bool autoFindKarts = true;
public ArcadeKart playerKart;
ArcadeKart[] karts;
ObjectiveManager m_ObjectiveManager;
TimeManager m_TimeManager;
float m_TimeLoadEndGameScene;
string m_SceneToLoad;
float elapsedTimeBeforeEndScene = 0;
public bool isQuit = false;
public int playerScore;
//private string path = "../Piwo Kart/Assets/Karting/Scripts/high_score.txt";
public LeaderboardManager leaderboardManager;
int playerScoreLeaderBoard;
void Start()
{
leaderboardManager = FindObjectOfType<LeaderboardManager>();
if (autoFindKarts)
{
karts = FindObjectsOfType<ArcadeKart>();
if (karts.Length > 0)
{
if (!playerKart) playerKart = karts[0];
}
DebugUtility.HandleErrorIfNullFindObject<ArcadeKart, GameFlowManager>(playerKart, this);
}
m_ObjectiveManager = FindObjectOfType<ObjectiveManager>();
DebugUtility.HandleErrorIfNullFindObject<ObjectiveManager, GameFlowManager>(m_ObjectiveManager, this);
m_TimeManager = FindObjectOfType<TimeManager>();
DebugUtility.HandleErrorIfNullFindObject<TimeManager, GameFlowManager>(m_TimeManager, this);
AudioUtility.SetMasterVolume(1);
winDisplayMessage.gameObject.SetActive(false);
loseDisplayMessage.gameObject.SetActive(false);
m_TimeManager.StopRace();
foreach (ArcadeKart k in karts)
{
k.SetCanMove(false);
}
//run race countdown animation
ShowRaceCountdownAnimation();
StartCoroutine(ShowObjectivesRoutine());
StartCoroutine(CountdownThenStartRaceRoutine());
}
IEnumerator CountdownThenStartRaceRoutine() {
yield return new WaitForSeconds(3f);
StartRace();
}
void StartRace() {
foreach (ArcadeKart k in karts)
{
k.SetCanMove(true);
}
m_TimeManager.StartRace();
}
void ShowRaceCountdownAnimation() {
raceCountdownTrigger.Play();
}
IEnumerator ShowObjectivesRoutine() {
while (m_ObjectiveManager.Objectives.Count == 0)
yield return null;
yield return new WaitForSecondsRealtime(0.2f);
for (int i = 0; i < m_ObjectiveManager.Objectives.Count; i++)
{
if (m_ObjectiveManager.Objectives[i].displayMessage)m_ObjectiveManager.Objectives[i].displayMessage.Display();
yield return new WaitForSecondsRealtime(1f);
}
}
void Update()
{
if (gameState != GameState.Play)
{
elapsedTimeBeforeEndScene += Time.deltaTime;
if(elapsedTimeBeforeEndScene >= endSceneLoadDelay)
{
float timeRatio = 1 - (m_TimeLoadEndGameScene - Time.time) / endSceneLoadDelay;
endGameFadeCanvasGroup.alpha = timeRatio;
float volumeRatio = Mathf.Abs(timeRatio);
float volume = Mathf.Clamp(1 - volumeRatio, 0, 1);
AudioUtility.SetMasterVolume(volume);
// See if it's time to load the end scene (after the delay)
if (Time.time >= m_TimeLoadEndGameScene)
{
SceneManager.LoadScene(m_SceneToLoad);
gameState = GameState.Play;
}
}
}
else
{
if (m_ObjectiveManager.AreAllObjectivesCompleted())
EndGame(true);
if (m_TimeManager.IsFinite && m_TimeManager.IsOver)
EndGame(false);
}
}
[System.Serializable]
public class ScoreEntry
{
public string playerName;
public int score;
}
public void EndGame(bool win)
{
// unlocks the cursor before leaving the scene, to be able to click buttons
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
m_TimeManager.StopRace();
// Remember that we need to load the appropriate end scene after a delay
gameState = win ? GameState.Won : GameState.Lost;
gameObject.SetActive(true);
if (win)
{
playerScoreLeaderBoard = (int)Math.Round(m_TimeManager.TotalTime - m_TimeManager.TimeRemaining);
PlayerPrefs.SetInt("PlayerScore", playerScoreLeaderBoard);
PlayerPrefs.SetString("PlayerName", playerName.name);
/*
float current_score = m_TimeManager.TotalTime - m_TimeManager.TimeRemaining;
Dictionary<String,float> score_board = new Dictionary<string, float>();
using (System.IO.StreamReader outputFile = new System.IO.StreamReader(Path.Combine(Application.persistentDataPath, "Assets/Karting/Scripts/high_score.txt"))){
for(int i = 0; i < 5; i ++){
string line = outputFile.ReadLine();
string[] splitted_line = line.Split(' ');
score_board.Add(splitted_line[0], float.Parse(splitted_line[1]));
}
}
score_board.Add("Mateusz9856u0",current_score);
Dictionary<String,float> sorted_score_board = new Dictionary<string, float>();
for(int i = 0; i < 5; i++){
float min = float.MaxValue;
string min_name = "";
foreach(KeyValuePair<String,float> pair in score_board){
if(pair.Value < min){
min_name = pair.Key;
min = pair.Value;
}
}
sorted_score_board.Add(min_name,min);
score_board.Remove(min_name);
}
using (System.IO.StreamWriter outputFile = new System.IO.StreamWriter(Path.Combine(Application.persistentDataPath, "Assets/Karting/Scripts/high_score.txt")))
{
string display_scores_string = "";
foreach(KeyValuePair<String,float> pair in sorted_score_board){
outputFile.WriteLine(pair.Key + " " + pair.Value);
display_scores_string += pair.Key + " " + pair.Value + "\n";
}
display_scores.SetText(display_scores_string);
}
*/
m_SceneToLoad = winSceneName;
m_TimeLoadEndGameScene = Time.time + endSceneLoadDelay + delayBeforeFadeToBlack;
// play a sound on win
var audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = victorySound;
audioSource.playOnAwake = false;
audioSource.outputAudioMixerGroup = AudioUtility.GetAudioGroup(AudioUtility.AudioGroups.HUDVictory);
audioSource.PlayScheduled(AudioSettings.dspTime + delayBeforeWinMessage);
// create a game message
winDisplayMessage.delayBeforeShowing = delayBeforeWinMessage;
winDisplayMessage.gameObject.SetActive(true);
}
else
{
m_SceneToLoad = loseSceneName;
m_TimeLoadEndGameScene = Time.time + endSceneLoadDelay + delayBeforeFadeToBlack;
// create a game message
loseDisplayMessage.delayBeforeShowing = delayBeforeWinMessage;
loseDisplayMessage.gameObject.SetActive(true);
}
}
}
Editor is loading...
Leave a Comment