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

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


    }
}

最佳答案

您不需要找到游戏对象,只需为按钮提供对撞机和标签,为您的暂停提供暂停标签,然后播放播放标签

      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
                                  }

                        }
                    }
                }
        }
}

关于c# - 使用2个单独的按钮Unity播放和停止音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307426/

相关文章:

android - Android 设备(蓝牙 LE)的上采样 wav 文件

python - audioop的 "sound fragment"参数是什么类型的文件?

c# - 使用反射(+hack)在运行时读取方法值?

android - 使用 actionBarSherlock 仅显示选项卡

android - Nexus 6 的正确屏幕尺寸和密度配置是多少?

php - 使用 android volley 和 php 将波斯语值发布到 mysql

javascript - 如何使用下载属性下载多个音频文件?

c# - jquery如何在c#中编写正确的json对象

c# - 如何避免 GUI 控件和域对象之间的并行继承层次结构

C# String.Substring 剪切出一个 Ip 地址和一个字符串