Proper way to use coroutines

I’m trying to use an asynchronous coroutine to load level items while other stuff continues, then when loading is done I modify some of the items so they can be used for a specific level. Occasionally, the items fail to be modified, a problem which can make the level impossible to win but is difficult to debug because it happens so rarely. Running the modifications code thousands of times didn’t reproduce the bug, so the problem must be due to the coroutine sometimes failing to load everything before modifications are made despite the fact that the coroutine sets a flag when it finishes and the other code waits for that flag to be set before making modifications. Here’s the code I’m using for the coroutine (the first function sets it running and the second is the coroutine itself). Am I doing something wrong?

        function LoadPrefabAsynchronously(Prefab:GameObject, PrefabPos:Vector3, PrefabRot:Quaternion, Parent:GameObject)
        {
            LPAFinished=0;
            LPAprefab = Prefab; LPAprefabPos = PrefabPos; LPAprefabRot = PrefabRot;LPAParent = Parent;
            StartCoroutine("LoadPrefabAsynchronouslyCoRoutine");

        }

        //co-routine for above
        // Prefab to load needs to be in LPAprefab
        // Parents it to LPAParent GO
        // "Returns" instantiated GO by placing it in LPAprefabGO
        function LoadPrefabAsynchronouslyCoRoutine()
        {      
            yield WaitForEndOfFrame();
            LPAprefabGO  = Instantiate(LPAprefab,LPAprefabPos, LPAprefabRot);
            LPAprefabGO.transform.parent = LPAParent.transform;
            LPAFinished=1;
        }

Anyone know? This is a frustrating bug given how difficult it is to reproduce and hence diagnose.

Try the scripting part of the forum. But since you are using UnityScript, it may be harder for people to help you.

As far as coroutines go though, if you need to wait for a coroutine to finish, you could just yield the coroutine so that it sets it to wait for a coroutine to finish before it continues on.

But I’m already having the coroutine set a global variable, LPAFinished, and then the other code waits for that variable to change to 1 before proceeding. The only explanation I can think of is that maybe the stuff being loaded in isn’t actually instantiated for multiple frames and so sometimes it hasn’t actually been placed in the scene before the code tries to change it?

You could add another wait before you set the variable and see if that makes a difference. But I don’t see an issue with the code that you posted, so that’s all I can suggest currently.