- Home /
Question by
SamTheT · Apr 19, 2015 at 10:19 PM ·
transformgetcomponentmeshrenderer
Getting mesh renderer from a Transform(not "transform")
I've been working on a project and decided to make sounds when walking.
To do that I shoot rays, collect them to array and pick nearest collider.
The problem is that to play sound corresponding to ground material I need to get that material and I tried a lot of things, none worked.
Code:
void CheckGroundType()
{
if (direction.magnitude == 0 || !cc.isGrounded || walkSoundTimeLeft > 0)
{
return;
}
Ray ray = new Ray(this.transform.position, -(this.transform.up));
Transform HitTransform;
Vector3 HitPoint;
HitTransform = FindClosestHitObject(ray, out HitPoint);
Material groundMaterial = HitTransform.gameObject.transform.GetComponent<MeshRenderer>().material;
fxManager.GetComponent<PhotonView>().RPC("PlayerWalk", PhotonTargets.All, groundMaterial, HitPoint);
walkSoundTimeLeft = walkSoundTime;
}
Transform FindClosestHitObject(Ray ray, out Vector3 HitPoint)
{
RaycastHit[] Hits = Physics.RaycastAll(ray);
Transform ClosestHit = null;
HitPoint = Vector3.zero;
foreach (RaycastHit Hit in Hits)
{
if (Hit.transform != this.transform && ClosestHit == null)
{
ClosestHit = Hit.transform;
HitPoint = Hit.point;
}
}
return ClosestHit;
}
I tried: 1.HitTransform.transform.GetComponent().material; 2.HitTransform.GetComponent().material; 3.HitTransform.gameObject.GetComponent().material;
I'm desperate, please help
Thanks a lot in advance!
Comment
Best Answer
Answer by Raresh · Apr 19, 2015 at 11:20 PM
HitTransform.GetComponent ().material
by the time unity managed to post my question, I found the answer, simply the raycastAll was returning null