You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#实现音频进度条遇空引用异常求助

解决Unity音频进度条的空引用与同步问题

一、先排查NullReferenceException的原因

  • 检查Inspector面板:确保source字段已经拖入场景中的AudioSource组件
  • 确认脚本所在的GameObject上挂载了Slider组件,否则GetComponent<Slider>()会返回null
  • 检查AudioSource的Clip属性:必须已经加载WAV音频文件,否则source.clip.length会报错

二、修改代码实现滑块同步与交互

你的代码缺少实时更新滑块位置的逻辑,同时需要完善拖动滑块跳转音频的交互。修改后的代码如下:

using UnityEngine;
using UnityEngine.UI;

public class TimeBar : MonoBehaviour
{
    [SerializeField] 
    private AudioSource source;
    private Slider timeBar;
    // 标记是否正在拖动滑块,避免Update同步覆盖手动操作
    private bool isDraggingSlider;

    public void UpdateSourceTime(float value)
    {
        if(source != null && source.clip != null)
        {
            source.time = value;
        }
    }
    
    private void OnEnable()
    {
        timeBar = GetComponent<Slider>();
        if(timeBar != null)
        {
            // 绑定滑块值变化事件
            timeBar.onValueChanged.AddListener(UpdateSourceTime);
            // 绑定拖动开始/结束事件
            timeBar.onDragStart.AddListener(OnDragStart);
            timeBar.onDragEnd.AddListener(OnDragEnd);
        }
    }

    private void OnDisable()
    {
        // 移除监听避免内存泄漏
        if(timeBar != null)
        {
            timeBar.onValueChanged.RemoveListener(UpdateSourceTime);
            timeBar.onDragStart.RemoveListener(OnDragStart);
            timeBar.onDragEnd.RemoveListener(OnDragEnd);
        }
    }

    void Start()
    {
        if(source != null && source.clip != null && timeBar != null)
        {
            timeBar.maxValue = source.clip.length;
            timeBar.minValue = 0;
        }
    }

    void Update()
    {
        // 未拖动滑块时,同步滑块位置到音频进度
        if(!isDraggingSlider && source != null && source.clip != null && timeBar != null)
        {
            timeBar.value = source.time;
        }
    }

    private void OnDragStart(float value)
    {
        isDraggingSlider = true;
    }

    private void OnDragEnd(float value)
    {
        isDraggingSlider = false;
        // 拖动结束后强制同步,避免偏差
        timeBar.value = source.time;
    }
}

三、验证步骤

  1. 将修改后的脚本挂在带有Slider组件的GameObject上
  2. 在Inspector面板中,把场景中的AudioSource拖入source字段
  3. 确保AudioSource的Clip已赋值目标WAV文件
  4. 运行游戏,播放音频后滑块会随进度同步移动;拖动滑块可跳转音频位置

四、后续研究方向

  • 熟悉Unity的UI事件系统:重点掌握Slider的各类交互事件用法
  • 吃透AudioSource核心API:比如time(当前播放位置)、isPlaying(播放状态)等属性
  • 扩展功能:添加播放/暂停按钮、显示当前时长/总时长的文本标签

内容的提问来源于stack exchange,提问作者Lord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:55:10