How to use SendMessage?

Hello,

I have 2 scripts. One is attached to a cube, and the other to my player. I’m raycasting from the player and sending the info to the script on the cube.

Player code:

    // Update is called once per frame
    void Update () {
 
               
                Vector3 fwd = transform.TransformDirection(Vector3.forward);
               
                RaycastHit hit;
               
                playerpos = transform.position;
               
                if(Physics.Raycast(playerpos, fwd, out hit,100f)){
                    this.gameObject.SendMessage("receive",hit.transform);       
                }
        }

and the script on the cube:

        void receive(Transform coll){
            if(coll == this.transform){
                DisplayThis = true;
            }else{
                DisplayThis = false;
            }
        }

but when i hit the cube with my raycast, I get the error:

What does that mean that it has no receiver?

How to use SendMessage? Don’t use SendMessage. It’s a very bad form of code and just about against every good design pattern.

If you know the type of script on the Cube, do GetComponent. If you don’t know the type and many can have the “receive” method, implement an interface and do GetComponent of that interface.

it means your object you are sending the message to doesn’t have the function you are trying to call. your send message statement is wrong… you are sending the message to yourself… you want:

hit.gameObject.SendMessage("recieve", hit.transform);

I get this error:

I’m not familiar with raycasting at all, so I’m not really sure why a hit doesn’t have a gameObject

I second this, it’s performance is terrible and it is incredibly hard to debug. I would avoid it at all costs.

As for the error mesage, novashot explained it nicely.

I’m afraid that for my level of knowledge of programming, SendMessage will have to do.

And after using Novashot’s code I got that new error message.

Ah, I had to use hit.transform.gameObject.SendMessage(“receive”, hit.transform);

thank you all

Try this:

class SomeClass : MonoBehaviour
{
    public void receive()
    {
        DisplayThis = true;
    }
}

class RayCaster : MonoBehaviour
{
    void Update()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        RaycastHit hit;
        playerpos = transform.position;

        if (Physics.Raycast(playerpos, fwd, out hit, 100f))
        {
            hit.transform.GetComponent<SomeClass>().receive();
        }
    }
}
2 Likes