Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

sending and recieving messages in scripts?

Discussion in 'Scripting' started by CodyDMartin, Aug 23, 2015.

  1. CodyDMartin

    CodyDMartin

    Joined:
    Jun 14, 2015
    Posts:
    3
    Hi I am new to c# and I've been having trouble knowing how to send a message from one script and receiving it in another script I am making. My main hope was to have a raycast that sends a message to the object it hit, so that i could make a raycast gun in a sense. I can use raycasts fine and everything else i can do just any help on the message sending or receiving would be great or even another way of doing it.
     
  2. Lorinthio

    Lorinthio

    Joined:
    Aug 7, 2015
    Posts:
    39
    Depends on how you're wanting to handle the messages honestly.

    One way would be switch/case handling in a script. For example, you have a class called Player, attached it to an object. On raycast you hit the object, check if it has the Player component, and call the message method.

    object.GetComponent<Player>().message("Hit");

    In the Player class, under the message method... you would have something as the following...

    Code (CSharp):
    1. void message(string action){
    2. case "Hit":
    3.     //Do hit action;
    4. case "Miss":
    5.     //Do miss action
    6. case "Open":
    7.     //Do open action
    8. }
    This is a raw code example for you to trigger events by strings or messages. I'm not sure how else to answer your message, without going into your own situational logic in your code as in if the shooter of the raycast is an attacker, and your target is a living entity, then call the player.attack() as opposed to player.message("Attack"). What you need to figure out is if you want to go with the switch/case or the method based(more optimised/better coding result).