简体   繁体   中英

“Class, struct, or interface method must have a return type” Even when function is set to void

I'm essentially trying to make a UI object fade in using Unity 2D's UI library. The function fadeIn() starts a coroutine FadeCanvasGroup that slowly changes the alpha of the object using lerping in order to fade it in, the fadeOut(); function simply reverses this. However, I keep getting thrown "Class, struct, or interface method must have a return type" errors when calling fadeIn(), which confuses me, considering that fadeIn() and fadeOut() both are void functions.

I have changed functions to public and private, added and removed voids, and attempted to start the coroutine without the function, all of which met with failure. As well, when attaching the function to a button using Unity's engine, it works fine, but when called through script, it fails.

//The element in question being defined(And later set using the engine)

public CanvasGroup uiElement;

//The coroutine in question

 private IEnumerator FadeCanvasGroup(CanvasGroup cg, float start, float end, 
 float lerpTime = 2f)
{

    float timeStartedLerping = Time.time;
    float timeSinceStarted = Time.time - timeStartedLerping;
    float percentageComplete = timeSinceStarted / lerpTime;
    while (true)
    {
        timeSinceStarted = Time.time - timeStartedLerping;
        percentageComplete = timeSinceStarted / lerpTime;

        float currentValue = Mathf.Lerp(start, end, percentageComplete);

        cg.alpha = currentValue;

        if (percentageComplete >= 1)
        {
            break;
        }

        yield return null;
    }
    print("done");
}

//The functions to fade in and out

    public void fadeIn()
    {
        StartCoroutine(FadeCanvasGroup(uiElement, uiElement.alpha, 1));
    }
    public void fadeOut()
    {
        StartCoroutine(FadeCanvasGroup(uiElement, uiElement.alpha, 0));
    }

fadeIn();

The fadeIn(); being called at the end should just execute, but the earlier described error is taking place. Thanks for anyone's time who wishes to help with this.

Without a good Minimal, Reproducible Example , it's impossible to give you the exact fixed code. However…

The way Unity3d uses C#, the error messages are sometimes not crystal clear. But, you're getting that error because coroutine methods must return IEnumerable .

See the "fade" example in the Unity3d documentation for an illustration of how to do this correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM