- Home /
Reverse Look up ( have transform want the gameObject of that transform)
so i have the vector 3 position of an object and i want to tell unity what object that is, is there any way to do this?
Answer by aldonaletto · Oct 30, 2011 at 11:03 PM
The title says one thing, the question says another. If you have the transform (like in the title), you can get its Game Object reference as transform.gameObject.
But if you have a 3D point (like in the question) and want the Game Object at that position, things are way different. You could do a Raycast passing through this position, but the ray should start at a near position, since raycasts do not detect objects from inside. The problem here is to choose a suitable near point: if the point is too near, it will be inside the object and nothing will be detected; if it's too far, other objects in between may be detected.
I think the best alternative is to define a point above enough the position - maybe 3 units higher - and do a raycast to the position:
var rayLength: float = 3;
function FindObjectAt(pos: Vector3): GameObject { var start = pos + rayLength * Vector3.up; // set a point rayLength above var hit: RaycastHit; if (Physics.Raycast(start, -Vector3.up, hit, rayLength)){ // do the ray down return hit.transform.gameObject; // return the object hit... } else { return null; // or null if none } }
I guess a simple Physics.OverlapSphere with a very small radius would do ;). You will get a list of all objects that intersect with that "point" so you can sort them out as you like.
How does that actually work? For example, if I'm using a collider which is completely bigger than the spherecast, will it still detect that collider? I'm almost certain that wouldn't work for non-convex mesh colliders...
Answer by ninjarob · Oct 30, 2011 at 10:21 PM
No not realy because several objects can be in the same place so unity wouldn't know which to return.
if you have the transform of the object though you can do the following
objTransform //contains the transform of the object
var obj:GameObject = objTransform.gameObject
Or, in fact, you can use
transform.gameObject.transform.collider.rigidbody.transform.gameObject;