- Home /
Grabbing MonoBehavior object from collision
I have a function that does a Raycast
and when it hits the correct object, it should do something specific with that object. The problem is that I cannot figure out how to get the object that extends from MonoBehavior
.
Here is the code I've been using:
void checkForHit(Vector3 position) {
var ray = Camera.main.ScreenPointToRay(position);
RaycastHit rayHit;
if(Physics.Raycast(ray, out rayHit)) {
if(rayHit.collider.tag == "specificTagToThisObj") {
var monoObj = rayHit.transform.gameObject as MyMonoBehaviour; //This line has an error.
}
}
}
Is this possible to do?
Although c# does have a var
keyword, it's probably better to use explicit type declarations. Your line 2 would be better to be written as Ray ray = ...
for example. It's possible that your code is a mix of c# and Javascript...
This is 100% C#, not mixed with JavaScript.
I also disagree with explicit typing here. In the C# style guide, they say you should use implicit typing if it is obvious what that variable is. In this case, it should be quite obvious that the variable ray
is of the class Ray
.
See http://msdn.microsoft.com/en-us/library/ff926074.aspx under Language Guidelines
-> Implicitly Typed Local Variables
.
Answer by Graham-Dunnett · Sep 04, 2014 at 09:07 AM
MonoBehaviour
basically means a script. In code, scripts are usually referred to as Components
. So, I suspect you actually want to access a component that is on the hit object. So, you probably want:
Wibble w = rayHit.transform.gameObject.GetComponent<Wibble>();
where Wibble
is the name of your script/class.
Your answer
Follow this Question
Related Questions
Multi object detection with single ray cast 1 Answer
Raycast not Detecting Colliders 2 Answers
Why Raycast is not working properly? 0 Answers
Raycast bullet collision problem 1 Answer
Raycast goes through 1 Answer