Javascript Distance Check Not Working

I’m working on a script which means that if a player presses the ‘e’ key when close to another player, they will attack. Although I can see in the inspector that the variable ‘distance1’ is working and changing as the characters move, I don’t get any of my Debug.Log statements and pressing the e key does nothing. I’m guessing this means that the statement ‘if(distance1 < 2)’ is never fulfilled. Any ideas why this could be? Thanks.

var distance1: float;

function Update () {	

	var manager = GameObject.Find("NetworkManager");
	var script = manager.GetComponent(NetworkManagerScript);
	
	var Player1 = script.Player1;
	
	distance1= Vector3.Distance(gameObject.transform.position, Player1.transform.position);
	
	if(distance1 < 2){
	
		Debug.Log("Close");
	
		if(Input.GetKeyDown("e")){
		
			Debug.Log("Dead");
			Destroy(Player1);
		}
	}
}

Also the "distance1" variable should be declared inside Update, unless you're using it in another function.

1 Answer

1

Thanks for the responses, but for future reference, the issue was that for some reason it wasn’t taking the distance from a network instantiated player. I fixed it by adding all the if statements into an ‘if(networkView.isMine)’ statement.