游戏的一个比较重要的点就是进行声音的正常播放,网上有各种各样的教程,但是很多都比较复杂或者比较长,在观看和摸索网上的一些教程之后,在这里给出一个我的办法。
首先创造一个sound manager脚本,作为主脚本,如果以后不止一个人物,或者说有其他的音乐,比如首页面的bgm或者是场景的声音,亦或者是踩在不同土地的声音的时候,可以再写一个脚本来继承sound manager,比如playerSoundManager或者是enemySoundManager在这里我给出一个模板。
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.InputSystem;
public class soundmanager : MonoBehaviour
{
public static soundmanager Instance { get; private set; }
//这里挂载需要的音乐
[Header("Player sound")]
public AudioClip jumpsound;
public AudioClip sprintsound;
public AudioClip healsound;
public AudioClip attacksound;
private AudioSource playersource;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
private void Start()
{
//初始化
initsource();
}
private void initsource()
{
//给对象添加
playersource = gameObject.AddComponent<AudioSource>();
}
public void healsounds()
{
playersource.clip = healsound;
playersource.Play();
}
public void attacksounds()
{
playersource.clip = attacksound;
playersource.Play();
}
public void jumpsounds()
{
playersource.clip = jumpsound;
playersource.Play();
}
public void sprintingsound()
{
if(!playersource.isPlaying)
{
playersource.clip = sprintsound;
playersource.Play();
}
}
}
创建完之后,将脚本放在hierarchy窗口里面,将音乐添加到脚本身上,例如:
然后可以通过在其他脚本里面调用这个脚本,比如有一个playermanager脚本,此时正挂载在敌人身上,脚本内容可以向以下这样。:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermanager : MonoBehaviour
{
public soundmanager soundmanager;
public void ishealsound()
{
soundmanager.healsounds();
}
}
然后将soundmanager脚本所在的地方拖到这个玩家的playermanager上
再到hierarchy窗口上点击角色所在的地方,然后
点击这个上面的animation,把animation窗口调出来,然后在动画里面添加playermanager的ishealsound()事件就好了