Setting button.onClick.AddListener saids: InvalidCastException: Cannot cast from source type to destination type.
I'm trying to make something common static class with js named MessageBox. I'm just gonna want to passing a function(callback) as second parameter and attach it into button.onClick.AddListener.
This is the code:
import UnityEngine.UI;
public static class MessageBox extends MonoBehaviour {
private var ui: GameObject = GameObject.Find('UI');
private var messageBox: GameObject = ui.transform.GetChild(0).gameObject;
private var messageBoxText: GameObject = messageBox.transform.GetChild(0).gameObject;
private var messageBoxOk: GameObject = messageBox.transform.GetChild(1).gameObject;
public function Show(text: String, onClickHandler: Function) {
messageBox.SetActive(true);
messageBoxText.GetComponent.<Text>().text = text;
messageBoxOk.GetComponent.<Button>().onClick.AddListener(onClickHandler);
}
}
As you can see, variable onClickHandler is a function, and it's used for AddListener on button to catch click event.
This is the code where execute MessageBox.Show:
function Update() {
if(Input.GetKeyDown('space')) {
MessageBox.Show('Helloworld', function() {
Debug.Log('Pressed OK');
});
}
}
I'm passing seconds parameter as function, and it just print some text on the console. But when it runs, it fails with this error message:
InvalidCastException: Cannot cast from source type to destination type.
MessageBox.Show (System.String text, ICallable onClickHandler) (at Assets/Scripts/Global/MessageBox.js:12)
Player.Update () (at Assets/Scripts/Player.js:15)
If I add a function inside of MessageBox class and using on button.onClick.AddListener, it's working without any error. Error is only occurs when I passing a function from another script, Player.js as above simple script that checks space pressed and show MessageBox.
I tried everything I can, not using anonymous function, removing type on onClickHandler to accept any kind of data nothing seems to be work.
I think the syntax is right, but why it doesn't work?
Answer by modernator24 · Apr 16, 2017 at 11:24 AM
I solved this with specify as function():void, not Function. I'm quite confusing about data types in Unity JavaScript, I have to read the documentation.
Anyway if someone faced same problem of this, this is the code what am I did:
public function Show(text: String, onClickHandler: function():void) {
messageBox.SetActive(true);
messageBoxText.GetComponent.<Text>().text = text;
messageBoxOk.GetComponent.<Button>().onClick.AddListener(onClickHandler);
}
And this is caller:
MessageBox.Show('Helloworld', function() {
console.log('Pressed OK');
});
Your answer
Follow this Question
Related Questions
How can I generate and setup buttons via code 1 Answer
Add listener to multiple buttons 2 Answers
UI Button OnClick Only Works the First Time 2 Answers
Assigning different buttons click events to the same function with a parameter dynamically 1 Answer
How to use Button.OnClick.AddListener? 2 Answers