how do I call a function from another script, when Raycast Hits?
Hello, just wondering if somebody can point me in the right direction.
I have this C# Script:
public class Raycasty : MonoBehaviour {
public float InteractDistance = 30;
//public DisappearScript disappearScript;
public void Update ()
{
Ray ray = new Ray (Camera.main.transform.position, Camera.main.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, InteractDistance))
{
Debug.DrawLine(Camera.main.transform.position, transform.position + transform.forward * InteractDistance, Color.green);
if (Input.GetButtonDown ("click"))
{
if (hit.collider.tag == "Cube")
{
Destroy (hit.collider.gameObject);
//disappearScript.GetComponent<DisappearScript>().Disappear();
}
}
}
}
}
This script works as expected. But, instead of : Destroy (hit.collider.gameObject); I want to call a "Disappear" function from another script. (commented out lines)
What am I doing wrong?
Any help is really appreciated, Thanks in advance!
Answer by Paricus · Feb 08, 2017 at 06:34 PM
https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
use hit.SendMessage("NameOfFunction");
Hello, thank you! I'm not familiar with this method. unfortunately I keep getting errors.
if (hit.collider.tag == "Cube")
{ hit.Send$$anonymous$$essage("Disappear"); }
Error says "UnityEngine.RaycastHit does not contain a definition for "Send$$anonymous$$essage" ?
That error is thrown if the referenced object doesn't contain the method you're calling use hit.Send$$anonymous$$essage("NameOfFunction", Send$$anonymous$$essageOptions.RequireReceiver) to fix it.
Probably should have mentioned that in the beginning, it kind of goes hand in hand with this function.
No worries! I got it working, thanks again for your help.
Your answer
Follow this Question
Related Questions
Find Script and call function FROM hit.transform 0 Answers
Raycast hit 2 Answers
Highlighting with a Raycast 1 Answer
Tag doesn't work when gameObject is a child of the Main camera? 1 Answer
get array of RaycastAll hits 1 Answer