Calling a scripts function whenever another scripts function runs

I’m making a pitch randomizer for my weapon audio sources in my game, and I want to be able to attach a script and just have the pitch change every time the audio source plays. I tried using UnityEvents to get this effect, but couldn’t quite get it to work in the way I wanted. If I could get some advice pointing me in the right direction it would be much appreciated :slight_smile:

using UnityEngine;
using UnityEngine.Events;

public class AudioPitchRandomizer : MonoBehaviour
{
    [SerializeField] float range;
    private AudioSource source;

    UnityEvent OnAudioPlayed = new UnityEvent();

    private void Start()
    {
        source = GetComponent<AudioSource>();

        OnAudioPlayed.AddListener(source.Play);
    }
    private void Update()
    {
        if(OnAudioPlayed)
        {
            ChangePitch();
        }
    }
    void ChangePitch()
    {
        source.pitch = 1 + Random.Range(-range, range);
    }
}

You have UnityEvent backwards. When you call AddListener on UnityEvent (line 15 in your code), you’re adding a callback that will get called when you call ‘Invoke’ on UnityEvent:

It doesn’t listen for when the passed in listener is called. It calls the listener when the event is invoked.

What you’ll need to do is in the place where you call ‘Play’ on the AudioSource, also call some event.