How to activate "OnTriggerEnter" when Player ray hits an object collider?
I have made a script for the Player to have a ray on the center of the camera 3 unit long, how can I raise the OnTriggerEnter function when my ray hits an object collider?
Answer by chillersanim · Oct 06, 2016 at 04:40 PM
You shouldn't call the OnTriggerEnter method yourself, as this is a special method for when a trigger event happens.
If you want to execute the code on the player script, which you have in OnTriggerEnter, you should move that code to a seperate method, and call this method from the ray cast.
If you want to execute code on the object your raycast hit (not the player), then it needs a defined script you can search for, with a defined public method, which does whatever it should do when the object is hit.
Example:
/// <summary>
/// The players class
/// </summary>
public class Player : MonoBehaviour
{
void Update() // Or FixedUpdate() for physical stuf
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
if (hit.collider != null)
{
// Find the hit reciver (if existant) and call the method
var hitReciver = hit.collider.gameObject.GetComponent<HitReciver>();
if (hitReciver != null)
{
hitReciver.OnRayHit();
}
}
}
}
}
/// <summary>
/// The component that needs to be added to the other objects which need a callback on a ray hit.
/// </summary>
public class HitReciver : MonoBehaviour
{
// Called when the player ray hits this object
public void OnRayHit
{
// Whatever you want to happen on a ray hit...
}
}
Greetings
Chillersanim
What if you want to call the method when the raycast ENTERS the collider? I mean, only once?
Your answer
![](https://koobas.hobune.stream/wayback/20220612094121im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
What is the best way to script a trigger that moves a object from point a to point b in C# (unity 5) 0 Answers
Croutch Player when Trigger enter 0 Answers
PLAYER NOT ACTIVATING TRIGGER WHEN ON TOP OF THE COLLIDER! IS THIS A BUG 0 Answers
My trigger won't activate the UI when the player collides with it. 0 Answers
How do I hide/show an object, when the player enters a trigger zone? 2 Answers