if (exitEditor.activeSelf)
{
if (File.Exists(Path))
{
deleteSave.interactable = true;
}
else
{
deleteSave.interactable = false;
}
}
}
code
IEnumerator FadeIntoMenu()
{
yield return new WaitForSeconds(InitialWait);
BlackMatte.FadeIn(FadeInTime);
yield return new WaitForSeconds(InitialWait * 2);
WhiteMatte.FadeIn(FadeInTime);
WhiteMatte.FadeOut(FadeInTime);
startable = true;
titleText.SetActive (true);
quit.SetActive (true);
saveEditor.SetActive (true);
}
void LoadLevel()
{
SceneManager.LoadScene(LevelName);
}
public void OpenControlsMenu()
{
GetComponent<AudioSource>().PlayOneShot(ClickButton);
}
public void CloseControlsMenu()
{
GetComponent<AudioSource>().PlayOneShot(ClickButton);
}
public void ExitGame()
{
GetComponent<AudioSource>().PlayOneShot(ClickButton);
Application.LoadLevel(0);
}
public void DeleteSave()
{
//File.Delete(Path);
GameObject.FindObjectOfType<GameMaster>().erase();
}
public void EndGame()
{
GetComponent<AudioSource>().PlayOneShot(ClickButton);
Application.Quit();
}
public void StartLevel()
{
stopSound ();
WhiteMatte.FadeIn(FadeOutTime);
titleText.SetActive (false);
quit.SetActive (false);
saveEditor.SetActive (false);
GetComponent<AudioSource>().PlayOneShot(EnterLevel);
GetComponent<AudioSource>().PlayOneShot(LetsAGo);
Invoke("LoadLevel", FadeOutTime);
}
public void stopSound(){
bool[] wasPlaying;
AudioSource[] allSources = GameObject.FindObjectsOfType<AudioSource>();
wasPlaying = new bool[allSources.Length];
for (int i = 0; i < allSources.Length; i++)
{
var source = allSources[i];
if (source.isPlaying)
{
wasPlaying[i] = true;
source.Pause();
}
}
}
}
Your script manages a start menu for a game using Unity, integrating a variety of elements like UI interactions, fading effects, save file handling, and level loading. Let's dive deeper into each component to ensure everything is optimized and to ensure best practices.
Initialization and Setup:
The Awake method ensures that all UI elements are correctly set up at the start.
Path initialization makes the script adaptable for both editor and runtime scenarios.
Start and Coroutine:
The Start method initializes key bindings and starts the menu fade-in process.
The FadeIntoMenu coroutine handles the fade-in effects, delaying the activation of UI elements until the transitions complete.
Update Method:
The Update method checks for user inputs (both keyboard and mouse/touch) to start the game.
It also manages the interactivity of the delete save button based on whether a save file exists.
UI Interaction Methods:
Methods like OpenControlsMenu, CloseControlsMenu, ExitGame, and DeleteSave provide functionality for button interactions.
Start Level and Stop Sound:
The StartLevel method handles the transition to a new level, including the UI effects and audio cues.
The stopSound method ensures that all audio sources are managed properly.
Here’s an optimized script with improved readability, structure, and comments where necessary:
csharp
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.IO;
public class StarMenu : MonoBehaviour
{
public GameObject DefaultInputs;
public MatteFade WhiteMatte;
public MatteFade BlackMatte;
public float InitialWait = 1.0f;
public float FadeInTime = 0.6f;
public float FadeOutTime = 1.0f;
public AudioClip EnterLevel;
public AudioClip LetsAGo;
public AudioClip ClickButton;
public GameObject QuitButtonExe;
public string LevelName;
private InputManager inputManager;
public bool startable = false;
public GameObject titleText;
public GameObject quit;
public GameObject saveEditor;
public GameObject exitEditor;
public Button deleteSave;
private bool saveExists;
private string SavePath;
void Awake()
{
InitializeUIElements();
SetupInputManager();
SetupSaveFilePath();
}
void Start()
{
inputManager.UpdateKeyBindings();
StartCoroutine(FadeIntoMenu());
if (Application.isWebPlayer)
{
QuitButtonExe.SetActive(false);
}
}
void Update()
{
HandleUserInput();
UpdateDeleteSaveButton();
}
private void InitializeUIElements()
{
titleText.SetActive(false);
quit.SetActive(false);
saveEditor.SetActive(false);
exitEditor.SetActive(false);
deleteSave.gameObject.SetActive(false);
startable = false;
}
private void SetupInputManager()
{
inputManager = FindObjectOfType<InputManager>();
if (inputManager == null)
{
inputManager = Instantiate(DefaultInputs, Vector3.zero, Quaternion.identity).GetComponent<InputManager>();
}
}
private void SetupSaveFilePath()
{
if (Application.isEditor)
{
SavePath = Application.persistentDataPath + "/save.sm64hdrsave";
}
else
{
SavePath = Application.streamingAssetsPath + "/save.sm64hdrsave";
}
}
private void HandleUserInput()
{
if (Input.GetKeyDown(KeyCode.Return) || (Input.GetMouseButtonDown(0)) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
if (startable)
{
StartLevel();
startable = false;
}
}
}
private void UpdateDeleteSaveButton()
{
if (exitEditor.activeSelf)
{
deleteSave.interactable = File.Exists(SavePath);
}
}
private IEnumerator FadeIntoMenu()
{
yield return new WaitForSeconds(InitialWait);
BlackMatte.FadeIn(FadeInTime);
yield return new WaitForSeconds(InitialWait * 2);
WhiteMatte.FadeIn(FadeInTime);
WhiteMatte.FadeOut(FadeInTime);
startable = true;
titleText.SetActive(true);
quit.SetActive(true);
saveEditor.SetActive(true);
}
private void LoadLevel()
{
SceneManager.LoadScene(LevelName);
}
public void OpenControlsMenu()
{
PlayButtonClickSound();
}
public void CloseControlsMenu()
{
PlayButtonClickSound();
}
public void ExitGame()
{
PlayButtonClickSound();
Application.LoadLevel(0);
}
public void DeleteSave()
{
// Note: Ensure GameMaster is properly handling the erase functionality
FindObjectOfType<GameMaster>().erase();
}
public void EndGame()
{
PlayButtonClickSound();
Application.Quit();
}
public void StartLevel()
{
StopAllSounds();
WhiteMatte.FadeIn(FadeOutTime);
HideUIElements();
PlayStartLevelSounds();
Invoke(nameof(LoadLevel), FadeOutTime);
}
private void HideUIElements()
{
titleText.SetActive(false);
quit.SetActive(false);
saveEditor.SetActive(false);
}
private void PlayButtonClickSound()
{
GetComponent<AudioSource>().PlayOneShot(ClickButton);
}
private void PlayStartLevelSounds()
{
var audioSource = GetComponent<AudioSource>();
audioSource.PlayOneShot(EnterLevel);
audioSource.PlayOneShot(LetsAGo);
}
private void StopAllSounds()
{
AudioSource[] allSources = FindObjectsOfType<AudioSource>();
foreach (var source in allSources)
{
if (source.isPlaying)
{
source.Pause();
}
}
}
}
Key Changes and Enhancements:
Encapsulated Initialization Logic: Methods InitializeUIElements, SetupInputManager, and SetupSaveFilePath to make Awake cleaner.
Improved Update Method Logic: Extracted user input handling and delete button update logic to their own methods.
Improved Readability: Added comments and better method structuring to improve readability and maintenance.
Ensured Proper Sound Management: Unified button click sound play logic into PlayButtonClickSound for consistency.
Performance Considerations: Ensured that all update checks are necessary and placed any file IO operations within conditional checks to avoid unnecessary performance hits.
This improved version keeps the core functionality of your original script intact while improving structure and readability. It should be easier to maintain and extend in the future.