0
\$\begingroup\$

This code is supposed to play a sound when I press 'E' but it's not working. also keep in mind I'm new to unity and coding in general so don't be to harsh if I made a really dumb mistake.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class flashlightonoffsound : MonoBehaviour
{

    public AudioSource flashlightsound;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            flashlightsound.Play();
        }
        else
        {
            flashlightsound.Stop();
        }
        
    }
}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Delete this:

flashlightsound.Stop();

Also make sure you have AudioListener somewhere (usually attached to camera). And make sure AudioSource component is added to the gameobject AND you have access to to it:

void Start()
{
    flashlightsound = transform.GetComponent<AudioSource>();
}

And make sure your audioClip is attached to audio source and everything will work!

Also make sure your audioListener (usually in camera) is not too far from from AudioSource!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .