AudioSource 附加按钮在另一个场景中不起作用

问题描述

public AudioSource menumusic;
public Button SoundButton;
public Sprite Soundoff;
public Sprite SoundOn;
bool isClicked = true;
private void Awake()
{
    DontDestroyOnLoad(this.gameObject);
    SoundButton.image.sprite = SoundOn;
}
// Start is called before the first frame update
void Start()
{
    menumusic = GetComponent<AudioSource>();                    
}

// Update is called once per frame
void Update()
{
    
    SoundButton.onClick.AddListener(BtnOnClick);
}
void BtnOnClick()
{
    
    changeState();
}
private void changeState()
{
    isClicked = !isClicked;
    if(isClicked)
        {
        SoundButton.image.sprite = SoundOn;
        menumusic.Play();
        }
    else
    {
        SoundButton.image.sprite = Soundoff;
        menumusic.Stop();
    }
       
}

我有这样的脚本而且我在菜单场景中使用但是当我用其他按钮切换到游戏场景时,这个脚本在那里工作,除了他找不到声音按钮,我如何从另一个场景链接到声音按钮我也应该创建相同的游戏场景吗? ,抱歉,我是 unity 的新手。

解决方法

看起来您正在检查器中设置对“SoundButton”对象的引用。当您更改场景时,您需要更新此脚本上的引用以引用新按钮。

有很多方法可以做到这一点。你可以用“soundButton”来标记 soundButtons。 然后,无论您在何处加载新场景,都可以通过搜索标签来更新参考。

SoundButton = GameObject.FindObjectWithTag("soundButton").GetComponent<Button>();

也可以在每个声音按钮上放置一个 SoundButton 脚本。然后它可以引用一个静态 SoundManager 对象,并告诉它在单击时打开或关闭声音。这可能是一种更简洁的方法。

另请注意:您正在向 Update() 中的 soundButton 添加一个侦听器(即每一帧)。这是不必要的。在 Start() 中添加一次监听器,或者当您更改 Scenes 时,它会在每次单击按钮时触发该事件。这个过程不需要使用Update()。

如果还是不行,你也可以在使用前先检查一下变量,如果是null,再获取引用:

if(soundButton == null)
{
    SoundButton = GameObject.FindObjectWithTag("soundButton").GetComponent<Button>();
}