I’ll start off by saying I’m pretty new to programming in unity.
What I want to accomplish is to generate a random number which I believe I have done correctly. Then based on the number assign a texture to a cube object. I have 4 different textures I am testing this with.
This is the only code I could come up with, I’m not sure how to assign texture to an object with script.
num = Random.Range(0,4);
Debug.Log(num);
if(num == 0)
{
}
else if(num == 1)
{
}
else if(num == 2)
{
}
else
{
}
Help is appreciated.
You need to have that object as a variable and drag the object through the inspector.
Something like this:
// being this var public will appear in the inspector
public var theObject : GameObject;
// do the same with the textures
public var texture1 : Texture2D;
public var texture2 : Texture2D;
public var texture3 : Texture2D;
public var texture4 : Texture2D;
num = Random.Range(0,4);
Debug.Log(num);
if(num == 0)
{
theObject.renderer.material.mainTexture = texture1;
}
else if(num == 1)
{
theObject.renderer.material.mainTexture = texture2;
}
else if(num == 2)
{
theObject.renderer.material.mainTexture = texture3;
}
else
{
theObject.renderer.material.mainTexture = texture4;
}
Hello KelliB,
There is an example of what you’re trying to do in the documentation for the material class.
You won’t need a long if or switch statement. Just pick a random number and use it as the index to your array of textures.
//Forum code
num = Random.Range(0, textures.length - 1);
renderer.material.mainTexture = textures[num];
Something similar to that.
Thank you both I’ll try them both!