0
\$\begingroup\$

So, I'm working on an IEnumerator() that is called to spawn objects in a fountain style (kinda flying up and out and landing at a random spot nearby). I feel like I had this working for a hot minute, but I don't know what I've done to screw it up. It's POSSIBLE that it was only working when it was a void() instead, but I need to function to be a coroutine (or otherwise run on something other than the main thread).

So, I have this. It works, except you only see the spawned objects after they've landed and the function has exited.

public IEnumerator ThrowFountain()
{
    System.Random rnd = new 
    System.Random(System.Guid.NewGuid().GetHashCode());
    GameObject _go = Transform.Instantiate(go, t.position, Quaternion.identity);

    _go.transform.parent = t.parent.transform;
    _go.transform.position = t.position + new Vector3(0.0f, 1.5f, 0.0f);
    float trajectoryHeight = rnd.Next(3,6);
    bool closeEnough = false;

    Vector3 startVec = _go.transform.position;
    Vector3 newVec = new Vector3 (t.position.x + rnd.Next(-6,6), t.position.y, t.position.z + rnd.Next(-6,6));

    float distance = Vector3.Distance(startVec, newVec);
    float startTime = Time.timeSinceLevelLoad;
    float evalTime = startTime;


    while (!closeEnough)
    {
        float distCovered = (evalTime - startTime) * speed;
        float fracJourney = distCovered / distance;
        Vector3 currPos = Vector3.Lerp(startVec, newVec, fracJourney);
        currPos.y += trajectoryHeight * Mathf.Sin(Mathf.Clamp01(distCovered) * Mathf.PI);

        _go.transform.position = currPos;
        closeEnough = V3Close(currPos, newVec, 1.0f);
        Debug.Log("Time: " + Time.time.ToString());
        evalTime += Time.deltaTime;
    }

    yield return new WaitForEndOfFrame();
}

V3Close() just returns a bool so long as none of the vectors of the object and it's target are more than 1.0f apart. That part seems to be working as well. Not sure if maybe the IEnumerator loop won't draw the object (because it's not on the main thread or for some other reason)?

\$\endgroup\$
0
\$\begingroup\$

This seems to happen to me a lot - post the question on SE, figure it out 30-60 minutes later. This one was after a few hours. The answer is simple:

Add a yield return null to the end of the while() loop. Now I just need to get my math better for the arc and such.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.