Audio not playing in Unity - c#

I am trying to program a script that when you hit an enemy it plays a sound, problem is I can't get it to play the sound it sees the audio source but my script won't pass the clip to it.
Here is the code I currently have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class makeanoise : MonoBehaviour
{
public AudioClip hurtSound;
public AudioSource soundSource;
private void Update()
{
if (!soundSource.isPlaying)
{
soundSource.clip = hurtSound;
soundSource.Play();
}
}
}
how do you get the audio source to play the sound? because not even my team mates know to do it

I am trying to program a script that when you hit an enemy it plays a
sound
Use collision detection + collider instead of the Update function to detect the hit then play audio:
void OnCollisionEnter(Collision collision)
{
soundSource.Play();
}
If 2D game, use OnCollisionEnter2D instead.
I can't get it to play the sound it sees the audio source but my
script won't pass the clip to it.
There are just many reasons why Audio many not play in Unity. Your sound won't play not because you put it in the Update function.The reason it's not the Update function like some mentioned is because you protected it with if (!soundSource.isPlaying) so it will only play again only when the first one is doe playing.
Reasons why audio won't play in Unity: (From likely to unlikely)
1.The AudioClip is not assigned.
This is your AudioClip
public AudioClip hurtSound;
If hurtSound not assigned or initialized in the Editor or via code, Unity won't throw any error. It simply won't play.
Simply drag the audio to your hurtSound slot and you should hear the sound. Sometimes, the audio reference is lost so simply repeat this step again to recreate the reference.
2.Editor is muted. If the Editor is muted no sound will be coming out of it but the build should have a sound. Check and disable the mute on the Editor.
3.Playing the sound every frame. This mistake is not uncommon and it causes the AudioSource not have time to play the audio over and over again.
Example of this mistake:
private void Update()
{
soundSource.Play();
}
Possible fix:
Check the Audio is playing first before playing it.(Did this in the code from this question which is correct!)
private void Update()
{
if (!soundSource.isPlaying)
{
soundSource.Play();
}
}
4.The GameObject the AudioSource is attached to has been destroyed.
This is also common. If the GameObject the AudioSource has been attached to is destroyed, the Audio would not play.
The fix is to attach the AudioSource to GameObject that doesn't destroy. An empty GameObject is fine.
Or you can play the Audio, wait for it to finish playing then destroy it:
IEnumerator playAudio()
{
//Play Audio
soundSource.Play();
//Wait until it's done playing
while (soundSource.isPlaying)
yield return null;
//Now, destroy it
Destroy(gameObject);
}
5.The GameObject the AudioSource is attached to has been deactivated.
If the GameObject that has the Audiosource is deactivated, the audio would also stop. Don't deactivate the AudioSource GameObject. See #4 for possible workarounds.
6.The code is not even executing.
You must make sure that the Play code is even executing. A simple Debug.Log function call is enough to determine this.
private void Update()
{
if (!soundSource.isPlaying)
{
soundSource.clip = hurtSound;
soundSource.Play();
Debug.Log("Played");
}
}
If you can't see that log in the Console tab then the code is not executing.
A.Script is not attached to a GameObject. Attach it to a GameObject:
B.The GameObject the script is attached to is not Active. Activate it from the Editor:
C.The script is not enabled. Enable it:
7.The AudioSource is muted or volume is 0.
8.The AudioListener component is not present. This is very unlikely since it is automatically attached to your camera. Check if it is deleted by mistake then re-attach it to the camera. It must be attached to the camera not to any other object.
9.Bad Audio. Replace with another Audio.
10.Bug. Go to the Help ---> Report a Bug.. menu and file for a bug report.
This is what to do if everything above has failed. This is unlikely the problem but could happen when there is a big OS update.

You need to have a AudioListener in the scene and also check the 3D sounds settings, the most usual thing is having the AudioListener attached to the main camera.
Check if in the scene is there any AudioListener and the Settings of your AudioSource

One more thing that can cause that it the Pitch settings - i had mine on 0 - i could see the audio playing in the mixer - but no sound would be heard - moved pitch back to 1 - and everything worked well.

Just to help anyone else out, the pitch settings like ash a mentioned actually can cause some strange bugs, the pitch of my audio source was set to -1 as I have a mechanic where points increase the sfx pitch by clicking on things in succession. using AudioSource.PlayClip at point allowed the sound to play but I then removed AudioSource.PlayClipAtPoint to use the cached AudioSource, made sure the pitch initialized at 1f when I wanted the GameOver sounds to play and all worked as expected.

I solved this by playing AudioSource.clip at the position of the main camera. Passing in a Vector3 with x, y, and z all equal to 0 played the sound, but it was quieter. I never got AudioSource.Play() to work.
AudioSource.PlayClipAtPoint(audioSource.clip, mainCamera.transform.position);

Related

I want loop music. How can i make that?

So, i want play music all time.
when the scene is reloaded, the music starts from the beginning, but I want it to continue from the same moment
using UnityEngine;
public class MusicBack : MonoBehaviour
{
private void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("Music");
if (objs.Length > 1)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
Debug.Log("correct");
}
}
I think that you'll need a custom script, like suggested here: https://answers.unity.com/questions/1260393/make-music-continue-playing-through-scenes.html
The idea with that answer is to use DontDestroyOnLoad to keep the audio source the same throughout scenes. So if you move from Scene 1 to Scene 2, the audiosource is still Scene 1's, if I interpreted taht correctly.
Then there's just some logic for not playing the audio in scenes where it shouldn't be played.
Probably this could have been found with a quick google search though.
Enable the loop option in AudioSource. If the music plays in the whole scene, 2D it as well.

Audio doesn't play right after object.instantiate (Unity)

So I have a little game with a gameobject called "bomb". I've coded a script that makes it so whenever you tap or click on the screen, the bomb gameobject gets cloned (using instantiate). Well, on my bomb gameobject I have attached a new script component with
FindObjectOfType().Play("name");
inside. My bomb is supposed to make a boom sound when colliding with something, so a trigger and that line of code above do that exact thing.
And here comes the problem: When I throw multiple bombs (because my game includes throwing as well) the boom sound plays flawlessly, until another bomb explodes and the boom sound goes all the way to the start and plays again.
The thing is I don't want the same sound to stop, go to the start, and then play again, I want multiple sounds that play independently of eachother, so when another bomb explodes, the currently exploding bomb's sound doesn't play again, it should continue playing and another sound to be created for the other bomb explosion.
I've lost so many neurons today trying to figure out how to do this, but I can't find any clue, so I am asking you for your help now! 😉
Here you have a link to a video in which you can hear how bad the explosions sound https://youtu.be/JdIrcgfkVHI
Thanks in advance!!
From what I can tell you are over complicating it when there isn't a need too, Just attach an AudioSource with the bomb clip to the bomb prefab with it set to PlayOnWake.
As for why you're having this issue I think it maybe due to how an AudioSource can only be making one sound at a time so cannot do explosion sounds for 2 bombs at the same time.
EDIT Update after comment
You can change if from PlayOnWake to be triggered when hit by the Player using its tag like in this example.
public class BombDemo : MonoBehaviour
{
private AudioSource _soundEffect;
private void Awake()
{
_soundEffect = GetComponent<AudioSource>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_soundEffect.Play();
}
}
}
This script when attached to a GameObject with an Audiosource will play it when it is triggered by the Player Object colliding with it.
Keeping this logic on the bomb it self is a lot easier to maintain aswell rather than trying to do it all from the Player side, also if you do need to access the PlayerController (or whatever you called it) you can then do so while playing the sound effect using..
PlayerController playerController = other.gameObject.GetComponent<PlayerController>()
..for example

Why does my script, which aims to remove gravity when the game starts, not work?

I'm trying to create a script in Unity wherein the gravity will go to zero when the game starts. The problem is, the gravity was still there after I launched the game.
This is for a Unity3D game. I've already tried to change the variable name, add using System; and moved my script to the top of the Rigidbody component, but none of these things worked.
public class PlayerGrav : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb.useGravity = false;
}
void Update()
{
}
}
I expected the gravity to be removed when the game launches, but in the actual output the gravity still remained, and the cube still fell downwards.
create a new scene
create a new cube
add rb = this.GetComponent<Rigidbody>() to your start function in your PlayerGrav script
attach your PlayerGrav script to the new cube
Hit play, and take look at the "use gravity" property from your new cube's inspector window (make sure the inspector isn't locked to other game object)
If the above tryout succeeds, then you need to check the other code/objects in your original scene. If there are massive other objects in your original scene, then I will suggest disable other objects first, and re-enable them back group by group to see which object/monobhevaiour is causing the issue.
I know this is an old question but I looked forever trying to find an answer to this. I am new to unity so it took me a long time to figure this out but I am using a Rigidbody 2d so this is what worked for me
gameObject.GetComponent<Rigidbody2D>().gravityScale = 0;

AudioSource not playing in Unity3d when EventSystem is in Scene

It took me a while to find it, I even had to re-create the scene and I happened to forget the EventSystem but... I am developing a simple 2D app. Push a button and it plays a random sound. This works, super easy. There's a Button UI element and the OnClick calls my script (which is on an object) and that script plays the audio.
I wanted to add a Pitch slider so the script assigns the audio clip to the AudioSource and I attached the UI Slider's OnValueChanged to my script. Now I realized I need to add my EventSystem but now my buttons won't play the Audio!
I have Debug.Log statements right before the Play() call so I know the button callback is working there's just no audio. Once I delete the EventSystem, the buttons play the audio just fine but now I can't use my slider. Ideas?
Using 2018.2 - Android Build
EDIT
private AudioSource audioSource;
....
IEnumerator PlayClip() {
// Do stuff
audioSource.clip = audioClip;
audioSource.Play();
while(audioSource.isPlaying)
yield return new WaitForSeconds(0.5f);
}
public void ButtonPushed() {
StartCoroutine(PlayClip());
}
public void ChangePitch(float pitch) {
audioSource.pitch = pitch
}
Then the Slider OnValueChanged() just calls ChangePitch with a range -3 to 3. All the code above is just one script and attached to one Controller object.
Don't worry, the Coroutine logic is a little better than that :)
Your issue could be related to this Unity issue:
[AUDIOSOURCE] AUDIO WITH NEGATIVE PITCH DOESN'T PLAY WHEN LOOP IS DISABLED
User shouldn't use negative pitch value, unless one wants the clip to
play backwards in the loop. If user wants it to play once through
backwards, firstly he/she needs to set the position with
AudioSource.time to the end of the clip and then play it.
I ran a test myself and I was able to reproduce your issue under the following conditions:
Looping is disabled on the audio source.
The pitch starts at a negative value.
If the starting value of the pitch is positive, or if it is negative with looping enabled, then I can use the slider to move the pitch between -3 and 3 without a problem.

Unity C# OnTrigger/OnCollision Sound

Note: It's a 2D Game
I'm trying to get an audio clip to play when the Character comes into contact with an object that has a Box Collider around it.
I've tried OnTrigger/OnCollision methods but neither are playing any sound. I've also tried many solutions online but still no sound on collision. My Clip works on Awake, but not as intended.
Checklist:
The Player has a "Player" tag.
The Player has a Rigidbody 2D and a Collider 2D
The Oject Collider has 'Is Trigger' ticked
The Object has an AudioSource
The Object has an Audio Script
The Object has a Box Collider 2D for the collision around it
The Audio Clip is attached to the AudioSource component
Here's the current Script (Attached to Object):
I'd be very thankful!
public class Audio : MonoBehaviour
{
public AudioSource audioClip;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
audioClip.Play ();
}
}
}
In order to find out what is wrong, you can start by simplifying the problem.
You can start by doing something simple in OnTriggerEnter2D, that you know will work, such as a Debug.log
void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(this.gameObject.name+ " collided with "+collision.gameObject.name)
}
This way, you will know if it's the collision or the audio that's the problem.
It may be, that the collision works, but you are unable to hear the audio because of wrong settings or some other minor detail you have missed.

Categories

Resources