Is there any way in which you can trigger functions of an object when detected with a Raycast2d in Unity?

0

I'm trying to operate a function of an object by detecting by raycast, that is, I press the mouse on the screen, create a Raycast2D and detect if it collides with a 2D object, and if that happens, trigger a function inside that object, for example: change_color (), destroy_object (), etc. Thank you very much for your attention.

    
asked by javier_lema 04.08.2018 в 03:06
source

1 answer

0

If that is possible, once you have stored the Raycast information you can use SendMessage("nombre_funcion") to execute a function that is in the Script of the object with which you have collided. Be careful, you will have to check first that the object with which your Raycast has collided is the object that contains that function you want to call, since otherwise it will send you an Exception.

If you share the code where you implement your Raycast2D, I could give you a more concrete example, but here is an example of general use:

//Al hacer click primario instanciamos un Raycast2D
if(Input.GetKey(KeyCode.Mouse0)){

    //La información del collider que ha entrado en colisión con el Raycast2D se almacena en la variable hit
    RaycastHit2D hit = Physics2D.Raycast(transform.position , Vector2.right);

    //Si el Raycast2D colisiona con un gameobject cuyo Tag sea Enemigo, llamamos a una función que se encuentra dentro de su Script
    if (hit != null && hit.transform.gameObject.tag == "Enemigo"){
        hit.transform.gameObject.SendMessage("cambiar_color");
    }
}
    
answered by 06.08.2018 / 14:10
source