Unity C# OnTrigger/OnCollision Sound - c#

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.

Related

Destroying an object on collision

I've been trying a way to get rid of an enemy in my game, but once the weapon in the game collides with it it does not do what it's suppose to do. So I tried a different way by turning of the box collider2d, the sprite renderer and another script inside it. But it still does not work.
enter image description here
Just use Destory to destroy the gameObject
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Sword")
{
Destroy(this.gameObject);
}
}

detecting collisions and destroying gameObjects in Unity

So I'm attempting to create a 2D game in Unity where the gameObjects would be destroyed upon hitting the walls. So i decided to use the isTrigger function and add the script to each of the walls. However, I do not know why the gameObjects don't get destroyed. I have tried to set Collision type as both discrete and continuous for the walls and gameobjects and I've also added static rigidbodys to the walls to see if that would help and even tried changing the size of the collisionbodys of the walls.
Here is the code for the wallscript
public class wallScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnTrigger2D(Collider2D other)
{
if (other.tag == "player01")
{
Destroy(other.gameObject);
}
}}
p.s. Even if I remove the conditional statement Destroy() still does not work
You should use void OnCollisionEnter2D(Collision2D other) {...} instead of void OnTrigger2D(Collider2D other).
And uncheck Is Trigger checkbox on your object's Collider.
To Fix The Problem You Are Facing, First Select The Wall Sprite In The Scene, Scroll Down To The Collider And Make Sure Is Trigger Is Checked.
Other Than That Just Check If The Tag You Typed Into The Code Matches The Player You Are Trying To Destroy. Remember, It's Case Sensitive!
After That The Code Should Run Just Fine.

Audio not playing in Unity

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);

Unity5 OnTriggerEnter2D not called after collision (2D game)

I'm brand new to Unity3D 5 and I'm having issues with my first 2D game involving collision detection. My moving object is a ball and has Rigidbody2D and CircleCollider2D. My stationary "collider or trigger" is a BoxCollider and has a script attached. The OnTriggerEnter2D should be fired when the ball passes through the stationary box. I've also tried OnCollisionEnter2D but I'm fairly certain I should use OnTriggerEnter2D because my stationary box is marked as a trigger.
My code:
public class LoseCollider : MonoBehaviour {
public LevelManager levelManager;
void OnCollisionEnter2D(Collision2D collision)
{
print("collide");
levelManager.LoadLevel("Lose");
}
void OnTriggerEnter2D(Collider2D trigger)
{
print("trigger");
levelManager.LoadLevel("Lose");
}
void OnCollisionEnter(Collision collision)
{
print("collide");
levelManager.LoadLevel("Lose");
}
void OnTriggerEnter(Collider trigger)
{
print("trigger");
levelManager.LoadLevel("Lose");
}
}
As you can see I'm testing all variations and none are being called. Here are my Unity properties for my objects:
And
I'm sure I'm missing something simple if anyone can please point it out to me.
If you are going to to use OnTriggerEnter2D, you must also use a 2D Collider. You are currently using BoxCollider as shown in your second screenshot.
Change that to BoxCollider2D and your Collision callback functions should be called.
I know you already solved it, but I ran into the same problem and found your post. I was using the correct 2D collider, I was missing the Ridgedbody 2D component. It took me a while to find that so I wanted to add it here in case someone else comes across the same problem.

How to spawn a collider after exiting a trigger? (Bomberman style game)

I trouble trying to get this to work. here is the problem.
When I spawn I bomb with a collider, it presses my character out of the way, forcing him either in the wall or to a side.
Now my character instantiates a Bomb gameobject with a bomb script.
What I want and my thought process:
I was thinking it might be possible having a triggercollider on the instantiated bomb, and no collider, but when my character "leaves" the bomb radius it spawn a regular collider.
Then He can't get stuck, and when he has exited he can't just past through it again.
But I don't know how to write this, any suggestions?
Or any better ideas? Thanks for all help :)
ps: ( I use c#)
You almost get a solution.
1. in bomb collider check trigger;
2. in bomb script at start get reference to collider
3. in OnTriggerExit set isTrigger to false
public class bomb : MonoBehaviour {
BoxCollider collider;
void Start () {
collider = gameObject.GetComponent<BoxCollider> ();
}
void OnTriggerExit(Collider other)
{
collider.isTrigger = false;
}
}
P.S. don't mix 3d and 2d colliders. Code sample for 3d, in 2d it slightly different.

Categories

Resources