- Home /
Add Texture to GameObject through code
Hi,
I have a game object in my scene and I want to add a texture to it through code. The reason that I cannot drag and drop the texture is because, based on certain conditions, the primary game object will change color, so this secondary game object (which is rendered seperatly) needs to do that.
What I did so far is set up public Texture2D types and dropped by textures their. Now if I could just AddComponent, similar to adding a script onto the player game object. But Texture2D is not a Script.
public Texture2D ColorWhite, ColorRed, ColorBlue;
private void ChangeColor() { // holder[0] is the color varaible that is declared in our primary game object script if (GameObject_1.holder[0] == Color.red) // primary game object { // Add the texture to the MiniGameObject (which this script is attached too). gameObject.AddComponent(typeof(ColorRed)); gameObject.AddComponent(typeof(RedTexture)); // Actual Texture } else if (GameObject_2.holder[0] == Color.white) { //gameObject.AddComponent(typeof(WhiteTexture)); } else if (GameObject_3.holder[0] == Color.blue) { //gameObject.AddComponent(typeof(BlueTexture)); } //... }
Answer by qJake · Aug 18, 2010 at 08:46 PM
Textures are NOT components! You can't add them like that.
You want something like:
gameObject.renderer.material.mainTexture = myTexture;