按下发射空格键时会播放AudioSource吗?

时间:2019-02-14 01:43:03

标签: c# unity3d

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class GunLaser: MonoBehaviour
{
    private AudioSource playAudio;
    private bool isActive = true;

    void Start()
    {
        playAudio = FindObjectOfType<AudioSource>();
    }

    void Update()
    {
        if (isActive)
        {
            ProcessFiring();
        }
    }

    void ProcessFiring()
    {
        if (CrossPlatformInputManager.GetButton("Fire"))
        {
            SetAudioSourceActive(true);
        }
        else
        {
            SetAudioSourceActive(false);
        }
    }

    private void SetAudioSourceActive(bool isActive)
    {
         playAudio = gameObject.GetComponent<AudioSource>();
         playAudio.enabled = isActive;
    }
}

当我按住火/空格键并按住不放时,音频源将停止播放,但是如果我继续轻按火/空格键,它将播放。按住火/空格键时如何播放?任何见识都值得赞赏。

1 个答案:

答案 0 :(得分:0)

最简单的方法是:

void Update()
    {    
       if(CrossPlatformInputManager.GetKeyDown(KeyCode.Space))
           playAudio.Play()

       if (CrossPlatformInputManager.GetKeyUp(KeyCode.Space))
           playAudio.Stop()
    }

代替启用和禁用音频源,您可以使用音频源播放和停止。