So basically I want to change the material, (or texture if possible) on my character. (Its a sphere atm - representing a bubble like thing that you control). It has a material on it that has a texture. When I hit a crate I wan’t the material to change to a different one. I’m using Java Script in this game so don’t give me anything in C# or something else.
So in other words, how can I change the material of an object after it hits a collider?
Something like this?
function OnTriggerEnter( hit : Collider )
{
if(hit.gameObject.tag == "Crate")
{
//Change material of object this is on
}
}
Ok well I ended up taking a bit of time to figure this out myself. This is what I did…
//Meshes for character
var MeshControl = 0;
var Mesh1 : Texture;
var Mesh2 : Texture;
var Mesh3 : Texture;
var Mesh4 : Texture;
var Mesh5 : Texture;
var Mesh6 : Texture;
function Update()
{
//Meshes Changers
switch(MeshControl)
{
case 0:
renderer.material.mainTexture = Mesh1;
break;
case 1:
renderer.material.mainTexture = Mesh2;
break;
case 2:
renderer.material.mainTexture = Mesh3;
break;
case 3:
renderer.material.mainTexture = Mesh4;
break;
case 4:
renderer.material.mainTexture = Mesh5;
break;
case 5:
renderer.material.mainTexture = Mesh6;
break;
}
}
function OnTriggerEnter( hit : Collider )
{
if(hit.gameObject.tag == "Crate")
{
MeshControl += 1;
}
}
Use an array of materials instead of discrete variables. Iterate an index of the array and set your material accordingly.
Two lines are always better than 20.
// Warning forum code!
var textureArray : Texture[];
var textureIndex = 0;
function OnTriggerEnter( hit : Collider )
{
if(hit.gameObject.tag == "Crate")
{
ChangeTexture();
}
}
ChangeTexture() {
textureIndex++;
// Make sure selection is not out of bounds.
if (textureIndex > textureArray.GetUpperBound(0))
textureIndex = 0;
if (textureIndex < 0)
textureIndex = textureArray.GetUpperBound(0);
renderer.material.mainTexture = textureArray[textureIndex];
}