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.
Related
So, I recently learned how to animate certain objects, but I don't know how the code works.
I learned the animator tab, where idle camera animation will transition from walking if I am holding my movement keys. I searched tutorials on youtube and google, but all I can find are animations found on models, not actually on the camera.
If I used that logic on a camera, nothing actually happens, and I don't know what to write.
I've set a bool, which is labeled "WalkingForward", because I have different animations on different movements.
When it is true, the forward walk animation will play, and if false, it turns back to idle animation.
The only thing I can't figure out is a code that will detect the "Horizontal" and "Vertical" movements to start playing the animation.
Here is the link of my animator controller tab https://imgur.com/a/euM9yFl , and I would really appreciate if someone has an idea.
You can handle/detect movement in the Update() method for a GameObject, then get the Animator for the Camera and set the Animator parameters.
See Unit Animation Parameters Docs for more info, but the general idea is something like this:
// Update method attached to wherever you want to detect movement
void Update()
{
// isMovingHorizontally and iMovingVertically are not defined here
// They could either be based off the speed/momentum of the GameObject
// Or the input from the player
var isMovingHorizontally = isMovingHorizontally();
var isMovingVertically = isMovingVertically();
animator.SetBool("MovingHorizontally", fire);
animator.SetBool("MovingVertically", fire);
}
I have a audio player during scene 0 in my game (the menu). I have a code that intends to prevent the objects destruction when changing scenes. This works.. mostly. But for some reason, when moving to scene 1 a second audio player is created. This does not happen when moving to scene 2, 3, etc. I cannot find any components in scene 1 indicating a second audio player.
I have attached screen shots that may be of assistance. Any help with this would be greatly appreciated. I am stumped.
audio player and code ....
duplicated audio in scene 1....
In your Scene Changing Script, Create a New Function (or edit existing function)
LoadSceneWithoutAudioDestruction or Whatever seems good to you
Then Write down the Following Code.
public GameObject AudioSouce; //in starting of file to reference Audio
public void LoadSceneWithoutAudioDestruction(){
DontDestroyOnLoad(AudioSouce);
SceneManager.LoadScene(SceneNameasString);
}
Now on button which you want to Load next Scene attach this Script and ad function LoadSceneWithoutAudioDestruction to On Button click Event of that button.
Also Ensure that the next scene that you are Loading does not habe any Audio Source Already
If any Problem exists, ask me in comment.
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
I am trying to start an animation by pressing a key on my keyboard.
For this I am using the following code:
[HideInInspector] public Animation animation;
private void Start()
{
animation = GetComponent<Animation>();
}
private void Update()
{
if (Input.GetKeyDown("1"))
{
animation.Play("AnimationName");
}
}
This gives me the following error:
The animation state AnimationName could not be played because it
couldn't be found!
Although, the animation DOES start, but how can I clear this error?
I think the only possible explaination is that your animation clip is not marked as Legacy.
https://www.unity3dtips.com/zh/the-animation-state-could-not-be-played-because-it-couldnt-be-found/
EDIT with step by step here:
Animations must be marked as legacy to be used with the animation component.
In the project window select the animation clips you’re trying to play.
Set the inspector to debug mode which exposes hidden variables, in this case it’ll make the “Legacy” checkbox appear.Unity Inspector Debug Mode
Tick the “Legacy” checkbox and change the inspector back to normal mode.
Unity Inspector Animation Clip Legacy Checkbox
But there is one thing you should know: you should avoid, if possible, the old legacy way to play animation.
Learn how to use an Animator component. Just create an animator, assign your animation clip, decide a boolean for start the animation in the animator component and set it to true in your code (for basic use).
Sure there is some things to do beside code but it will be easier to control your animation, bleand different animations and change them to your needs (it's for example much easier to loop or stop the animation at some point).
It would be also easier to understand when it start and when is playing.
Another thing to check is the legacy 'Animation' component on your gameObject that is supposed to perform the animation. In my case things were marked as legacy for the animation on the imported animation but somehow when adjusting settings on my import it dropped the animation it was complaining about from the actual 'Animation' component so once I added it things worked as expected
Inspector in Debug mode showed my animation marked as 'Legacy' true
My Animation component showed the missing animation
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);