Home > Net >  Change Color of just one instantiated object in Unity
Change Color of just one instantiated object in Unity

Time:11-13

In my game I instantiated many objects from a prefab, then after a few seconds, I select one object as a target so I want to change the color of just that one object in Unity.

I tried diferents options of previous questions

gameObject.GetComponent<Renderer>().material.color = mycolor;

and also

 Renderer victimRender = target.GetComponent<Renderer>();
 victimRender.material.color = Color.black;

But I get the following error

Not allowed to access Renderer.material on prefab object. Use Renderer.sharedMaterial instead

And if I use sharedMaterial insteat of material, it changes the prefab material so all objects change their color.

It's possible to change the color of just one instantied object?

UPDATE

I instantiate the game objects in other script and store them in an array in the current script I want to access one random position of the array and get one gameObject

 
        victimMaterial = Resources.Load<Material>("VictimMaterial");       
        target = SpawnerController.sharedInstance.citizens[victim];
        MeshRenderer victimRenderer = target.GetComponent<MeshRenderer>();          
        victimRender.material = victimMaterial;

Instead of getting the cloned object, it's getting the prefab so I cannot change the color of adding other material to it's Mesh Render

If only I could reference the cloned object instead it's prefab I could easily change the color.

Also in game mode I can drag the material to it's mesh render and it change the color of that particular object, so I'm sure it must be a way to achieve it

CodePudding user response:

Make sure you are refencing the instantiated Object instead of the prefab.

This should work for you:

GameObject instance = Instantiate(prefab);

instance.GetComponent<Renderer>().material.color =
                new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f),1f);
  • Related