- Home /
Problem is not reproducible or outdated
If statement doesn't work with CompareTag()
I'm new to c# and I'm working in HDRP. I want to apply a material called "Generic House Mat" to all objects in the editor EXCEPT for with tag "Don'tApplyGenMat". I made sure of the spelling and Capitalization in addition of making sure all exceptions have the tag. What happens that the material is applied to all the objects including those with the tag.
if (GUILayout.Button("Apply Generic Materials"))
{
Material newMat = Resources.Load<Material>("Generic House Mat");
foreach (MeshRenderer myRenderer in Resources.FindObjectsOfTypeAll<MeshRenderer>())
{
if (!myRenderer.CompareTag("Don'tApplyGenMat"))
{
myRenderer.sharedMaterials[0] = newMat;
if (myRenderer.sharedMaterials[0] == null)
{
myRenderer.sharedMaterials[0] = new Material(Shader.Find("HDRP/Lit"));
}
}
}
EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
}
Anyone could help? what is wrong with this code? Thanks in advance
Answer by SirCrazyNugget · Jun 15, 2021 at 03:05 PM
I've just tested .CompareTag and it's working as expected.
Initially I'd Debug a message to determine if the right objects are being found, e.g. does the MeshRenderer component exist on all these object? (SkinnedMeshRenderer does not derive from MeshRenderer though both derive from Renderer).
Other than that there's nothing which really stands out as being incorrect.
I'd also store the Shader.Find result too rather than searching for it for each new material.
Follow this Question
Related Questions
Does Material.color, ParticleSystem.startcolor property clones/copies the material? 2 Answers
Can't get a simple reflection to work on a material 2 Answers
Procedural Mesh Texturing 1 Answer
MaterialPropertyBlock causes Z-fighting sprites 0 Answers
How to change object's material while preserving material's color? 0 Answers