In the game "Snake", there is background music that plays from the start of the level.

Here she is:

enter image description here

And also there is a sound that is played only with the "Game Over" screensaver.

Here he is:

enter image description here

What exactly am I doing?

HealthManager Script:

using UnityEngine; using System.Collections; public class HealthManager : MonoBehaviour { public int maxPlayerHealth; public static int playerCurHealth; public Game gameManager; //переменная главного меню public string mainMenu; public GameObject gameOverScreen; public Player player; public float waitAfterGameOver; public GameObject musicBack; public GameObject musicGameOver; // Use this for initialization void Start () { //musicGameOver.gameObject.SetActive(false); playerCurHealth = maxPlayerHealth; gameManager = FindObjectOfType<Game>(); player = FindObjectOfType<Player>(); } // Update is called once per frame void Update () { if (playerCurHealth <= 0) { //playerCurHealth = 0; gameOverScreen.SetActive(true); player.gameObject.SetActive(false); musicBack.gameObject.SetActive(false); musicGameOver.gameObject.SetActive(true); } if (gameOverScreen.activeSelf) { waitAfterGameOver -= Time.deltaTime; } if (waitAfterGameOver < 0) { Application.LoadLevel("mainMenu"); } if (playerCurHealth > maxPlayerHealth) { playerCurHealth = maxPlayerHealth; } } public void TakeLife() { playerCurHealth--; } public void FullHealth() { playerCurHealth = maxPlayerHealth; } } 

That is, the sound of the Game Overa is set to off. (Yes, I don’t understand to the end what the tick is taken off (somewhere in the next topic this was discussed)). When the "Game Over" screensaver appears, the music is transferred to SetActive(true); , then it returns us to the main menu and what is the actual question ... When I switch the camera there (via buttons and SetActive), then when I lose again and the "Game Over" screensaver, this error pops up:

enter image description here

What am I doing wrong? What I do not know? How to make the sound play equally in both cases at different positions of my camera? What does the error message mean and how to fix it?

UPDATE:

To comment below. enter image description here

I just noticed such a strange thing that when the GameOverScreen appears, the first camera is still working (as it should be), with the second camera the situation is different. Already on the GameOverScreen it does not work (not active, a check mark is removed from the object (how to say it right?)).

SwitchCameras script:

 using UnityEngine; using System.Collections; public class SwitchCameras : MonoBehaviour { public Game theGame; public static int numberOfCamera; private void Start() { theGame = FindObjectOfType<Game>(); //theGame.cam1.enabled = true; //theGame.cam2.enabled = false; } public void Switch1() { numberOfCamera = 1; //theGame.cam1.enabled = !theGame.cam1.enabled; //theGame.cam2.enabled = !theGame.cam2.enabled; } public void Switch2() { numberOfCamera = 2; //theGame.cam1.enabled = !theGame.cam1.enabled; //theGame.cam2.enabled = !theGame.cam2.enabled; } } 

Game Script:

 using UnityEngine; using System.Collections; public class Game : MonoBehaviour { // материал стен public Material wallMaterial; // набранные очки //public static int points; // количество стен в уровне public int countWals = 10; //private string _pointsString; //private int _lastPonts = -1; //игровой объект - текщий чекпоинт public GameObject currentCheckpoint; //штрафные очки за смерть public int pointPenaltyOnDeath; //наш игрок private Player player; public HealthManager healthManager; //камеры для переключения public Camera cam1; public Camera cam2; // генерируем уровень при загрузке сцены public void Awake() { if (SwitchCameras.numberOfCamera == 1) { cam1.gameObject.SetActive(true); cam2.gameObject.SetActive(false); } if (SwitchCameras.numberOfCamera == 2) { cam1.gameObject.SetActive(false); cam2.gameObject.SetActive(true); } // обнуляем очки //points = 0; // генерируем уровень GenerateLevel(); // ставим первую еду Food.GenerateNewFood(); } public void Start() { //игрок это объект со скриптом Player player = FindObjectOfType<Player>(); healthManager = FindObjectOfType<HealthManager> (); } public void Update() { // обновление отображаемого текста очков только при их изменении //if (_lastPonts == points) return; //_lastPonts = points; // форматируем очки в формате четырех цифр, начинающихся с нулей //_pointsString = "Score: "+ points.ToString("0000"); } // отрисовка набранных очков //public void OnGUI() //{ //GUI.color = Color.yellow; // GUI.Label(new Rect(20, 20, 200, 20), _pointsString ?? ""); //} // функция генерации уровня private void GenerateLevel() { for (int i = 0; i < countWals; i++) { // создаем куб GameObject wall = GameObject.CreatePrimitive(PrimitiveType.Cube); // называем его "Wall" wall.name = "Wall"; // увеличиваем его габариты wall.transform.localScale = new Vector3(2,2,2); // расставляем его так, чтобы координаты были не в центре игрового поля var pos = new Vector3(Random.Range(-40, 41), 0, Random.Range(-40, 41)); while (Mathf.Abs(pos.x) < 10 || Mathf.Abs(pos.z) < 10) { pos = new Vector3(Random.Range(-40, 41), 0, Random.Range(-40, 41)); } wall.transform.position = pos; // и назначаем материал wall.GetComponent<Renderer>().material = wallMaterial; } } // функция восскрешения(респауна) игрока public void RespawnPlayer() { ScoreManager.AddPoints (-pointPenaltyOnDeath); player.enabled = false; //чтобы видеть в логе, что респаун прошёл успешно Debug.Log ("Player Respawn"); //перемещаем игрока в местоположение чекпоинта player.transform.position = currentCheckpoint.transform.position; player.enabled = true; } } 

Link to the project

  • No listener says. It is necessary that at AudioListener one was .... apparently there is an AudioListener on one camera, and the other is not ... and turn on the camera where there is no such component - Alexey Shimansky
  • @ Alexey Shimanskiy UPDATE - Artik Slayer 5:38 pm
  • It's somehow difficult)) somewhere in some listener script you do enabled = false ... you need to look at the project better, where you assign false to ... By the way, how interesting SwitchCamers work for you. I think this script will not find FindObjectOfType<Game>() - Alexey Shimansky
  • @ Alexey Shimansky why? - Artik Slayer
  • Well, the Game is in your Game)) and the script in the Menu is Alexey Shimansky

0