Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Reuse game objects across different scenes on inspector: button On Click()

Discussion in 'Scripting' started by Jorhoto, Nov 18, 2019.

  1. Jorhoto

    Jorhoto

    Joined:
    May 7, 2019
    Posts:
    99
    So I make a monobehavior containing a function like:
    PlaySfx (string soundName){//play the sound }

    I create a game object implementing the script, I add an audiosource component to it and use the DontDestroyOnLoad

    In the scene this game object is created, I assign it to a button script On Click(), so I can trigger a click sound each time that button is clicked.

    If I move to another scene, If I try to set up another button script On Click() to trigger another sound, I can't because the gameobject isn't in the scene.


    Please, any suggestion on how to do it?
     

    Attached Files:

  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    You cant reference objects inbetween scenes using game object inspector. You should do it directly. Instead, make small script what attaches a event handler to the button clikc event internally via code and, when button is clicked, invoke your PlaySfx from that event handler
     
  3. Jorhoto

    Jorhoto

    Joined:
    May 7, 2019
    Posts:
    99
    What about scriptable objects with the functions? They persist along different scenes.
    Would you recommend doing it that way?
     
  4. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748