1
votes

So for starters, I wish to say that the code below works. But its not structured how I want it to:

public AudioClip pickup;

void OnTriggerEnter(Collider collider)
{
    //Trigger for pickups
    if (collider.gameObject.CompareTag("Pickup"))
    {
        AudioSource audio = GetComponent<AudioSource>();
        audio.PlayOneShot(pickup);
    }
}

But I want to split the class into two and have the player controller (part of it written above) be used to call a function from a new class called 'LevelClass' which will house the method for pickup like so:

public void collidePickup(Collider collider)
{
    collider.gameObject.SetActive(false);
    AudioSource audio = GetComponent<AudioSource>();
    audio.PlayOneShot(pickup);
}

and have player controller call the function like so:

 level.collidePickup(collider);

I also linked the sound file with the script so that it would have a sound to play on. From testing, I determined that the problem is being caused in the AudioSource section as its not finding an audio source to work with. Is there something i can do so that i would be able to use an instance of audiosource within the levelclass rather than in the playercontroller?

2

2 Answers

0
votes

You should be able to pass a reference to your audio source into the function like this.

public void collidePickup(Collider collider,ref AudioSource audio)
{
    collider.gameObject.SetActive(false)
    audio.PlayOneShot(pickup);
}

Then you just need to pass the AudioSource to he function when you call it.

0
votes

You should know, that every AudioSource emits sound according to it's position and uses Doppler effect parameters with it's rigidbody relative velocity.
Also note that every AudioSource can play exactly one clip at a time.

One of the solutons is to create a new GameObject with AudioSource on it (either from prefab on the your audio manager object or from code) for every sound that you want to play in your game, and immediately Destroy it with timeout equal to audio length.

public void collidePickup(Collider collider) 
{
    collider.gameObject.SetActive(false);
    PlaySoundAt(pickup, collider.transform.position);
}

private static void PlaySoundAt(AudioClip sound, Vector3 position) 
{
    var go = new GameObject("PickupSound");
    go.transform.position = position;
    var source = go.AddComponent<AudioSource>();
    source.PlayOneShot(sound);
    Destroy(source, sound.length);
}