I have created a prefab called DestroyPlane (for killing player on collision). I’m interested in changing the main colour of all instances of DestroyPlane from a C# script. This paramater is shown by the green arrow in the picture below.
If it makes any difference, I plan on controlling these colour changes from a script that is not attatched to DestroyPlane, but to another object which on collision will cause the colour to change.
Can anyone tell me how I would access the the prefab colour and change it to a new colour from a C# script so that all instances used in the level change colour at the same time?
Once the collison happens, just search the scene for tagged objects to change values on them.
You can store all found in a list and then loop through the list, change all stuff and then remove the item from the list. Or use an array and a foreach to do the stuff.
How ever the approach could be:
void OnTriggerEnter(Collision other)
{
if(other.collider.tag == "whatever")//whatsever collides
{
GameObject[] destroyPlanes = GameObject.FindGameObjectsWithTag ("destroyPlane");//create an array of gameobjects
{
foreach (GameObject plane in destroyPlanes)//go through em
{
plane.GetComponent<Renderer>().material.color = new Color32();//set your color here
}
}
}
}
It could contain problems, but thats the basic idea, how i would try to approach this.
You have two options that I can think of. If you can assign the material directly to the script that will be changing the color, then it’s an easy change.
public Material destroyPlaneMaterial;
void ChangeMaterialColor()
{
destroyPlaneMaterial.color = Color.red;
}
However, if you’re unable to do this for whatever reason (multiple types of destroy planes, texture could change during runtime, etc) then you can access this through the Renderer’s ‘sharedMaterial’ variable.
public GameObject destroyPlane;
void ChangeMaterialColor()
{
destroyPlane.GetComponent<Renderer>().sharedMaterial.color = Color.green;
}
If you need to be able to do this repeatedly, then either try to use the first method, or at least store the Renderer reference for use in the second so you’re not calling GetComponent unnecessarily.
Note for both of these: Since you’re changing the material directly, this is saved even after exiting Play mode, so you’ll need to reset the color on game start. Also, if you’re using this material on any other objects, they will also be changed. Make sure the material is only used on destroy planes that you want to modify.