Any good idea for storing a bool value for similar game objects?

Here’s the situation. I got three balls in the scene. They are red, green, blue balls holding scripts named RedController,GreenController and BlueController. What I want to do is when I click on a ball, it can be controlled with WASD and other balls are disabled for controlling. I’ve realized it by using OnMouseDown() and so on. But every time I want to disable other balls, I have to do “playerGreen.GetComponent().active=false” (active is a bool set to able or disable the ball’s control). Since diffrent balls get diffrent scripts, I have to write this kind of code many times. Do you got any good idea to optimize the code?

Better use a “currentBall” variable where you switch it OnMouseDown()
And change it based on a tag, or name, or any variable in your script:

1 for Red

2 for Blue

3 for Green

And in your controller you simply check for that variable:

//RedController

if(manager.currentBall == 1){ //Red

//Control Red

}

//Blue Controller

if(manager.currentBall == 2){ //Blue

//Control Blue

}

//Green Controller

if(manager.currentBall == 3){ //Green

//Control Green

}

I guess it understand your problem. Here is my solution

public class BaseBall : MonoBehaviour {
	public static BaseBall ActiveBall;

	private bool _Active = false;
	public bool Active {
		get {
		return _Active;
		}
		set {
			_Active = value;
			if (_Active) {
				if (ActiveBall != null) {
					ActiveBall.Active = false;
				}
			
				ActiveBall = this;
			} else {
				ActiveBall = null;
			}
		}
	}

	public BaseBall GetActiveBall() {
		return ActiveBall;
	}
}

public class RedBall : BaseBall {
}

public class BlueBall : BaseBall { 
}

public class GreenBall : BaseBall {
}

I would create a BallController class with a SetController(bool value) method. Each of the ball color controller inherits from it. Then you have a BallManager that listens to the input:

public class BallController:MonoBehaviour{
   public void SetBall(bool value){ active = value;}

   void OnMouseDown(){
        ballManager.SetBalls(this);
    }
}

public class BallManager:MonoBehaviour{
    BallController [] ballControllers = null;
   void Start(){
       // Get all ball controller in games, that will get your Red/Green/BlueController since they inherit
   }
   public void SetBalls(BallController bc){
       foreach(BallController ballCont in ballControllers){
             ballCont.SetBall(true);
             if(ballCont == bc)continue;
             ballCont.SetBall(false);
       }
   }
}

So what it does is that when one of the ball gets the OnMouseDown, it will call the BallManager method and pass itself as parameter. Inside the SetBalls method, you run through each BallController first setting them to true, then if if the current ball happens to be the calling one, then you skip to next, if not it means it is meant to be the other two and you set it back to false.