Search Unity

Need help with something that I thought is fairly straightforward

Discussion in 'Scripting' started by scr33ner, Mar 13, 2019.

  1. scr33ner

    scr33ner

    Joined:
    May 15, 2012
    Posts:
    188
    Hey all, I need a little help with this.

    I've an empty game object with 2 meshes whose renderers I would like to disable.

    I've got this coded as such:
    Code (CSharp):
    1.  
    2. public class LocatorRendererControl : MonoBehaviour {
    3.  
    4.    public Renderer renderLocator;
    5.    public Renderer renderLocatorFp;
    6.  
    7.    // Use this for initialization
    8.    void Start ()
    9.    {
    10.        renderLocator = GetComponentInChildren<Renderer>();
    11.        renderLocatorFp = GetComponentInChildren<Renderer>();
    12.  
    13.        renderLocator.enabled = false;
    14.        renderLocatorFp.enabled = false;
    15.    }
    16.  
    17. }
    The problem I'm running into is that, renderLocatorFp NEVER gets disabled per code. Somehow, the Locator is the only one that gets disabled.

    Here's the setup

    What's happening during runtime

    Thank you in advance.
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    They are both finding the same object. Manually assign the references in the inspector or use get componentS [0] and [1]
     
  3. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    GetComponentInChildren is going to return the same component, so both renderLocator and renderLocatorFp both point to exactly the same renderer. Hence, you are disabling the same renderer twice.

    I would suggest removing those 2 lines, and manually dragging and dropping the renderer onto the field in the inspector.
     
  4. scr33ner

    scr33ner

    Joined:
    May 15, 2012
    Posts:
    188
    Thank you, changed it to

    Code (CSharp):
    1.  
    2.     public Renderer[] renderLocator;
    3.  
    4.     // Use this for initialization
    5.     void Start ()
    6.     {
    7.         renderLocator = GetComponentsInChildren<Renderer>();
    8.        
    9.  
    10.         foreach(Renderer rLocator in renderLocator)
    11.             rLocator.enabled = false;
    12.        
    13.     }
     
    Kurt-Dekker and bobisgod234 like this.