Enemy will only take (melee) damage when the distance is below 1 (ie. A zero with decimals after it)

Well I said it all in the title. I’m an absolute beginner to Unity and I’m following the Brackeys tutorial on youtube and no matter how high I set the max distance in the inspector tab or in the actual code it only takes damage when its a zero with decimals as I said.
Any help would be much, much appreciated.
Thanks

Here’s the Code for the player:

#pragma strict

var TheDammage : int = 50;
var Distance : float;
var MaxDistance : float = 20.0;

function Update ()
{
	if (Input.GetButtonDown("Fire1"))
	{
		var hit : RaycastHit;
		if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), hit))
		{
			Distance = hit.distance;
			if (Distance < MaxDistance)
			{
				hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
			}
		}
	}
}

And for the Enemy:

#pragma strict

var Health = 100;

function ApplyDammage (TheDammage : int)
{
	Health -= TheDammage;
}

I haven't used hit.distance (wasn't even aware of it to be honest) so there might be something off about the way you are using it. For a test, try the more generic Distance = Vector3.Distance(hit.position,transform.position); if(Distance < ...

@getyour411, @supernat - If you don't specify a distance in the Raycast(), it uses Mathf.Infinity for the distance.

@robertbu - good call, I didn't think about the fact it uses infinity, but the only example in unity script passes a value in for depth and then uses the returned depth, so I would try it just to rule out any Unity oddity. I thought you might be getting the MaxDistance from the editor instead of the one in code too, actually that was my first thought, but you said you were changing it in the inspector. I would just make it private like robertbu said to rule it out. If you're using a prefab and you didn't update the value on the prefab, that could explain it as well.

2 Answers

2

You need to add a distance to the RayCast call (probably MaxDistance plus a little), after passing the parameter hit. Otherwise, it is likely limiting the returned distance to 1.0 since that is a unit vector magnitude.

I have an educated guess here. I’ll bet you are trying to change the distance by changing this line:

 var MaxDistance : float = 20.0;

Instance variables like this one are public by default. They appear in the Inspector. The initialized value (20 in this case) is only used at the time the script is attached to the game object. After that, only the value in the Inspector matters. So you can either change the value in the Inspector, or you can make this variable private:

private var MaxDistance : float = 20.0;

Private variables will not appear in the Inspector and will be initialized by the code in the script.