使用2个单独的按钮Unity播放和停止音频

时间:2014-10-10 20:18:19

标签: c# android audio unity3d

我是Unity新手,我正在尝试使用2个四边形作为按钮和一个脚本来播放停止音频文件。我搜索过互联网,但我找不到解决问题的方法。

这是我的代码

using UnityEngine;
using System.Collections;

public class PlayStop : MonoBehaviour {
    public GameObject Button1;
    public GameObject Button2;
    public AudioClip Clip;

    void Start()
    {
        Button1 = GameObject.Find ("Fa1Play");
        Button2 = GameObject.Find ("Fa1Stop");
    }
    void OnMouseDown ()
    {
        if (Button1.GetComponent ("Fa1Play"))
        {
            if (!audio.isPlaying)
            {
                audio.clip = Clip;
                audio.Play();
            }
        }

        if (Button2.GetComponent("Fa1Stop"))
        {
            audio.Stop();
        }


    }
}

1 个答案:

答案 0 :(得分:0)

你不需要游戏对象发现只需给你的按钮碰撞器和标签给你的暂停一个暂停标签并播放一个游戏标签

      public class PlayStop : MonoBehaviour {

            public AudioClip aclip;
            private bool stop;

             void Start()
                {
                   audio.clip=aclip;
                   stop=true;
                }


    void Update () 
     {
        if(Input.touches.Length == 1)
        {
        Touch touchedFinger = Input.touches[0];

        if(touchedFinger.phase==TouchPhase.Began){ 
         Ray aRay = Camera.mainCamera.ScreenPointToRay(touchedFinger.position);
          RaycastHit hit;
          if(Physics.Raycast(aRay.origin, aRay.direction, out hit, Mathf.Infinity))
               {

                            if(hit.collider.tag=="stop" && !stop)
                                  {
                                          audio.Stop();
                                          stop=!stop
                                  }
                         if(hit.collider.tag=="play" && stop)
                                  {
                                          audio.Play();
                                          stop=!stop
                                  }

                        }
                    }
                }
        }
}