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
Related
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.
I created a project using the FPS Microgame in Unity Hub to learn scripting. I'm trying to play a simple particle effect when the player collides with it (in the future I'd love to be able to trigger it from farther away, maybe when crossing into a plane, but I'll learn that later). I created the following script and attached it as a component to the particle effect on the scene:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class portalTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play();
}
}
And here's what the particle effect looks like in the Unity Inspector:
The particle effect plays when the game starts if I select Play on Wake so I disabled it because I want it to play when the user collides with it. Any ideas?
Thanks!
First I would add a debug print to verify that a collision is triggered in the onTriggerEnter method.
If that is not the case, I would check that both game objects have a rigid body and a collider. One (and only one) of the two colliders must have the isTrigger flag set.
Here is unity doc link for reference:
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
Had you quite made sure that the isTrigger option in object main object has been checked true?
If not then either see the way to check it( What do I mean here is that if you only check isTrigger without making another collision than object won't stop even after the collision. It had been really hectic for me when I started.)
or use the OnCollisionEnter. If none of these happened then try printing to see if they're even colliding or not. C'mon you are trying to become a Unity scripter so best way is to debug anything you doubt about.
So I've just been tinkering with unity and all yesterday I was making a little game. I have a main menu when you start the game, the game itself and a gameover menu when you die that puts you back at the home screen, but I have no clue how to set it when a thing/enemy hits the player, It brings you to the restart menu on collision with it. anyone know any code to help out, I've been trying to find videos but they are not what I need. I need when on collision set scene to GAMEOVER. But don't know how, PLZ help.
So to what I understand you want to make a collision and restart you scene or go to another scene ?
You need to use something like this.
I added 3 possibiities of Scenemanager.LoadScene however you need to use them.
make sure to add the the using UnityEngine.SceneManagement; at the top
using UnityEngine.SceneManagement;
void OnCollisionEnter(Collision collision)
{
//if you want to load another scene
SceneManager.LoadScene("OtherSceneName");
//if you want to load the same scene you are on
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
//if you want to load the same scene you are on
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
To know if an object with a Collider was hit in Unity (e.g. the player) you need to add one of the OnCollision functions to your script:
OnCollisionEnter - is called when the object is first hit
OnCollisionStay - is called every frame while the object is being touched
OnCollisionExit - is called on the frame the object stops being touched
Then, in the function you can load a different scene using SceneManager.LoadScene
This is the current script that I have. I have a ball that is player, and I want a collision with my game object tagged as "pit" to end the game. When the game ends I want my game over canvas to pop up. The current script detects the hit when the player rolls over the pit, however, currently, nothing else happens. Both my player and pit have rigidbodies and colliders attached to them. I would really appreciate any help with how to get my code to work properly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public GameObject GameManager;
private void OnTriggerEnter(Collider other)
{
Debug.Log("hit detected")
if(other.gameObject.tag == "pit")
{
GameManager.GetComponent<Game_Manager>().EndGame();
}
}
}
My EndGame code is in my GameManager script. The is the part of that script that deals with ending the game.
public void EndGame ()
{
player.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
hasGameStarted = true;
inMenuUI.gameObject.SetActive(false);
inGameUI.gameObject.SetActive(false);
gameOverUI.gameObject.SetActive(true);
}
If I'm correct in interpreting your question, your script successfully detects player death already. If you want a game over screen you have a couple of options:
You can create a UI canvas with a panel on it that obscures the whole screen and put the words Game Over.
Or, probably the better option is to create an entirely new Unity scene and make the Game Over canvas there. When you want to trigger the game over screen you simply use:
Scene manager.LoadScene("Scene name");
You have to add "using UnityEngine.SceneManagement;" at the top of your script. Also note you have to add your Game Over scene to the list of scenes in you game. I believe this can be done by navigating to File>Build settings>scenes and then pressing add open scenes assuming the game over scene is open.
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);