- Home /
Changing materials of a plane on keydown.
Hi, I'm new to Unity and Javascript and I'm having a bit of trouble working out a few things with changing a materials on a plane upon a keydown event.
For instance, when I want the material on the plane I'm using for my character to change to a picture I've created of my main character facing left. I've had a look though various other questions similar to my own and I'm just not sure.
I'm not sure if this code is correct at all;
function Update () {
if (Input.GetKeyDown("a")) {
body.renderer.materials = MaterialLeft;
}
}
I'm curious as to where I would put the image called "MaterialLeft", do Ineed to create a new material, located where I keep my assets, or will this be made on the fly using the code. And also, whether that code would work.
Any response will help! Thanks in advance.
Whilst looking around I also found out how to import resources. public class LearningScript : $$anonymous$$onoBehaviour
{
private Texture testTexure;
void Start()
{
Object temp = Resources.Load("CharacterLeft");
if ( temp == null )
Debug.Log("Load Object Fail");
testTexure = Resources.Load("CharacterLeft" ) as $$anonymous$$aterial;
if ( testTexure == null )
Debug.Log("Load Texture Fail");
But sadly I don't know C++, so I'm unsure on how I'd go about writing this in JavaScript.
Answer by robertbu · Mar 20, 2013 at 12:32 AM
Here is some modification to your code. It will change the texture when an 'a' is pressed. To make it work:
Attach it to the object that will have its texture changed
Select the object in the hierarchy
Look in the Inspector for your Script name followed by (Script), then down to the 'Material Left' variable.
Drag a texture to the 'Material Left' variable. You will be dragging it on top of "None (Texture).
Play the app.
#pragma strict var materialLeft : Texture; function Update () { if (Input.GetKeyDown(KeyCode.A)) { renderer.material.mainTexture = materialLeft; } }
Works wonderfully well. Thank you, I'm really grateful.