- Home /
Instance of c# class can't be null checked from javascript
Hey guys,
I have a weired problem here.
I wrote a model class in C# named Pilot. Creating instances of that class and use these instances works fine both from C# and Javascript scripts. But if I try to check if an instance of my class is null, I always get true from Javascript no matter if it is instantiated or not.
I just moved my Pilot model class from Javascript to C#. The check worked fine when it was Javascript. Is there an issue with checking C# instances for null in Javascript? I am doing the checks in a method which is called from the OnGUI() method.
My code looks as follows:
var isHovered:boolean = hoveredPilot!=null?pilot.getUserName()==hoveredPilot.getUserName():false;
isHovered is always false because hoveredPilot!=null always evaluates to false. I did some further checks:
var pilot1:Pilot = null;
var pilot2:Pilot = new Pilot("JohnDoe");
Debug.Log(pilot1==null); ( => prints "True" to the console)
Debug.Log(pilot2==null); ( => prints "True" to the console)
Debug.Log(pilot2.getUserName()); ( => prints "JohnDoe" to the console)
When I do
Debug.Log(pilot1.getUserName());
the program crashes with a null reference error message (as expected).
What really puzzles me is why the null check for pilot2 returns true but on the next line I can retrieve the user name variable from the object.
Any suggestions what I am doing wrong? How should I check if an instance of the Pilot class is null?
Thanks in advance, Henrik
Your answer
