Search Unity

Have a look at this code and can you spot it?

Discussion in 'Scripting' started by San_Holo, Oct 23, 2014.

  1. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    The included code basically just tries to play an audio file but not for me, no errors, my other script is calling the function with

    Code (csharp):
    1. if (GameManager.instance)
    2.             GameManager.instance.PlayMusic (0, 3.0f);
    which it is doing but no sound, a debug log shows I fail the first check point, the script itself is attached to a gameobject named Game Manager and I see the serialized list in my inspector which I've inserted two 2D sound clips which I know play and work, but for me I have no sound here, been pouring over it trying to see what I've missed, the code is below, if you can spot anything please advise me, cheers

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class GameManager : MonoBehaviour
    6. {
    7.         [SerializeField]
    8.         private List<AudioClip> MusicClips = new List<AudioClip> ();
    9.         // Number of lives remaining
    10.         private int _lives = 3;
    11.         private AudioSource _music = null;
    12.         private int _currentClip = -1;
    13.  
    14.         public int lives{ get { return _lives; } }
    15.  
    16.         // Player's current score
    17.         private int _currentScore = 0;
    18.  
    19.         public int currentScore{ get { return _currentScore; } }
    20.  
    21.         // Player's current level
    22.         private int _currentLevel = 0;
    23.  
    24.         public int currentLevel{ get { return _currentLevel; } }
    25.  
    26.         // Singleton - Only one game Manager should exist
    27.         private static GameManager _instance = null;
    28.  
    29.         public static GameManager instance {
    30.                 get {
    31.                         if (_instance == null) {
    32.  
    33.                                 _instance = (GameManager)FindObjectOfType (typeof(GameManager));
    34.                         }
    35.                         return _instance;
    36.                 }
    37.         }
    38.  
    39.         void Awake ()
    40.         {
    41.  
    42.                 DontDestroyOnLoad (gameObject);
    43.                 // Init Game State
    44.                 _lives = 3;
    45.                 _currentScore = 0;
    46.                 _currentLevel = 0;
    47.         }
    48.  
    49.         void Start ()
    50.         {
    51.                 _music = audio;
    52.                 if (_music) {
    53.             Debug.Log("found & set");
    54.                         _music.playOnAwake = false;
    55.                         _music.volume = 0;
    56.                         _music.Stop ();
    57.                 }
    58.         }
    59.  
    60.         public void PlayMusic (int clip, float fade)
    61.         {
    62.                 if (!_music)
    63.             Debug.Log("NO MUSIC???");
    64.                         return;
    65.                 if (MusicClips == null || MusicClips.Count <= clip || MusicClips [clip] == null)
    66.                         return;
    67.                 if (_currentClip == clip && _music.isPlaying)
    68.                         return;
    69.                 _currentClip = clip;
    70.                 StartCoroutine (FadeInMusic (clip, fade));
    71.         }
    72.  
    73.         public void StopMusic (float fade = 2.0f)
    74.         {
    75.                 if (!_music)
    76.                         return;
    77.                 _currentClip = -1;
    78.                 StartCoroutine (FadeOutMusic (fade));
    79.         }
    80.  
    81.         private IEnumerator FadeOutMusic (float fade)
    82.         {
    83.                 if (fade < 1.0f)
    84.                         fade = 1.0f;
    85.                 if (_music) {
    86.                         _music.volume = 1.0f;
    87.            
    88.                         float timer = 0.0f;
    89.                         while (timer<fade) {
    90.                                 timer += Time.deltaTime;
    91.                                 _music.volume = 1.0f - timer / fade;
    92.                                 yield return null;
    93.                         }
    94.                         _music.volume = 0.0f;
    95.                         _music.Stop ();
    96.                 }
    97.         }
    98.  
    99.         private IEnumerator FadeInMusic (int clip, float fade)
    100.         {
    101.                 if (fade < 0.1f)
    102.                         fade = 0.1f;
    103.                 if (_music) {
    104.                         _music.volume = 0.0f;
    105.                         _music.Stop ();
    106.  
    107.                         _music.clip = MusicClips [clip];
    108.                         _music.Play ();
    109.                         float timer = 0.0f;
    110.                         while (timer<=fade) {
    111.                                 timer += Time.deltaTime;
    112.                                 _music.volume = timer / fade;
    113.                                 yield return null;
    114.                         }
    115.                         _music.volume = 1.0f;
    116.                 }
    117.         }
    118.    
    119. }
    120.  
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    The if on line 62 only affects line 63 ( no {} to dictate the scope means the if only affects the next instruction)
    So line 64 happens regardless.

    You've essentially written: if no music put a comment on the console, return, <stuff that'll never happen>


    Use { } when using ifs... Or be careful where you insert debug code :p
     
  3. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Thanks, so I painted myself into a corner so to speak, you know with even my limited knowledge just being a couple of weeks into my adventure with Unity and after hours of coding tutorials I did actually think to myself where are those braces and I'm sure I tried that, anyway I'm still debugging, I'm following this in an on-line tutorial and this bug is most likely my inaccurate copy/typing, so I'm going to following it again step by step and just check everything... I do have a valid audio-source component and it's being read and reset in Start() but that's where it leaves me :) so I'm sure it's either a capital letter or a semi-colon or as you say some if statements, I thought I was getting somewhere and when it's not completely obvious you just have to follow the logic & the code and hope you spot it.. I'll report back if I spot my mistake, thanks for the help.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Remember to keep an eye on your warnings too because in this case the compiler should have been telling you there was unreachable code at line 65, which is an unexpected thing to see.

    Ideally, always keep your warnings at zero warnings so when one comes up, it draws your attention.

    And yes, always put your curly braces in your conditional and looping blocks... Save the braceless look for python scripts. :)

    Kurt
     
  5. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    thank you for the advice, in this case I must of missed something, my code again is below, it's verbatim from a tutorial and the link for that is here, around 17mins in till around 27min - thats the bit which is befuddling me for some reason

    the inspector audio clips are good, the scripts attached, the function is being called yet no sound for me and I just can't see why at the moment, so i'll need a pro to fix me up and tell me where I'm going wrong, please advise.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class GameManager : MonoBehaviour
    6. {
    7.         [SerializeField]
    8.         private List<AudioClip> MusicClips = new List<AudioClip>();
    9.        
    10.         // Number of lives remaining
    11.         private int _lives = 3;
    12.         private AudioSource _music = null;
    13.         private int _currentClip = -1;
    14.         public int lives{ get { return _lives; } }
    15.  
    16.         // Player's current score
    17.         private int _currentScore = 0;
    18.         public int currentScore{ get { return _currentScore; } }
    19.  
    20.         // Player's current level
    21.         private int _currentLevel = 0;
    22.         public int currentLevel{ get { return _currentLevel; } }
    23.  
    24.         // Singleton - Only one game Manager should exist
    25.         private static GameManager _instance = null;
    26.         public static GameManager instance {
    27.                 get {
    28.                         if (_instance == null) {
    29.  
    30.                                 _instance = (GameManager)FindObjectOfType (typeof(GameManager));
    31.                         }
    32.                         return _instance;
    33.                 }
    34.         }
    35.  
    36.     void Awake ()
    37.         {
    38.  
    39.                 DontDestroyOnLoad (gameObject);
    40.                
    41.                 // Init Game State
    42.  
    43.                 _lives = 3;
    44.                 _currentScore = 0;
    45.                 _currentLevel = 0;
    46.         }
    47.  
    48.     void Start ()
    49.         {
    50.                 _music = audio;
    51.                
    52.                 if (_music) {
    53.                         _music.playOnAwake = false;
    54.                         _music.volume = 0;
    55.                         _music.Stop ();
    56.                 }
    57.         }
    58.  
    59.     public void PlayMusic (int clip, float fade)
    60.         {
    61.                 if (!_music) return;
    62.                 if (MusicClips == null || MusicClips.Count <= clip || MusicClips[clip] == null) return;
    63.                 if (_currentClip == clip && _music.isPlaying) return;
    64.  
    65.                 _currentClip = clip;
    66.                 StartCoroutine (FadeInMusic (clip, fade));
    67.     }
    68.  
    69.     public void StopMusic (float fade = 2.0f)
    70.     {
    71.         if (!_music) return;
    72.  
    73.         _currentClip = -1;
    74.         StartCoroutine (FadeOutMusic (fade));
    75.     }
    76.  
    77.     private IEnumerator FadeInMusic (int clip, float fade)
    78.         {
    79.                 if (fade < 0.1f) fade = 0.1f;
    80.                 if (_music) {
    81.                         _music.volume = 0.0f;
    82.                         _music.Stop ();
    83.                         _music.clip = MusicClips[clip];
    84.                         _music.Play ();
    85.                         float timer = 0.0f;
    86.                        
    87.                         while (timer<=fade) {
    88.                                 timer += Time.deltaTime;
    89.                                 _music.volume = timer / fade;
    90.                                 yield return null;
    91.                         }
    92.                        
    93.                         _music.volume = 1.0f;
    94.                 }
    95.         }
    96.  
    97.     private IEnumerator FadeOutMusic (float fade)
    98.         {
    99.                 if (fade < 1.0f) fade = 1.0f;
    100.                 if (_music) {
    101.                         _music.volume = 1.0f;
    102.                         float timer = 0.0f;
    103.  
    104.                         while (timer<fade) {
    105.                                 timer += Time.deltaTime;
    106.                                 _music.volume = 1.0f - timer / fade;
    107.                                 yield return null;
    108.                         }
    109.  
    110.                         _music.volume = 0.0f;
    111.                         _music.Stop ();
    112.                 }
    113.         }
    114. }
    115.  
     
  6. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    well in Start() all is well...

    Code (csharp):
    1.     void Start ()
    2.         {
    3.                 _music = audio;
    4.                
    5.                 if (_music) {
    6.             Debug.Log("setup complete");
    7.                         _music.playOnAwake = false;
    8.                         _music.volume = 0;
    9.                         _music.Stop ();
    10.                 }
    11.         }
    and the PlayMusic() function fails on the first hurdle

    Code (csharp):
    1.  
    2.     public void PlayMusic (int clip, float fade)
    3.         {
    4.         Debug.Log("running checks");
    5.         if (!_music) Debug.Log("fail");
    6.         return;
    7.         Debug.Log("check 1 complete");
    8.                 if (MusicClips == null || MusicClips.Count <= clip || MusicClips[clip] == null) return;
    9.         Debug.Log("check 2 complete");
    10.                 if (_currentClip == clip && _music.isPlaying) return;
    11.         Debug.Log("check 3 all passed");
    12.         Debug.Log("fading In");
    13.                 _currentClip = clip;
    14.                 StartCoroutine (FadeInMusic (clip, fade));
    15.     }
    So what happened to my valid audio source? I even used *.wav over my *.ogg sound files thinking it was those, but no I'm slightly baffled here as they say I'm lacking braces for my if's but I'm not getting anything pumped into it for some reason, i'll keep checking
     
  7. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    If your log says "setup complete","running checks" and "fail", try putting a Debug.Break() at the top of PlayMusic() and when it breaks check if the AudioSource is Enabled and if there are more copies of GameManager running (in the project folder right click on GameManager.cs and select "Find References in Scene").
     
  8. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Thank you, I placed the break there and Unity paused and I could see the audio-source is enabled and that there was only one Game Manager in scene, the volume is set to zero, playOnAwake to false etc then it's broken, it usually silently loads the next scene, so I wonder what's really wrong here, I've checked my samples, 3D on off... etc etc as you can imagine I've tried everything I know and I might of either buggered the code myself or I dunno...

    So it's finding the game manager instance and running the PlayMusic function sending an int 0 and a float 3.0f and then poof it's gone... I don't know if it's knowing what the sound is, perhaps the list I've place it in is buggered or my audio-source is not represented or... well I just don't know, might be the the way I've used the editor perhaps but it's not rocket-science is it and I'm sure it can't be that... but thanks for helping me, I want to understand for next time what I've done wrong here, I'm sure the code looks to be fine but I'm just learning as I go, cheers
     
  9. bansheesoft

    bansheesoft

    Joined:
    Oct 3, 2014
    Posts:
    62
    My practice is to always drop the braces to the level of the call but I am old fashioned

    If (x==1)
    {
    AniliteTheWorld(true);
    }

    I feel it easier to read at the cost of one line of code you can see the alignment. Saved me nightmares in the unreal code. And I never do not use them even in one line if else junk.

    If (x==1)
    {
    do(true);
    }

    less prone to error
     
  10. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Thanks yes I must do this just to see, which I did, see below, still no sound for me, so it's a mystery, I have checked for sound in my Unity editor and all is fine there, it's something obvious but hidden perhaps, I just don't know.

    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3.  
    4. public class GameManager : MonoBehaviour
    5. {
    6.         [SerializeField]
    7.         private List<AudioClip>
    8.                 MusicClips = new List<AudioClip> ();
    9.        
    10.         // Number of lives remaining
    11.         private int _lives = 3;
    12.         private AudioSource _music = null;
    13.         private int _currentClip = -1;
    14.  
    15.         public int lives{ get { return _lives; } }
    16.  
    17.         // Player's current score
    18.         private int _currentScore = 0;
    19.  
    20.         public int currentScore{ get { return _currentScore; } }
    21.  
    22.         // Player's current level
    23.         private int _currentLevel = 0;
    24.  
    25.         public int currentLevel{ get { return _currentLevel; } }
    26.  
    27.         // Singleton - Only one game Manager should exist
    28.         private static GameManager _instance = null;
    29.  
    30.         public static GameManager instance {
    31.                 get {
    32.                         if (_instance == null) {
    33.  
    34.                                 _instance = (GameManager)FindObjectOfType (typeof(GameManager));
    35.                         }
    36.                         return _instance;
    37.                 }
    38.         }
    39.  
    40.         void Awake ()
    41.         {
    42.  
    43.                 DontDestroyOnLoad (gameObject);
    44.                
    45.                 // Init Game State
    46.  
    47.                 _lives = 3;
    48.                 _currentScore = 0;
    49.                 _currentLevel = 0;
    50.         }
    51.  
    52.         void Start ()
    53.         {
    54.                 _music = audio;
    55.                
    56.                 if (_music) {
    57.  
    58.                         _music.playOnAwake = false;
    59.                         _music.volume = 0;
    60.                         _music.Stop ();
    61.                 }
    62.         }
    63.  
    64.         public void PlayMusic (int clip, float fade)
    65.         {
    66.  
    67.                 if (!_music) {
    68.                         return;
    69.                 }
    70.  
    71.                 if (MusicClips == null || MusicClips.Count <= clip || MusicClips [clip] == null) {
    72.                         return;
    73.                 }
    74.  
    75.                 if (_currentClip == clip && _music.isPlaying) {
    76.                         return;
    77.                 }
    78.  
    79.                 _currentClip = clip;
    80.                 StartCoroutine (FadeInMusic (clip, fade));
    81.         }
    82.  
    83.         public void StopMusic (float fade = 2.0f)
    84.         {
    85.                 if (!_music) {
    86.                         return;
    87.                 }
    88.  
    89.                 _currentClip = -1;
    90.                 StartCoroutine (FadeOutMusic (fade));
    91.         }
    92.  
    93.         private IEnumerator FadeInMusic (int clip, float fade)
    94.         {
    95.                 if (fade < 0.1f) {
    96.                         fade = 0.1f;
    97.                 }
    98.                 if (_music) {
    99.                         _music.volume = 0.0f;
    100.                         _music.Stop ();
    101.                         _music.clip = MusicClips [clip];
    102.                         _music.Play ();
    103.                         float timer = 0.0f;
    104.                        
    105.                         while (timer<=fade) {
    106.                                 timer += Time.deltaTime;
    107.                                 _music.volume = timer / fade;
    108.                                 yield return null;
    109.                         }
    110.                        
    111.                         _music.volume = 1.0f;
    112.                 }
    113.         }
    114.  
    115.         private IEnumerator FadeOutMusic (float fade)
    116.         {
    117.                 if (fade < 1.0f) {
    118.                         fade = 1.0f;
    119.                 }
    120.                 if (_music) {
    121.                         _music.volume = 1.0f;
    122.                         float timer = 0.0f;
    123.  
    124.                         while (timer<fade) {
    125.                                 timer += Time.deltaTime;
    126.                                 _music.volume = 1.0f - timer / fade;
    127.                                 yield return null;
    128.                         }
    129.  
    130.                         _music.volume = 0.0f;
    131.                         _music.Stop ();
    132.                 }
    133.         }
    134. }
     
  11. San_Holo

    San_Holo

    Joined:
    Sep 26, 2014
    Posts:
    152
    Hey I fixed it...

    I took all the code from Start() and placed it in Awake() see below and it all worked, Sound fades in and plays well, so what went wrong?

    Code (csharp):
    1.         void Awake ()
    2.         {
    3.  
    4.                 DontDestroyOnLoad (gameObject);
    5.                
    6.                 // Init Game State
    7.  
    8.                 _lives = 3;
    9.                 _currentScore = 0;
    10.                 _currentLevel = 0;
    11.         _music = audio;
    12.        
    13.         if (_music) {
    14.            
    15.             _music.playOnAwake = false;
    16.             _music.volume = 0;
    17.             _music.Stop ();
    18.         }
    19.         }
    20.  
    21.         void Start ()
    22.         {
    23.                
    24.         }
     
  12. Deleted User

    Deleted User

    Guest

    Quick not on if statements...

    Only use this, if you only have one line of code to run if your condition matches..
    if (bla)
    do something..;
    anything below this wont run with the if.. it will always run

    now, if you have 2 or more lines of code to run then you use brackets.

    if (bla)
    {
    do something;
    do something else;
    //etc //etc
    }

    Now something extra..
    Switches compile and run faster then if statements..

    so if you have a single value.. lets call it int x;

    switch (x)
    {
    case: 0
    //do something
    break;
    case: 1
    //do something else
    break;
    }

    That code will execute quicker then
    if (i == 0)
    {
    do something;
    }
    else if (i == 1)
    {
    //do something;
    //and some more..
    }
     
    San_Holo likes this.
  13. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    I tested the second code you posted and it worked well. Only difference was I put instance = this; in Start() instead of the _instance = Find() you used (but I think it make no real difference like moving the code from Start to Awake...).
    If you never closed Unity before, then doing so could have fixed the audio problem.
     
    San_Holo likes this.