Change color of object with C#
Hi,
I would like to ask if it is possible to do following with Unity 5 in 2D and C# and how can it be done, or perhaps there is a tutorial I can look at:
instantiate game object (circle or rect) with c# script without any texture or sprite assigned through the unity interface?
I would like to apply a color as per randomly selected palette and be able to change for each level during the game.
is it possible to do the same with a custom shape object, for example a gear (I have Gear.PNG file for it).
Is there perhaps an asset in Unity store which can be also helpful to accomplish it?
Thank you
Answer by Jessespike · Sep 08, 2016 at 06:38 PM
It's possible.
[RequireComponent(typeof(Canvas))]
public class ChangeColor : MonoBehaviour {
public GameObject prefab;
public Color[] palette = new Color[]{ Color.white };
// Use this for initialization
void Start () {
GameObject go = Instantiate(prefab);
go.GetComponent<Image>().color = palette[Random.Range(0, palette.Length)];
go.transform.SetParent(this.transform, false);
}
}
This example script requires a UI Canvas, (Create -> UI -> Canvas)
The prefab will be a blank UI.Image.
In the project window, create a prefab (Create -> Prefab).
Then in the hierarchy window, create a new UI.Image (Create -> UI -> Image).
Drag and drop the new Image GameObject onto the blank prefab in the project window.
Delete the Image GameObject in the scene.
Drag and drop the prefab from the project window into the Prefab property of the script.
For tutorials, watch the Unity Tutorials, they explain all of this.
Sorry for a late reply to your post. Thank you for your advice. I will try it out as soon as I get a chance.