- Home /
renderer.enabled question
Why does this code work:
function Start()
{
renderer.enabled = false;
}
function Update ()
{
if(Input.GetKeyUp("m"))
renderer.enabled = true;
if(Input.GetKeyUp("n"))
renderer.enabled = false;
}
But this code doesn't:
function Start()
{
renderer.enabled = false;
}
function Update ()
{
if(Input.GetKeyUp("m"))
{
if(renderer.enabled == true)
{
renderer.enabled = false;
}
if(renderer.enabled == false)
{
renderer.enabled = true;
}
}
This one will render the object, but will not un-render it.
Comment
Best Answer
Answer by Eric5h5 · Jun 27, 2011 at 10:50 PM
Because:
if(renderer.enabled == true)
{
renderer.enabled = false;
}
OK, so that sets renderer.enabled to false. And then:
if(renderer.enabled == false)
{
renderer.enabled = true;
}
renderer.enabled was false, so you just immediately set it back to true again. You should use else if
, or better yet, just toggle it:
if(Input.GetKeyUp("m"))
{
renderer.enabled = !renderer.enabled;
}
The problem is that computers only do exactly what you tell them to do, not what you want them to do. ;)
Answer by dotbox · Nov 13, 2013 at 01:06 AM
Oh yeah, got a similar question. maybe it's that easy as above. With Cube = GameObject.Find("Cube"); defined within Start(). This code works pretty fine, but when i uncomment the "else" line, "D" doesn't have any effect anymore. WHY ???
if(Input.GetKeyDown(KeyCode.D)){
if(Cube.renderer.enabled){
Cube.renderer.enabled = false;
}
//else Cube.renderer.enabled = true;
}
if(Input.GetKeyDown(KeyCode.V)){
Cube.renderer.enabled = true;
}
if(Input.GetKeyDown(KeyCode.F)){
if(gameObject.renderer.enabled){
gameObject.renderer.enabled = false;
}
else gameObject.renderer.enabled = true;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612123843im_/https://answers.unity.com/themes/thub/images/avi.jpg)