Show only selected enemy's health bar

'Ello all. I’ve been 'aving a bit of an issue with the above. I kind of wonder if I’m just trying to access the variable the wrong way.

'ere’s where I’m trying to access it in the targetting script:

	private void SelectTarget()
	{
		//We'll change the selected target's color to red, so we can tell it apart.
		selectedTarget.renderer.material.color = Color.red;
		
		EnemyHealth2 st = (EnemyHealth2)GetComponent("EnemyHealth2");
		st.GetComponent<EnemyHealth2>().isSelected = true;
		
		PlayerAttack2 pa = (PlayerAttack2)GetComponent("PlayerAttack2");
		
		pa.target = selectedTarget.gameObject;
	}
	
	private void DeselectTarget()
	{
		//We'll change the color back to white.
		selectedTarget.renderer.material.color = Color.white;
		selectedTarget = null;
		
		EnemyHealth2 st = (EnemyHealth2)GetComponent("EnemyHealth2");
		st.GetComponent<EnemyHealth2>().isSelected = false;
	}

'ere’s the bit containing the variable in my enemy 'ealth script. The bool is declared up top and initially set to false.

void OnGUI()
	{
		if(isSelected = true)
		{
			//Set up a box to hold our health bar.
			GUI.Box(new Rect(10, 40, healthBarLength, 20), curHealth + "/" + maxHealth);
		}
	}

You’re doing a big mess when accessing the selected target EnemyHealth2 script. You must have a reference to the selected target in order to get one of its components - and selectedTarget is this reference:

private void SelectTarget()
{
   //We'll change the selected target's color to red, so we can tell it apart.
   selectedTarget.renderer.material.color = Color.red;
   // use selectedTarget as the GetComponent reference:
   selectedTarget.GetComponent< EnemyHealth2>().isSelected = true;
   // without a reference, the owner object is assumed - in this
   // case, PlayerAttack2 must be attached to the same object as
   // this script:
   PlayerAttack2 pa = (PlayerAttack2)GetComponent("PlayerAttack2");
   pa.target = selectedTarget.gameObject;
}

private void DeselectTarget()
{
   //We'll change the color back to white.
   selectedTarget.renderer.material.color = Color.white;
   selectedTarget.GetComponent< EnemyHealth2>().isSelected = false;
   selectedTarget = null; // assign null after using selectedTarget!
}