BackButton.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.SceneManagement;
  4. public class BackButton : MonoBehaviour
  5. {
  6. [Header("Target Scene")]
  7. public string targetSceneName = "TitleScreen";
  8. [Header("Button Reference")]
  9. public Button backButton;
  10. private void Awake()
  11. {
  12. // If no button is assigned, try to find it on this GameObject
  13. if (backButton == null)
  14. {
  15. backButton = GetComponent<Button>();
  16. }
  17. // If still no button found, try to find one in children
  18. if (backButton == null)
  19. {
  20. backButton = GetComponentInChildren<Button>();
  21. }
  22. if (backButton != null)
  23. {
  24. backButton.onClick.AddListener(GoBack);
  25. }
  26. else
  27. {
  28. Debug.LogWarning("No Button component found for BackButton script on " + gameObject.name);
  29. }
  30. }
  31. private void GoBack()
  32. {
  33. Debug.Log($"Going back to scene: {targetSceneName}");
  34. SceneManager.LoadScene(targetSceneName);
  35. }
  36. // Method to set target scene programmatically
  37. public void SetTargetScene(string sceneName)
  38. {
  39. targetSceneName = sceneName;
  40. }
  41. }