- Home /
Help doing mouse click changin shader and back to normal to a gameObject ꜛ!
i need help with a code, i need to change the shader of a obj who is "Vertex Lit" while is not selected and if you click on it the shader changes into "Transparent/Bumped Specular"; if you click in no obj but the camara background, everyone is "Vertex Lit" as it should be the normal.
this a script example in my proyect like should be with the shaders but with GUI.
this script is a component for a gameObject that if you click on it, the text you input in the string should be shown:
public class Character : MonoBehaviour
{
public string myWords = string.Empty;
private void Start ()
{
}
private void Update ()
{
}
public string GetWords ()
{
return myWords;
}
}
and this goes for the camera allowing to click a obj, if you click on another obj and if you click on the camara background:
public class UI_Demo : MonoBehaviour
{
private GameObject clicked = null;
private void Start()
{
}
private void Update ()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.mainCamera.ScreenPointToRay(Input.mousePosition), out hit))
{
if (hit.collider.gameObject.GetComponent<Character>() != null)
clicked = hit.collider.gameObject;
else
clicked = null;
}
else
clicked = null;
}
}
private void OnGUI()
{
if (clicked != null)
GUI.Label(new Rect(15,15,200,25), clicked.GetComponent<Character>().GetWords());
}
}
can anyone help me please :( i don't know very much of C# and scripting you can be in the credits or teach me right here. ty if you are reading this coders! and sorry for my bad english..
Answer by HansMcCode · Jul 31, 2013 at 06:57 PM
Would you be looking for something like this?
using UnityEngine;
using System.Collections;
public class ShaderChanger : MonoBehaviour
{
public Shader shader1;
public Shader shader2;
void Awake()
{
shader1 = Shader.Find("Diffuse");
shader2= Shader.Find("Transparent/Diffuse");
}
void Update()
{
if (Input.GetButtonDown("Jump"))
{
if (renderer.material.shader == shader1)
renderer.material.shader = shader2;
else
renderer.material.shader = shader1;
}
}
}
This should change the shader to whatever you'd like while the space bar is held down. Should be able to hook it into your click detection easily enough.
"renderer.material.shader = " is the important line that set the shader
Hope this helps :)
Updated my code to match this, I recommend going through the script ref, incredibly useful. http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$aterial-shader.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613111304im_/https://answers.unity.com/themes/thub/images/avi.jpg)