Attack only when character is front

Hi guys,

i am working on a game where player can switch places of three different characters i am using following script so by pressing E characters switch places. i am using a placeholder which contain all three characters.

var character1 : GameObject; // Your first character
var character2 : GameObject; // Your second character
var character3 : GameObject; // your third character
 
var activechar = 0; // when 0 active character is char1, when 1 active character is char2, etc.
 

function Update()
{
if(Input.GetKeyDown(KeyCode.E))//if they press E the active char is switched
{
activechar++;
  if(activechar >2)
   activechar = 0;  // makes sure it cycles through your 3 characters
}
 
IsActive(); //calls the IsActive function to see which sprite is enabled
 
}
 
function IsActive()
{
if(activechar==0) 
{
character1.transform.localPosition = Vector3(1.5, 0, 0) ;
character2.transform.localPosition = Vector3(0, 0, 0) ;
character3.transform.localPosition = Vector3(-1.5, 0, 0);
}
if(activechar == 1) 
{
character1.transform.localPosition = Vector3(0, 0, 0);  
character2.transform.localPosition = Vector3(1.5, 0, 0) ;
character3.transform.localPosition = Vector3(-1.5, 0, 0);
}
if(activechar == 2) 
{
character1.transform.localPosition = Vector3(0, 0, 0);  
character2.transform.localPosition = Vector3(-1.5, 0, 0);
character3.transform.localPosition = Vector3(1.5, 0, 0);
}
}

I have done my ranged attack script as well
var rangeattackPrefab : GameObject;
function Update (){

if (Input.GetKeyDown("f")) {
 attackRange();
 }
 }
 
 function attackRange () {
 
 Instantiate(rangeattackPrefab, this.transform.position,this.transform.rotation);
 }

My question is how make it so that only character in the front attack ? If the character is in center or in back he cannot attack.

thanks

The code below is not a generic code but will work depending on your hard coded values.

Considering the Game Object with x value equal to 1.5 is at the first position the psuedo code will look like:

if(transform.position.x == 1.5) {
    // Can attack
} else {
    // Can not attack
}

I am assuming you are attaching this ranged attack script to all these three Game Objects.

To make it more generic you have to sort the Game Objects based on their position to decide which one is at the front and then allow that game object to attack.