Thursday, January 24, 2013

I Feel So Dirty

I wanted to make note here of a new milestone in cheap hacks, which coming from me is saying a lot. So, apparently, you can't destroy an instantiated prefab from within a coroutine. This poor S.O.B. had the same problem I was facing, and nobody had a good answer for him. I fully grant that this could be just a knowledge failure on my part, but I have not been able to determine why Destroy(thisThing) works perfectly well from inside a standard function, but fails silently from inside a coroutine, even though the code after it executes perfectly well. I'm sure one could track this down to some intersection of Unity's particular object system, the way its prefabs work, and its use of C#'s IEnumerator returning functions as the basis for coroutines (for instance, I suspect it might work fine in Javascript), but I don't think I'm that someone, at least not this evening. When I find someone else has encountered the issue that's blocking me, and has appealed to the Greater Internet about it, and has received no succor, I tip my hat to that brave pioneer and then I reach for my hacking axe.

So, when you need an object destroyed at an exact point in a coroutine, but you can't do it from within that coroutine, what do you do? If you're me, you make a new C# script called cloneKiller, and when you instantiate the prefab you also add the script to the clone with

ck = clone.AddComponent<cloneKiller>();

cloneKiller contains a single function, called KillMe:

public void KillMe()
if (gameObject!=null)

and in the middle of the coroutine, I simply call


 I know, that's absolutely ridiculous, and I should be ashamed of myself, but it works. . . actually I'm going to go ahead and make that statement the official motto of this blog.

No comments:

Post a Comment