Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Audio not playing when scripted to...

Discussion in 'Audio & Video' started by nutntubear, May 18, 2015.

  1. nutntubear

    nutntubear

    Joined:
    May 18, 2015
    Posts:
    4
    Hi everybody,
    I've been struggling with a piece of script and I can't get it to work. The piece I have is as follows:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. function Start () {
    4.     if (PlayerHealth.healthPoints == 5){
    5.         audio.Play();
    6.     }
    7. }
    8.  
    I have this piece of script attached to a GameObject, which also has an Audio Source component on it. What I want to happen is when the healthpoints variable hits 5 (which I know functions, as it works in another piece of script) a clip of audio plays. However, nothing happens. I have tried many things, none of which seem to work with unity 4, which is what I'm using. Any help would be fantastic.

    Thanks!
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Your code is in Start, which means it runs only once. You should put the code in whatever function alters the healthPoints variable.

    --Eric
     
  3. nutntubear

    nutntubear

    Joined:
    May 18, 2015
    Posts:
    4
    I feel incredibly stupid.
    Thank you Eric, it works great now. I must have spaced that-- all I had to do was put it as Update rather than Start.
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    I would not recommend using Update. That means you're checking the value every frame (plus the overhead of running Update), when presumably it doesn't actually change very often. You should really put the code in the function where the variable actually changes; that way the code only runs when it needs to and has no additional overhead.

    --Eric
     
  5. nutntubear

    nutntubear

    Joined:
    May 18, 2015
    Posts:
    4
    Okay, got it. I set it all up and it still works-- thanks again!