I have script that is adding multiple spheres (prefabs) to the scene. On those prefabs, I have a script to change their materials color. About 1 every 10 prefabs color will actually change to the desired result. If that prefab with the changed color is destroyed, a random prefab will finally show the desired color. Hope that made sense?
Here is what I have on the prefab :
function Update()
{
gameObject.Find("Sphere").renderer.material.color = Color(1.0, 0.0, 1.0, 1.0);
}
The reason for me using gameObject.Find(“Sphere”) is to grab the child which has the material attached to it. The parent doesn’t have any materials applied to it.
If all the spheres are named “Sphere”, then you have to add all spheres to a GameObject[ ] and loop through the objects in the array to change the color on all of them.
GameObject.Find() only returns a single object per frame. Hence, one random object. Populate an array using GameObject.FindGameObjectsWithTag().
It’s also not a good idea to use these find utility functions within an Update(). They’re very slow. Cache the values by populating a list as you create/destroy the spheres.
private var color : String;
function Awake()
{
color = Random.Range(0, 10) < 5 ? "black" : "white";
sphere = gameObject.FindGameObjectsWithTag("Bubble")[0];
sphere.renderer.material.color = color == "black" ? Color.black : Color.white;
}
function Update()
{
transform.Translate(0, -1 * Time.deltaTime, 0);
}
For some reason, all the bubbles are still white. There will be 1 in every ~30 bubbles that are black, but then that same bubble with switch back to white after 1-2 seconds, then back to black, then back to black… why?
I have this script attached to my Prefab, and there is a child prefab that has a tag name called “Bubble”. I am trying to change the materials color.