2D Toolkit Forum
2D Toolkit => Support => Topic started by: scottp100 on April 18, 2013, 07:24:50 pm
-
I am getting a NullReferenceException on iOS when setting color of a sprite in Start. I do not get this error in the editor (presumably because of the #if UNITY_EDITOR if statements in tk2dBaseSprite checking for null). My script execution order has tk2dBaseSprite set before default time (along with other tk2d classes).
I have a gameObject with a C# script called LevelManager, and it is setting the color of a different a sprite gameObject in it's Start() function.
The sprite causing the exception is just a plain static sprite (not multi-atlas). I'm using the latest version of the 2d toolkit 1.92 + patch 1.
Any ideas what could be happening?
NullReferenceException: A null value was found where an object instance was required.
at tk2dBaseSprite.SetColors (UnityEngine.Color32[] dest) [0x0006b] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dBaseSprite.cs:419
at tk2dSprite.UpdateColorsImpl () [0x00000] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dSprite.cs:145
at tk2dSprite.UpdateColors () [0x00000] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dSprite.cs:133
at tk2dBaseSprite.set_color (Color value) [0x0001e] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dBaseSprite.cs:101
at SpellGem.SetDrawStage () [0x00011] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/AbracatapraAssets/Scripts/GameScripts/Items/SpellGem/SpellGem.cs:153
at DrawLevelManager.SpawnNextShape () [0x0006b] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/AbracatapraAssets/Scripts/GameScripts/Singletons/DrawLevelManager.cs:93
at DrawLevelManager.Start () [0x0008b] in /Users/scottp/Documents/Unity/Abracatapra/AbracatapraWork/Assets/AbracatapraAssets/Scripts/GameScripts/Singletons/DrawLevelManager.cs:80
-
I think I've found a case where this could happen, when you instantiate a prefab, and the prefab is disabled by default - Awake never gets called on the sprite, and the sprite never gets initialized. This might be what you're experiencing.
Please replace these lines:
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (mesh == null || meshColors == null || meshColors.Length == 0)
return;
#endif
with
if (mesh == null || meshColors == null || meshColors.Length == 0)
Build();
and it should fix your issue. This should be fixed in tk2d 2.0.
-
You exactly identified the problem case that I had!
In my prefab, the sprite was disabled. In my start function, I enabled the sprite and immediately set the color. I will change my code so that that the sprite is enabled in my prefab, and I can disable it in my start function when I don't need it. Whew, thank you!