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

Unity 2017.3.0f3报错:当前上下文中不存在名称‘sources’[Assembly-CSharp]求解决

解决Unity中“当前上下文中不存在名称‘sources’”的错误

看起来你在Unity 2017.3.0f3开发SoundManager脚本时遇到了变量未定义的编译错误,我来帮你梳理问题并给出修复方案:

问题根源

从你提供的代码片段来看,错误出在AudioSource[] ...这一行——你大概率是想获取当前GameObject上的AudioSource组件,但要么没有提前声明sources变量,要么代码没写完就触发了编译检查,导致编译器识别不到sources这个名称。

修复方案

根据你的脚本需求(需要一个soundEffectAudio来播放音效),有两种常见的修复方式:

方式1:获取单个AudioSource组件

如果你的SoundManager GameObject上只挂了一个AudioSource组件,直接用GetComponent<AudioSource>()获取并赋值给soundEffectAudio即可:

public static SoundManager Instance = null; 
public AudioClip goalBloop; 
public AudioClip lossBuzz; 
public AudioClip hitPaddleBloop; 
public AudioClip winSound; 
public AudioClip wallBloop; 
private AudioSource soundEffectAudio; 

// 用于初始化 
void Start () { 
    if(Instance == null) { 
        Instance = this; 
    } else if (Instance != this) { 
        Destroy(gameObject); 
    } 

    // 修复:获取单个AudioSource组件
    soundEffectAudio = GetComponent<AudioSource>();
}

方式2:获取多个AudioSource组件数组

如果你的GameObject上有多个AudioSource,需要先声明sources数组变量,再通过GetComponents<AudioSource>()获取所有组件:

public static SoundManager Instance = null; 
public AudioClip goalBloop; 
public AudioClip lossBuzz; 
public AudioClip hitPaddleBloop; 
public AudioClip winSound; 
public AudioClip wallBloop; 
private AudioSource soundEffectAudio; 

// 用于初始化 
void Start () { 
    if(Instance == null) { 
        Instance = this; 
    } else if (Instance != this) { 
        Destroy(gameObject); 
    } 

    // 修复:先声明数组变量,再获取所有AudioSource
    AudioSource[] sources = GetComponents<AudioSource>();
    // 按需选择其中一个赋值给soundEffectAudio,比如取第一个
    soundEffectAudio = sources[0];
}

额外提示

  • 确保你的SoundManager GameObject上已经添加了AudioSource组件,否则GetComponent会返回null,后续播放音效会报错。
  • Unity 2017.3.0f3的组件获取API和后续版本兼容,以上写法可以正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:35:35