Search Unity

Calling function XXXX with no parameters but the function requires 1.

Discussion in 'Scripting' started by BigB, Dec 8, 2021.

  1. BigB

    BigB

    Joined:
    Oct 16, 2008
    Posts:
    672
    Hi,

    I'm converting some code from JS to C#, and I'm having an issue with the SendMessage function.

    I have a class, let's call it myClass located in the myclass.cs file.

    In that class I have this function :

    public void setObjective(int id)

    Now from another script I'm calling this function, like this :

    Object.SendMessage("setObjective", 0);

    and I get at runtime :

    Failed to call function setObjective of class ObjectiveID
    Calling function setObjective with no parameters but the function requires 1.

    If I remove the parameter from the function, then all is fine, but I want to send a parameter to the function.
    How can I do this?

    Thanks!
     
  2. It is very bad naming any class you have "Object" or any other generic C# class name. You will mix up the namespaces and will call things on objects, classes you don't intend. I recommend to rename your class something meaningful.
    Second:
    Object.SendMessage
    suggest you call it as a static method and not on a game object. You need to call
    SendMessage
    on an instantiated object.

    See the simple example in the documentation here. If you want to send message on another game object, first you need to obtain a reference to it, like through dragging and dropping in the inspector or
    FindObjectOfType
    or whatever.
     
    Bunny83 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Everything that @Lurking-Ninja says above is spot-on... and also while you're refactoring it might be an idea to use interfaces in order to get rid of SendMessage() entirely, since it is subject to misspelling the method names and subsequent failure, whereas interfaces are compiler-checked.

    Using Interfaces in Unity3D:

    https://forum.unity.com/threads/how...rereceiver-error-message.920801/#post-6028457

    https://forum.unity.com/threads/manager-classes.965609/#post-6286820

    Check Youtube for other tutorials about interfaces and working in Unity3D. It's a pretty powerful combination.
     
    Bunny83 and StarManta like this.
  4. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    691
    I rarely use SendMessage, I just get a script reference and call the function directly. Though it can be handy in some situations.
     
    Bunny83 likes this.