- Home /
Footsteps and Bulletholes based on Material UVs?
Hello, I'm stumped with this one. I'm trying to figure out how to access the Unity PBR material of a surface based on a raycast, and check whether or not it's shared material is in one of multiple lists that determine what footstep sound effect to play, what bullet hole texture to use, whether one surface makes more sound when you walk across it (thief: dark project stealth mechanic) and so many other interesting things.
I've been looking around Unity Answers, and I believe this can also be done with a CharacterController collision check? Could someone give me an example? It sounds familiar.
You don't need a CharacterController - in fact, you've pretty much listed the correct approach already: perform a raycast downwards from the player, using the appropriate layermask to deter$$anonymous$$e the object on which they are standing. Then retrieve the sharedmaterial of the renderer component of that object, and compare it to your list. What part are you stuck on?
"that deter$$anonymous$$e what footstep sound effect to play" wouldn't you just use a tag or layer - or nothing more than the name of the game object - for that? it seems really weird to go to the material.
As others have mentioned if (for some reason) you want the material just type .shared$$anonymous$$aterial. (Do NOT type ".material". If you don't know why, you don't want to know why :) )
Answer by rageingnonsense · Nov 30, 2015 at 09:13 PM
If I understand correctly, you are trying to find the physics material of a gameobject; correct? Have you tried:
GetComponent<Collider>().sharedMaterial;
?
If you meant the shader material, try this:
Material[] mats = GetComponent<MeshRenderer>().sharedMaterials;
// now you have all materials assigned to this object; do what you want with them
or this if you only have one for each object:
Material mat = GetComponent<MeshRenderer>().sharedMaterial;
Answer by JonathanCzeck · Dec 01, 2015 at 02:36 PM
When you Raycast you can get a RaycastHit structure back on a hit. (Let's call that variable raycastHit) In that will be a variable called "collider". Now, either you have your meshes on this object or they are on some other object because you have a simplified collider.
If the collider is the same as the rendered mesh, then you can simply do: raycastHit.collider.GetComponent<Renderer>().sharedMaterial
. If not, you will need to have a script that links the collider to the rendered mesh. (Call that ColliderToRendererLinker) You then would raycastHit.collider.GetComponent<ColliderToRendererLinker>().linkedRenderer.sharedMaterial
.
Is that enough to guide you?