Search code examples
c#unity-game-engineaugmented-realityvuforia

How to change color of the instance of a prefab in runtime?


I have a problem to change of color of prefab object in runtime.

The problem is that the prefab is composed of a GameObject and inside it is the cube. Therefore, when you instance the object from runtime does not allow you to change the color. How can I identify that created object and change its color or any other property?

Here the image of the error:

Errors

This is my repository with the project (branch develop): https://github.com/emicalvacho/MapaMentalAR


Solution

  • Therefore, when you instance the object from runtime does not allow you to change the color

    Yes .. simply store the reference when you instantiate. From your exception in the console you can see that you (accidently?) are trying to change the color of the prefab itself - not the just created instance.

    var instance = Instantiate(prefab, position, rotation);
    var objRenderer = instance.GetComponentInChildren<Renderer>(true);
    objRenderer.material.color = Color.blue;
    

    It seems that in your scripts you are referencing the prefab instead of the instantiated object.