I’m having problems using Delegates with Unity.
I’m using them with Queues to create a method for my threads to communicate with the main Unity thread. (Based on this How do I invoke functions on the main thread? - Questions & Answers - Unity Discussions)
Since we cant make Unity API calls directly in other threads, they need to be Queued and picked up by the main thread.
That was all working fine and everything, but I suddenly started to get my Unity code to just work very strangely.
After 2 days, I’ve figured out that the C# was just stopping at a line of code, with no error message or anything.
First off, it seems that this error, if it happens in a another thread rather than the main thread, just stops the thread and no error message is displayed in the console or anything. So it was quite hard to find.
Eventually, I’ve managed to create a simple test case that shows the problem I’m having. Since I’m quite new to C# and Unity, I would like to know if I’m doing anything wrong, or if its a bug with Unity.
This is the basic test I have that reproduces the problem:
delegate void testdel();
public string testpub = "rrr";
void Start() {
string transCmd = "cmd2";
switch (transCmd) {
case "cmd1":
int loginCode2 = 1;
testdel rd3 = delegate () {
Debug.Log("IF1-2:" + loginCode2);
};
rd3();
break;
case "cmd2":
testdel rd2 = delegate () {
Debug.Log("IF2-2:" + testpub);
};
rd2();
break;
}
}
If this is put on the Main Camera in a new project, then it will produce the following error message when run in the console:
Line 21 in Unity (displayed as line 17 here in the post), is the first line in the 2nd case part, ie ‘testdel rd2 = delegate () {’
Its VERY specific to get the error to happen.
It only happens, if its in a CASE statement like this. If you change it to a IF statement rather than a CASE, that does exactly the same as the CASE, then it doesnt happen. Even though the “cmd1” part of the code doesnt get executed, if you remove that ‘delegate’ part, then the error doesnt happen.
The error message, once I got it to output it, seems a bit vague, and doesnt really help at all.
It seems to be because its accessing the public vars.
If I put this exact code into VS 2015, in a console app, then it works fine, even if I compile it against the Unity 3.5 NET framework.
I’m currently on the most current version of Unity: 5.3.0f4
So, my workaround is to use an IF, but thats not really great, and I’m probably more worried that this isnt ‘fixing’ it but possibly just hiding another problem that I may have.
Any ideas?
Thanks, Rob.