As discussed in the comments, since the thing which you want to achieve is to create a reusable dialog with buttons which will trigger different functions from other classes which are part of the current Scene
, the way you can achieve this is by using UnityAction
.
Let's say you have a Dialog
script with a function OnButtonClickedAction
:
public class Dialog : MonoBehaviour {
public static UnityAction OnButtonClickedAction;
public void OnButtonClicked(){
if (OnButtonClickedAction != null){
OnButtonClickedAction.Invoke();
}
}
}
And in your Scene
's where you want to show this dialog you should have a class which subscribes for those actions:
public class Script : MonoBehaviour {
private void OnEnable() {
Dialog.OnButtonClickedAction += CodeToRunOnButtonClick;
}
private void OnDisable(){
Dialog.OnButtonClickedAction += CodeToRunOnButtonClick;
}
private void CodeToRunOnButtonClick(){
// code
}
}
And by doing this, your Dialog
is reusable between different Scene
's.
There is another way using Singleton pattern, by calling a function from a GameObject
which doesn't get destroyed during changing Scene
's. Let's say you have a GameManager
class which doesn't get destroyed so you can call something like that from your Dialog
script.
public class Dialog : MonoBehaviour {
public void OnButtonClicked(){
GameManager.Instance.CodeToRunOnButtonClick();
}
}
I prefer the first version, but it's up to you.
Here is the hierarchy inside Unity Editor:
As you can see there is a Dialog
object inside the Scene
which has the Dialog
script attached to it and on Button
's onClick
event, Dialog
's OnButtonClicked
method is assigned.
And by adding Script
object to every scene where you want to show this Dialog/WinPopUp you can listen for that action like this:
If you have more than one button, you can easily extend the UnityAction
to support adding let's say an id to every Button
(buttonId
) and pass it like that:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…