-1
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();
    }
       
}

I have script like this And I am using on menu scene but when I switch to game scene with other button , this script works in there to except that he can not find soundbutton , how can I link to sound button from another scene should I create same to game scene too ? , sorry I am new on unity.

1 Answers1

0

It looks like you're setting the reference to your "SoundButton" object in the inspector. When you change scenes, you'll need to update the reference on this script to refer to the new button.

There are many ways to do this. You could just tag the soundButtons with "soundButton". Then, wherever you're loading a new scene, update the reference by searching for the tag.

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

It would also be possible to have a SoundButton script which you place on every sound button. This could then reference a static SoundManager object, and tell it to toggle the sound on or off when clicked. This is probably a cleaner way to do it.

Also note: You're adding a listener to the soundButton in Update() (i.e. every frame). This is unnecessary. Add the listener one time in Start(), or when you change Scenes, and it will trigger the event whenever the button is clicked. There is no need to use Update() for this process.

If it still isn't working, you can also check the variable before using it, and get the reference again if it's null:

if(soundButton == null)
{
    SoundButton = GameObject.FindObjectWithTag("soundButton").GetComponent<Button>();
}
  • Thank you, I manage to pull out something different what I just saw on youtube I just edit audio manager with this script and add another script to button when I switch them on and off – batuhanboran Feb 05 '21 at 11:35