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. Dismiss Notice

Resolved Particle and sound effects controlled by GetMouseDown

Discussion in 'Scripting' started by 66ALW99, Jul 11, 2023.

  1. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Hi all!

    Been lurking a while and found many a solution to previous issues on these boards (much appreciated, btw - thanks!) so I'm hoping you might be able to help with this one that I've not found covered so far.

    My project involves a flying craft, controlled via the mouse. I have the direction stuff sorted, but I'm having problems with triggering effects via the mouse buttons.

    What should happen is, that the right button being held down should:
    - activate the thruster particle effect (works)
    - play a thruster sound effect (mostly works, sometimes stays on when it shouldn't)
    - apply thruster physics stuff to add the appropriate movement (works)

    The left button being held down should:
    - activate the gun particle effect (doesn't really work - even though I've used GetMouseButton to start the particle system and GetMouseButtonUp to stop it)
    - play a gun sound effect on loop (doesn't work, seems to trigger the thruster effect sometimes, even though I've used "GetMouseButton(0)" for the left mouse and "GetMouseButton(1)" for the right...


    The physics stuff works fine. The thruster particle effect triggers correctly. The thruster sound effect *mostly* works correctly, though occasionally keeps playing when it shouldn't (issues with registering mouse button releases?).

    The left-mouse button stuff is all over the place, even though I copied the code across from the right mouse button stuff, which mostly worked correctly and just changed the if{} bits.

    I'm wondering if there are particular issues around playing sound and particle effects while a particular mouse button is held down? Anyone have a reliable (and preferably simple!) way to do this?

    (I can post my code if needed, but to tell you the truth, I'm willing to start these systems from scratch as my current approach doesn't seem to be 100% reliable anyway)
     
  2. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    With input events you need to decide if you want to use the new Input System or the legacy Input Manager. Input System has more functionality and supports switching and reconfiguring whole action maps, but up to you, for a simple game the old one is fine. When watching tutorials, make sure you understand which one you're watching about.

    The new Input System requires installing a package. You use it with callbacks like OnFire() that will trigger when "Fire" action is invoked, which can be mapped to, say, left mouse, F key and gamepad inputs. And so on.

    If you go with Input Manager, then just put into your Update() like: if Input.GetKeyDown("space") or Input.GetMouseButtonUp(1) (right button released) and go from there.

    Your key logic should go like this
    • If button pressed, start thruster
      • AudioSource.Play
      • Instantiate ParticleSystem prefab
      • Apply thruster physics
    • If button released, stop thruster
      • AudioSource.Stop
      • Destroy ParticleSystem gameobject
      • Stop thruster physics
     
    66ALW99 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    For continuous things like thrusters, do not stop / start the audio or the particle system.

    Set the audio and particle system to Play On Awake and Looped

    Set the particle system emission rate over time to zero

    In your main loop;

    - based on input choose a volume for audio and a quantity for thruster particles

    - set the volume of the audio

    - call .Emit() on the particle system for how much particle you want, OR... set the rate-over-time on the particle system.

    Everything else I won't comment on since it sounds like it works for you, reading keys, etc.

    If you want it smoother, use this pattern:

    Smoothing movement between any two particular values:

    https://forum.unity.com/threads/beginner-need-help-with-smoothdamp.988959/#post-6430100

    You have currentQuantity and desiredQuantity.
    - only set desiredQuantity
    - the code always moves currentQuantity towards desiredQuantity
    - read currentQuantity for the smoothed value

    Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

    The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4
     
  4. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    This method will work but I see no reason why not to stop/start the audio system as it works fully reliably. Just set AudioSource.clip to your sound clip, set loop bit to true, and hit Play(). When you want to stop, hit Stop().

    You can reuse the same AudioSource component after you've used it, and I am reusing mine always, when playing one shots or when looping.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    I have never seen turbomachinery that can stop and start instantly. :)

    I just added particles and sound to my Demo2D SpaceShip2D scene in my Proximity Buttons project.

    Script:

    https://github.com/kurtdekker/proxi...buttons/Assets/Demo2DMovements/SpaceShip2D.cs

    Full project:

    proximity_buttons is presently hosted at these locations:

    https://bitbucket.org/kurtdekker/proximity_buttons

    https://github.com/kurtdekker/proximity_buttons

    https://gitlab.com/kurtdekker/proximity_buttons

    https://sourceforge.net/projects/proximity-buttons/
     
  6. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    Look, it doesn't matter how you like to do it, that's subjective. You're giving advice of doing it in a particular way, which is fine, it's the way you've found best. All good so far.

    But you're giving advice not to use AudioSource in the way Unity recommends it to be used. Then you better have some evidence why one shouldn't trust their AudioSource API cos it doesn't work.

    If you don't have this evidence, you just don't know what you're talking about and it's as good as the day's horoscope and you're just spreading rumours that their stuff don work. Again this is a case where I find you advising against documented use of Unity tools because, for you, they don't work for some reason.
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Where on earth did I say that?!!! Now you're putting words in my mouth!! I simply suggested an approach.

    I was merely listening to the original poster's use case:

    and answering with something simple that suits it.

    I have no idea where you get horoscopes from. This is software engineering.

    I really don't mind if you don't want to use my solution or not. I really don't. Whatever you like, that's okay by me. If it offends you so profoundly, then by all means, don't use my approach.

    EDIT: oh, okay, I get it now, I see your signature:

    It all makes sense.
     
  8. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    You advised not to start/stop audiosources. I pointed out there's no reason not to. You replied to my comment and evaded the question (because you don't have arguments to back up your initial claim). When I pointed this out, you got offended and went into tangent rage. Then trying to blame me for it, you're the one who got offended.

    If you can't back up your claims, don't blame me for pointing this out.
     
    Last edited: Jul 12, 2023
  9. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,300
    There is a reason why you would want to apply what are effectively quick volume envelopes to clips that are starting or stopping half way through, generally.

    To avoid what sound like pops and glitches that will occur if you stop or start in the wrong place in the wrong sound. When you go from no volume to high volume, or from high volume to no volume immediately, that drastic change sounds like a pop or glitch.

    Anyway, here is some simplistic code I put together for the OP to consider that illustrates what they asked for, and also applies a linear volume envelope both for starting and stopping the sound.

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class TestStop : MonoBehaviour
    7. {
    8.     public AudioClip clip;
    9.     private AudioSource source;
    10.  
    11.     public float VolumeEnvelopeSpeed = 5f;
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         source = gameObject.AddComponent<AudioSource>();
    16.         source.clip = clip;
    17.         source.loop = true;
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if (Input.GetMouseButton(0))
    24.         {
    25.             if (!source.isPlaying)
    26.             {
    27.                 source.volume = 1f;
    28.                 source.Play();
    29.             }
    30.             if (!Mathf.Approximately(source.volume, 1f))
    31.             {
    32.                 source.volume += VolumeEnvelopeSpeed * Time.deltaTime;
    33.             }
    34.          
    35.         }
    36.         else
    37.         {
    38.             if (source.isPlaying)
    39.             {
    40.                 if (!Mathf.Approximately(source.volume, 0f))
    41.                 {
    42.                     source.volume -= VolumeEnvelopeSpeed * Time.deltaTime;
    43.                 }
    44.                 else
    45.                 {
    46.                     source.Stop();
    47.                 }
    48.             }
    49.         }
    50.     }
    51. }
    52.  
     
    Last edited: Jul 12, 2023
    66ALW99 and KillDashNine like this.
  10. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Thanks for this. I'll have a look at the new system. The flexibility makes it sound like it's worth learning now, even if this particular project doesn't need it. I mean, my current thing isn't working correctly so I might as well just get to grips with a new approach that could be useful in the future!
     
  11. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Thanks, I think that could come in handy when I go to fine-tune the audio!
     
  12. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Thanks for the reply. The thruster physics and particles are actually working okay, though! It's the audio for it that's slightly screwy.

    My gut feeling is that the issue is to do with reading the inputs and then having those inputs trigger the particles and audio. One particle effect (thruster) works. Despite using the same basic code with minor changes (like which mouse button is used), the other particle system (the gun) doesn't..
     
  13. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    Make sure you're not hitting Play() in a loop every frame, but you only hit it when your button is pressed, and stop when your button is released. Whether you use Play-Stop or creating a new AudioSource and destroying it. Put a Debug.Log line where your audio starts.

    If you do it with the new Input System, its sorta easier because you don't need to make some if-structure into Update() but you just make a callback and the system will call your event handlers. The system practically replaces all this input controller code people would write for this logic.
     
    Last edited: Jul 12, 2023
    66ALW99 likes this.
  14. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Sounds ideal - managed to do a little testing, printing every action to the log, and I suspect my issues are to do with the if statements not triggering actions correctly. Hopefully I'll get some time over the weekend to play with the Input System and get it all working properly! Thanks again
     
  15. 66ALW99

    66ALW99

    Joined:
    Feb 2, 2023
    Posts:
    12
    Managed to sort it - Although I'd copied the input stuff from one script to another, it turns out I'd attached the scripts to their respective GameObjects differently. Because I'm a dumbass. Anyway, spent the morning tidying up all the scripting stuff so it's more simplified and compartmentalised now.

    Thanks to everyone who weighed in - even though there's no fix for my dumbassery, the suggestions were still helpful and I'll likely implement them later!
     
    Kurt-Dekker likes this.