invoke couldn't be called

Hi there. I’m very new to unity and c#, and the forums, so I’m sorry if I’ve done something wrong ahah.

Anyway, I’ve been having issues with using invoke. I’m trying to create a very simple program in which an apple ‘ripens’ on a tree, and then the player can collect that apple. The apple get ripened in a method by switching the number of apples of the tree to 1. This method is called using the invoke function on awake, after a ten second period. Then, it should again be invoked after the user has collected the apple. This is in a different script to the ‘ripening’ of the apple.

However, when this second invoke command is returning the error message:
“Trying to Invoke method: appleRipe.scriptRipe.AppleRipe couldn’t be called.”

Again, I’m really new to this so I’m sorry for my inevitable stupid mistakes. Here is the code for the method which causes the problem:

public void Update()
    {
        if(nearApple == true)
        {
            if(scriptRipe.numberOfApples >= 1)
            {
                if(Input.GetKeyDown(KeyCode.Z))
                {
                    scriptRipe.numberOfApples = scriptRipe.numberOfApples - 1;
                    applecollectplayer.playerApples = applecollectplayer.playerApples + 1;
                   
                    scriptRipe.Invoke("scriptRipe.AppleRipe", scriptRipe.ripeTime);
                }
            }
        }  
    }

This is the method it’s attempting to call:

public void AppleRipe()
    {
        numberOfApples = 1;
    }

Don’t put the name of your variable into the Invoke call. All you need is:scriptRipe.Invoke("AppleRipe", scriptRipe.ripeTime);

This kind of error demonstrates why it is a bad idea to use Invoke in Unity. Coroutines are much more flexible and come with compile-time error checking that would prevent this issue.

Thanks so much. I’ll have a look into coroutines.

Calling Invoke with a string is a mistake but there’s nothing wrong with using Invoke if you write it like this:

Invoke(nameof(YourMethodName), delay);

I know this is old but this post comes up when searching.

2 Likes