2014-10-10 143 views
0

我是Unity新手,我试图使用2个四方形按钮和一个脚本来播放停止音频文件。我搜索了互联网,我还没有找到针对我的问题的单一解决方案。使用2个单独按钮播放和停止音频Unity

这是我的代码

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(); 
     } 


    } 
} 
+0

那你试过吗? – Asenar 2014-10-10 20:20:41

+0

我尝试过HARDLY:D,所以我没有采取任何行动。我想通过按一个按钮播放音频,并用另一个按钮或甚至使用相同的按钮停止播放。我有一个带有2个孩子Fa1Play和Fa1Stop的gameobject PlayStop。我有点糊涂:( – 2014-10-10 20:27:40

+0

,我想提前!!!!! – 2014-10-10 20:34:49

回答

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 
            } 

         } 
        } 
       } 
     } 
} 
+1

我将音频分配给gameobject上的脚本,并将音频源添加到gameobject并将标记更改为小写,并且我在AR相机上有一个音频监听器! – 2014-10-11 14:44:25

+0

http://www.4shared.com/download/i1K2_oOJba/Capture.JPG?lgfp=3000 – 2014-10-11 14:46:51

+0

把调试如果内(hit.collider.tag ==“一站式” &&!停止),看看它被调用 – 2014-10-11 14:47:17