Search code examples
c#unity-game-engineyieldcoroutineyield-return

My unity IEnumerator method not seems to be work


I have some code: Why Debug.Log inside the IEnumerator method not display anything? And why my method isn`t working?

void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            Debug.Log(true);
            MoveInsideTheShape(speedy);
        }
    }

    public IEnumerator MoveInsideTheShape(float speed)
    {
        speed = 1 / speed;
        float totalLenght = cam.orthographicSize * 2;
        float iterationLenght = totalLenght / speed;

        Debug.Log(cam.orthographicSize); // does not work
}

Solution

  • Even though you are missing a return statement from the MoveInsideTheShape method, adding it would still not solve your issue.

    IEnumerator methods have to be iterated using the StartCoroutine helper method.

    Here's a tested working code.

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            Debug.Log(true);
            StartCoroutine(MoveInsideTheShape(speedy));
        }
    }
    
    public IEnumerator MoveInsideTheShape(float speed)
    {
        speed = 1 / speed;
        float totalLenght = cam.orthographicSize * 2;
        float iterationLenght = totalLenght / speed;
    
        Debug.Log(cam.orthographicSize);
    
        yield return null;
    }
    

    Helpful links: