- Home /
MeshRenderer.ShadowCastingMode issue
Hi everyone !
I need a little help with a piece of script. I'm trying to make a mesh invisible but still casting shadows while another one appears without casting shadows. To do so, I'm trying to mess up with MeshRenderer.ShadowCastingMode but I can't find a solution to script this correctly. I always have a NullReferenceException or a MissingFieldException (or something similar). If anyone sees where I'm getting wrong, can he helps me please ?
Thank you by advance.
if(collider.Raycast(rayMouse,mouseHitInfo,Mathf.Infinity))
{
for(var child:Transform in transform)
{
if(child.name == "HiddenWall")
{
child.GetComponent(MeshRenderer).enabled = true;
}
if(child.name == "Wall")
{
child.GetComponent(MeshRenderer).ShadowCastingMode = ShadowCastingMode.ShadowsOnly;
}
}
}
if(!collider.Raycast(rayMouse,mouseHitInfo,Mathf.Infinity))
{
for(var child:Transform in transform)
{
if(child.name == "HiddenWall")
{
child.GetComponent(MeshRenderer).enabled = false;
}
if(child.name == "Wall")
{
child.GetComponent(MeshRenderer).ShadowCastingMode = ShadowCastingMode.On;
}
}
}
Answer by Edy · May 31, 2015 at 07:09 AM
You are referencing properties directly after "GetComponent(MeshRenderer)". GetComponent returns null when the object doesn't have a MeshRenderer component. It's very likely that some child object don't have a MeshRenderer component, thus you are getting the NullReferenceException when trying to set the enabled property.
You should do something like this:
MeshRenderer renderer = child.GetComponent(MeshRenderer);
if (renderer != null)
{
renderer.enabled = true;
// ... etc
}
Also, note that ShadowCastingMode is a type, not a property. Use renderer.shadowCastingMode (first letter lowercase) for accessing the property:
renderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly;
You're welcome. You should accept the answer as correct by clicking the "ok" icon below the thumbs :)