Raycast.hit returning strange variables.

Hi, I’m using a raycast to get the distance between two objects. A soldier object and anything else. I need to use raycast instead of just using math on the two positions because the range on the soldier is about the same as the distance from the edge of an object to it’s center and I thought it would be better than adding a certain value depending on the target. Anyway, for some reason it only works on one object, and even then only just. On the worker object my function returns an incorrect value, 50 and it doesn’t change much, increasing only by about .01 or something when the object comes closer then all of a sudden drops to 1 after they are at the same position (the soldier is told to move when it is too far, but thinks it is always too far) and varies by about .01 when it moves closer or further. even when it is about 10 units away. However on other soldiers, it just shows infinity. Here is the code for finding the distance.

// Find distance from self to attack target
	float FindDistanceAttack()
		// Find the direction to send the ray
		Vector3 attackVector = (gameObject.transform.position - attackTarget.transform.position).normalized;
		RaycastHit hit;
		if (Physics.Raycast(gameObject.transform.position, attackVector, out hit))
			temp = hit.distance;
			return hit.distance;
			temp = Mathf.Infinity;
			return Mathf.Infinity;

I have a feeling it has something to do with normalizing the vector.

Kind regards,

You are calculating your attackVector wrong. It should be

Vector3 attackVector = (attackTarget.transform.position - transform.position);

You don’t need to normalize the vector, but it did not hurt the calculation to do so.