script is treating all enemies as one, instead of them as individuals.

I’ve got myself a script that is attached to the camera which simply detects when target is at screen edge and tells the enemy2script to turn it around. However, when more than on enemy of type is on screen; the enemies act as one, and turn together and not at the edge. This has confused me.

public var pos : Vector3 = camera.WorldToViewportPoint(but had no idea what went here);

This is the main script; in it’s basic form; It’s how it was before I wanted it to affect more than one enemy of the same type.

var target: Transform;
static var turnaround : boolean = false;
static var turnaround2 : boolean = false;

//public var pos : Vector3 =  camera.WorldToViewportPoint();??

function Update () {	

 	target = GameObject.FindWithTag("Enemy2").transform; 

    var pos : Vector3 =  camera.WorldToViewportPoint (target.position);

    if(pos.x < 0.0){
    turnaround = !turnaround;
    }
    if(1.0 < pos.x){
    turnaround = !turnaround;
    }
    if(pos.y < 0.0){
    turnaround2 = !turnaround2; 
    }
    if(1.0 < pos.y){
    turnaround2 = !turnaround2;

    }

}

Then this is accessed in my enemy2Script:

function Start(){

	var someScript : enemy2CameraScript;
	someScript = gameObject.GetComponent("enemy2CameraScript");
	
	var someScript2 : multiplierScript;
	someScript2 = gameObject.GetComponent("multiplierScript");

}

function Update () {

	if(enemy2CameraScript.turnaround==true){	
   		transform.eulerAngles = Vector3(0,0,180);
		}
		
	if(enemy2CameraScript.turnaround==false){	
   		transform.eulerAngles = Vector3(0,0,0);
		}
		
	if(enemy2CameraScript.turnaround2==true){	
   		transform.eulerAngles = Vector3(0,0,180);
		}
	
	if(enemy2CameraScript.turnaround2==false){	
   		transform.eulerAngles = Vector3(0,0,0);
		}
}

Knowing my luck I’ve missed something simple, but I’m now just confused.

Thanks in advance.

Two mistakes here.

The following code will always return the same object.

target = GameObject.FindWithTag("Enemy2").transform;

Therefore only one enemy will be checked.


You’re using static variables. Thus your enemy2Script are always reading the same value. Combined with your first mistake, all enemies will turn if the first one is at the edge.


What can you do? Don’t put the code to test the position in the camera script but in the enemy script. This way all enemy will do this check separately. Don’t use static variables.

Here is my fix, only took a morning (fml)

  var viewPos = Camera.main.WorldToViewportPoint(transform.position);
  transform.position = Camera.main.ViewportToWorldPoint(viewPos);

	    
   if(0.0> viewPos.x){
   		transform.eulerAngles = Vector3(0,0,0);
    }
    
    if(1.0 < viewPos.x){
   		transform.eulerAngles = Vector3(0,00,180);
    }
    
    if(viewPos.y < 0.0){
   		transform.eulerAngles = Vector3(0,0,0);
    }
    
    if(viewPos.y > 1){
   		transform.eulerAngles = Vector3(0,0,180);
   		
   	}