先给物体添加音效控件,然后把下载的声音添加到Audio Source中。
音效代码
在代码中声明两个变量,一个是音频源( public AudioSource audioSource;)一个是音频(public AudioClip bulletSound)
using UnityEngine;
public class ShootingAudio : MonoBehaviour
{
public AudioSource audioSource;//射击音频源
public AudioClip bulletSound;//射击音频
public AudioSource sjinbi;//金币
public AudioClip jinbi;//金币
void Update()
{
if (Input.GetButtonDown("Fire1")) // 如果按下鼠标左键或按下键盘上的射击键
{
PlaySound();//播放声音
}
}
void PlaySound()//射击
{
audioSource.clip = bulletSound; // 设置音频片段为射击音效
audioSource.Play(); // 播放音效
}
void jinbiPlaySound()//金币 添加到金币消失响声音的地方
{
sjinbi.clip = jinbi;
sjinbi.Play();
}
}
jinbiPlaySound();添加到合适位置
作业代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//
public class NewBehaviourScript : MonoBehaviour
{
//射线发射到屏幕中间,击中物体,销毁物体(只有点中屏幕中间的物体他才会消失)
Vector3 ScreenMidPos;//引用屏幕中间
float fenshu;
public Text scoretytext;//
public AudioSource audioSource;
public AudioClip bulletSound;
public AudioSource sjinbi;
public AudioClip jinbi;
void Start()
{
//MaCamera=Camera,main;
ScreenMidPos = new Vector3(Screen.width / 2, Screen.height / 2, 10f);//找到屏幕中心
Debug.Log(Screen.width);
fenshu = 0;
}
// Update is called once per frame
void Update()
{
Ray OneRay = Camera.main.ScreenPointToRay(ScreenMidPos);//射线=摄像机的点到屏幕中心点连成的线
if (Input.GetKeyDown(KeyCode.Q))//如果用户点下Q键就射击物体让物体消失
{
PlaySound();
RaycastHit ShotEnemy;//将用户点到的物体临时存放到ShotEnemy中
if (Physics.Raycast(OneRay,out ShotEnemy) && ShotEnemy.transform.gameObject.CompareTag("Player"))
{
fenshu = fenshu + 1;
Debug.Log("射中了物体他叫" + ShotEnemy.transform.name+"开始加分,当前分数:" + fenshu);
jinbiPlaySound();
Destroy(ShotEnemy.transform.gameObject);
scoretytext.text = "当前分数:" + fenshu;//
}
}
}
void PlaySound()
{
audioSource.clip = bulletSound;
audioSource.Play();
}
void jinbiPlaySound()
{
sjinbi.clip = jinbi;
sjinbi.Play();
}
}