Invoke access private function on another class

  • Editor version: 2023.2.15f1

Invoke in class TestB shall not access private function TargetFunc in the super class TestA.
But it is compiled and executed accessing the private function.

image

Considering behavior of Invoke, it shall link to TargetFunc with parameter and report warning message as there are parameter.
But it link to the private function which shall not be accessed as it is a private function.

/// === TestA.cs ===
...
public class TestA : MonoBehaviour
{
    public void TargetFunc(int param) {
        Debug.Log("calling TargetFunc with param");
    }
    private void TargetFunc() {
        Debug.Log("calling TargetFunc without param");
    }
}

/// === TestB.cs ===
...
public class TestB : TestA
{
    void Start()
    {
        Invoke(nameof(TargetFunc), 1.0f);
    }
}
1 Like

Invoke can and will call private methods as they are called from outside the class itself, from the C++ side just like any other message function (Start, Update, …). It calls the method via a string name and does not support parameters. The “nameof” operator does only give you access to the string. It has no actual connection to any method. It’s just a way to avoid typing errors and get refactoring support.

Since what you do makes no sense, you can not call a method with parameters via Invoke and you should avoid having overloaded method names in the first place, especially when you plan to call them via Invoke. So there is no bug, you just doing things you shouldn’t do.

2 Likes