FindGameObjectsWithTag doesn't find objects that are added during runtime

Hey.
So I have five objects with the same tag. In a script I add about 250 more objects with the same tag. Then I’d like to change a property of their shader:

        foreach(GameObject fooObj in GameObject.FindGameObjectsWithTag("Placeholder"))
        {
            fooObj.GetComponent<Renderer>().material.SetFloat("_Thickness", 5);
        }

This almost works. The problem is that only the shader of the initial 5 gameobjects gets updated.

Any ideas?

Thanks

if you spawn the objects add them to a list. and then “do something” maybe? always avoid if possible findgameobject

OK, I haven’t tested this but off the top of my head:

You probably don’t want to do it that way.
Firstly, setting material can alter the asset. You want to use sharedmaterial instead.

Secondly, since you’re setting them all to the same value, what you really want to do is set them all to the SAME SHARED MATERIAL reference when you create them.

TheShardMaterial.setfloat(5);

Is all you really need, since they all have the same material reference. And they can be batched.

If you want them to have unique _Thickness values, then check out “Material Property Block”.

That’s if they’re all the same material. If they have a set of different materials, you can do things like keep a dictionary of common/shared materials and set them that way so you don’t break batching for whatever groups have the same settings.

Also, since you’re creating them on the fly, keep your own list as you make them and don’t use FindGameObjectsWithTag at all. And stash the result from GetComponent or the resulting sharedmaterial reference so you don’t have to make the function call each time.

Lastly, FingGameObjectsWithTag() works. So it can likely be assumed you didn’t set the tag on the instantiated objects like you think you did and/or you set them at the wrong time. You didn’t show that code, so IDK what else to say. See note here:

Hope this helps.