- Home /
How can I hit raycast on only one collider and ignore oter collider types
I have Gameobjects I want to select and the selection itself works with Physics.Raycast. But some objects have a sphere collider additionally to the capsule collider. I only want them to be selectable on the capsule collider. How can I do that? I guess the Ignore Raycast layer is not an option, since that would ignore the whole Gameobject.
Answer by AndresBarrera · Jan 22, 2015 at 08:59 AM
Use collition layers for your objects. Check this and this. Example:
int mask = (1 << LayerMask.NameToLayer("Tiles"));
Ray ray = ........;//Init your ray
RaycastHit rayHit;
Physics.Raycast(ray, out rayHit, 100, mask);
//This will test a ray only against objects inside the "Tiles" layer
Can you explain why this would ignore all other colliders? It seems that the whole object inside the "tiles" layer would be ignored. But I don't want an object to be ignored, I only want to ignore its sphere collider (and maybe others). Otherwise the ignore raycast layer would be a good joice, I guess.
Are you using two colliders on the same GameObject? $$anonymous$$y suggestion would be to put one of your colliders (lets say the sphere) on the main object, and the other (the capsule) on a child object. Put that child object in the layer you want to detect with raycast, but not the parent.
From this point on it will depend on what you are doing and how do you want to keep your hierarchy. You can communicate parent and child objects with scripts, or pass some of your scripts from the parent to the child, or use GetComponentInParent to access some behaviour when you detect the ray hit on the child.
Thank you so much! The answer is great and really helped me.
Answer by MaximilianPs · Apr 13, 2016 at 09:04 PM
I have the same problem, it's an RTS, the soldier have a box collider used to be selected by the player by click on 'em, but the soldiers have also another very big sphere collider which is used for other game mechanics. So, i need the raycast hit the box collider but not the sphere collider. Any help ? O.o
Your answer
Follow this Question
Related Questions
Unity RayCast Selection 1 Answer
Raycast Object Selection 3 Answers
GUI Box not showing up after object clicked 1 Answer
Add force to the selected object 1 Answer
Help - Selection System 1 Answer