- Home /
get custom class instance of collider hit by raycast?
I'm sure I've done this before, but I'm not remembering how...
I have a custom class, FooObject. Each FooObject instance has a GameObject and a BoxCollider. I'm casting a ray from one FooObject's GameObject's transfrom.position to see if any other FooObject's BoxCollider is hit.
That's all fine, but I can't remember how to access the FooObject instance of the BoxCollider I hit with my Raycast.
I need something like:
if (hit.collider != null) {FooObject whichFoo = the FooObject that owns the collider we hit}
Any takers? Thanks for your time..!
The GameObject is a member of the FooObject class? And is the collider a component of this game object?
Answer by tingham · Mar 06, 2012 at 12:31 AM
Should be:
// c#
hit.collider.gameObject.GetComponent<FooObject>()
// js
hit.collider.gameObject.GetComponent(FooObject)
FooObject isn't a component of a FooObject. It's its own class, defined like
public class FooObject
{
GameObject myGO;
BoxCollider myCollider;
public FooObject(....arguments)
{
//instantiate stuff
}
}
If each FooObject manages one GameObject, then attaching it as a component (probably inheriting from $$anonymous$$onoBehaviour) really seems like the way to go. It'll enforce that one-to-one relationship and make sure that each can access the other.
If there's some pressing reason you can't do that, I guess you're left with the option of creating and maintaining some easily accessible data structure that maps each GameObject to its respective FooObject, but... ew.
I suppose I'm still not used to thinking with Unity's workflow. Still an XNA guy at heart, where these arbitrary relationships are there by design. Yours sounds like the superior method to begin with, so I'm satisfied with that answer if you'd like to post it as one.
$$anonymous$$any thanks. :)
The solution is that the standard way to do this is to attach your script to the game object as a component. In this scenario; my code is the appropriate way to access your script.
Indeed, I suppose so. $$anonymous$$ight confuse someone looking unless they read these comments, but I selected it as correct. I do appreciate everyone's time and patience. :)
Your answer
Follow this Question
Related Questions
Move player to specific location and avoid obstacle. 2 Answers
Im trying to create a word game with a twist 0 Answers
Raycast not detecting ANY HITS AT ALL when starting inside a collider. 0 Answers
Raycast Destroy(hit.collider.gameObject); (Still need help) 1 Answer
Logic to detect objects entering between the player and camera? 1 Answer