- Home /
Selecting Object. Changing material via script.
Here I am trying to use Unity for the first time. I Managed to make a simple FPS level and to make an object that, with the Raycast thingy, notices when I'm looking at it from reasonably near. Now I would like for it to be 'selected' when I look at it that way, that is, I crated another material with an outline and I would like that the object's material change when I look at it. By copying the Raycast code I had on a script on the player and pasting it in a script on the object I created this:
Shader shader1 = Shader.Find ("Toon/Lighted");
Shader shader2 = Shader.Find ("Toon/Lighted Outline");
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0));
renderer.material.shader = shader1;
if(Physics.Raycast(ray, out hit, 2))
{
if(hit.collider.tag == "Computer")
{
//Change material
renderer.material.shader = shader2;
if( Input.GetButton ("Fire1") ) {
//respawn
renderer.material.shader = shader1;
}
}
}
Since the camera is a child of the player it should work, but (even though it doesn't give me any errors) it doesn't, the material doesn't change. I know that there's a simpler function that should allow objects to know when the mouse overs over them, but it's possible to set a distance from the object for that to work? And it even works with FPS?
Thanks for your help.
Answer by moonstruck · Jun 21, 2013 at 07:43 AM
You don't want to change the shader, because when you do this Unity is most likely to copy the old parameters to a new shader. Instead add 2 public variables with materials, create them and assign in the inspector and change the material (renderer.material = yourMaterial
).
I think I got it, but I'm not sure about the kind of variable I'm supposed to use for materials.
var your$$anonymous$$aterial : $$anonymous$$aterial; // uJS
http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$aterial.html
http://docs.unity3d.com/Documentation/ScriptReference/Renderer-material.html
Edit :
public $$anonymous$$aterial your$$anonymous$$aterial; // C#
If you look at the Unity Scripting Reference, on the right above the script example, there is a drop-down menu, by default set to JavaScript. Click on this, then select C# to see the example in C#
I'm working with C#, that code doesn't work and in the documentation doesn't seem to be clear enough about how I'm supposed to do it in C#. Somebody have an idea?
public $$anonymous$$aterial your$$anonymous$$aterial;
That is how you can declare variables in C#. And don't forget to assign it in the inspector.
I can't bloody believe it. I wrote "material" without the capital $$anonymous$$. Thank you, now it works perfectly. I think it's about time to make it a little bit neater.
Your answer
