Search Unity

Hide/Show unless it has material

Discussion in 'Scripting' started by Truls_, Aug 21, 2018.

  1. Truls_

    Truls_

    Joined:
    Dec 4, 2016
    Posts:
    107
    I have this house where all the different parts are individual objects, and when I click on anything - say a wall - it will get highlighted. I now have this function
    Code (CSharp):
    1.        
    2. GameObject[] gameobjects = GameObject.FindGameObjectsWithTag(tagName1);
    3.         foreach (GameObject go in gameobjects)
    4.         {
    5.             if (go.GetComponent<MeshRenderer>().enabled == true)
    6.             {
    7.                 go.GetComponent<MeshRenderer>().enabled = false;
    8.                 go.GetComponent<MeshCollider>().enabled = false;
    9.             }
    10.             else
    11.             {
    12.                 go.GetComponent<MeshRenderer>().enabled = true;
    13.                 go.GetComponent<MeshCollider>().enabled = true;
    14.             }          
    15.         }  
    16.  
    where I can hide/show for example all the walls or all the windows/doors etc. but if one of the objects has been highlighted (has the material "selected") I don't want to hide that specific object. The highlighted one should always be visible. does anybody have any idea for how to do this?
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    You could just reorganise the "if" to ignore something that is highlighted (as long as you know how to check that it is highlighted of course). So, maybe something like this? :-
    Code (CSharp):
    1. foreach (GameObject go in gameobjects)
    2. {
    3.     if( ! add_the_is_highlighted_test_here )
    4.     {
    5.         go.GetComponent<MeshRenderer>().enabled =
    6.         go.GetComponent<MeshCollider>().enabled = !go.GetComponent<MeshRenderer>().enabled;
    7.     }
    8. }
    Incidentally, you should really try to limit runtime calls to
    FindGameObjectsWithTag
    . You might want to consider having some sort of a manager class that tracks these objects (i.e. the adding and removing of them) and get the list of current objects from that manager instead.
     
  3. Truls_

    Truls_

    Joined:
    Dec 4, 2016
    Posts:
    107
    I tried to do something like this
    Code (CSharp):
    1.          
    2.  if (go.GetComponent<Renderer>().material != selected)
    3.             {
    4.                 go.GetComponent<MeshRenderer>().enabled =
    5.                     go.GetComponent<MeshCollider>().enabled = !go.GetComponent<MeshRenderer>().enabled;
    6.             }
    7.  
    but the selected object still disapears.. what am I doing wrong?
     
  4. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Does the "if" on line 2 definitely work correctly? You may want to step it through in the debugger or add debug logging to find out what is happening.