Hi, I am trying to pass an arbitrary function to be called inside a fixed function, which itself is called using delegate keyword through the AddListener function of InputField.onEndEdit event.
I am new to delegates, but as I understand, I need to create a new delegate to do this, and I’m getting bit tangled up, having read a few delegate articles still stuck.
Currently, code compiles but get ArgumentExceptionerror:
Value does not fall within the expected range.
CharacterController3D..ctor ()
Where the script name is CharacterController3D.cs - I don’t know what ctor means or if it is relevant.
Line generating this error is: Del marySuccess = question.MarySuccess;
End Objective: When player inputs an answer to an arbitrary question posed when player triggers it in game, the ProcessAnswer function will call a customised function processing correct answer to each question, ie each question will have different function dealing with a correct answer response. Likewise, the ProcessAnswer function will call different custom function for that question if player gives wrong answer and so on.
Below is the ProcessAnswer function, with arbitrary delegate passed to it delegate1, which in following code block runs when correct answer is given:
private void ProcessAnswer (InputField input, string answer, float clockStart, Del delegate1)
{
if (String.Equals(answer, input.text.Trim(), StringComparison.OrdinalIgnoreCase)) // trim trailing spaces, accept any case in letters typed
{
countdownTimer.enabled = false; // stops timer
float timePoints = Mathf.Round(2000/(clockStart - countdownTimer.TimeStoppedTenthsSecond()));
delegate1();
}
else ....
Above function is called in same script by:
string answer = "grace";
clockStart = 90f;
inputField.onEndEdit.AddListener(delegate { ProcessAnswer(inputField, answer, clockStart, marySuccess); });
where marySuccess is the delegate parameter in this case, defined by:
private delegate void Del(); // declare a delegate function wrapper with no parameters and returns void.
Del marySuccess = question.MarySuccess;
Still in this same script, question here is declared as a static instance of a separate component script on same object. I understood have to make it static for the delegate to reference it, didn’t work as non-static anyway:
private static Questions question;
and initialised in the Awake method, all in same script:
question = this.GetComponent<Questions>();
Any suggestions very grateful, thanks! I saw @Bunny83 gave great answer to delegate question not sure how difficult this is or if I’m on wrong track anyway.
Are you sure: -
– Helliumquestion.MarySuccessis a function? -question.MarySuccess's signature isvoid MarySuccess()?Hi, yes
– Will_Croxfordpublic void MarySuccess()is function in theQuestionsclass thanks