Search Unity

Multiple Components to Toggle

Discussion in 'Scripting' started by Littlenorwegian, Feb 13, 2016.

  1. Littlenorwegian

    Littlenorwegian

    Joined:
    Oct 19, 2012
    Posts:
    143
    Hiya, so, this is sort of to keep things cleaner (hopefully)
    Got this code;
    Code (CSharp):
    1. (Player.GetComponent("ThirdPersonController")as MonoBehaviour).enabled  = false;
    It works. I'm trying to get it to work with two components in the same line using &&, but no luck
    Code (CSharp):
    1. (Player.GetComponent("ThirdPersonController") && Player.GetComponent("ThirdPersonCharacter")as MonoBehaviour).enabled  = false;
    I'm trying different things, but no luck so far and so I decided to ask you guys. Thanks! :)
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You can't enable two things at once, you need to do two seperate line of code for that. && is a boolean operator, it means "and", so: if (true AND true) then... not "enable (gameObject1 AND gameObject2)"
     
  3. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,052
    Since the type is the same (enabled - bool), you can assign them both at the same time using "=". So something like this:
    Code (CSharp):
    1. go.GetComponent<Light>().enabled = go.GetComponent<TrailRenderer>().enabled = true;
    Doing multiple things in a single line isn't usually considered cleaner, but it is perfectly valid, and really up to you as far as code style.
     
  4. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    For just the sake of readability, I wouldn't prefer that method.
     
  5. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,052
    Neither would I. But some like stacking assignments like that.
     
  6. Littlenorwegian

    Littlenorwegian

    Joined:
    Oct 19, 2012
    Posts:
    143
    Thanks, guys. Cleared me right up, that did :)