Take the 2-minute tour ×

I'm experiencing the following:

Foo myFoo = new Foo();   // Init a Foo, right?
myFoo.bar = 5;           // property assigned
Debug.Log(myFoo.bar);    // Properly traces the value 5 or whatever to the console
Debug.Log(myFoo);        // Traces "null" to the console..... WTF?!?!?!?

This is happening using C# in MonoDevelop in conjunction with Unity 3.5. In this case, Foo is subclassing Object, and to my knowledge, isn't dynamic. Is there some nuance of C# I'm missing here, because this is extremely weird behavior, and I have never seen it in ActionScript 3 or Objective-C. It's odd to me that the runtime is able to access/assign a property of a variable that simultaneously traces "null", without even throwing a NullException or some kind of error. Any ideas on why this might be occurring would be a huge help. Thanks in advance.

share|improve this question
Where to you get the Debug.Log method you use? System.Diagnostics.Debug has no such method. Maybe it is mono specific? Also - I tried this using Debug.WriteLine() and it works as expected, outputting the type name of Foo a and 5 for the property. This was on .Net not Mono so I'm guessing the behaviour comes down to framework in some way - it isn't c# at least. –  David Hall Jul 9 '12 at 16:08
We need the Foo class to answer this question, at least I do, to explain what is actually going on. You do understand that Debug.Log(myFoo); convert the Foo class to a string right? So at most it would print out System.Object you should also post the link to the documentation for Debug.Log otherwise we cannot help you. –  Ramhound Jul 9 '12 at 16:08
Debug.Log is part of Unity's framework: docs.unity3d.com/Documentation/ScriptReference/Debug.Log.html It's basically like Console.Writeline(); It takes an argument of type object and I'm assuming handles the rest internally. I've passed many object types to this function before, and it always traces out the type passed, unless it's primitive, in which case it traces the value itself. I'll try to post some code in a bit, it's a bit of a complicated set of classes, but the Foo in question is really just a simple data model. –  p_atNextUp Jul 9 '12 at 16:14
Is there an override for the ToString() method of Object on class Foo? If so, is there a chance that implementation is doing something a bit out of the ordinary that would cause it to return null? –  David W Jul 9 '12 at 18:45
Check if the ToString() is not returnin "null" for the Foo object. –  MBen Jul 9 '12 at 23:12
add comment

1 Answer

Are you subclassing System.Object, or UnityEngine.Object?

UnityEngine.Object is a special class used to represent Unity engine objects that are backed by native representations. You shouldn't derive from it.

share|improve this answer
add comment

Your Answer


