Hi,
Nobody seems to know the answer to this in this forum, is that really true? I want to check if a player that I’m hitting with raycast is dead, but my code doesn’t do that. It works perfectly in hit and spawn blood fx on hit and point system, but not to check a public bool on the person I hit. Here’s my code, I’ve commented out what I tried and where the problem occurs:
void Fire()
{
if(isenabled)
{
if (weaponData == null)
{
weaponData = gameObject.GetComponentInChildren<WeaponData>();
if (weaponData == null)
{
Debug.LogError("Did not find a WeaponData script on child object");
}
return;
}
if (cooldown > 0)
{
return;
}
Ray ray = new Ray(RootToShoot.transform.position, RootToShoot.transform.forward);
Transform hitTransform;
Vector3 hitPoint;
hitTransform = FindClosestHitObject(ray, out hitPoint);
if (hitTransform != null)
{
Debug.Log("We hit: " + hitTransform.name);
//First I check if the ray hits the player tagged "Sam" and I know this works because I debugged it:
if (hitTransform.gameObject.tag == "Sam" )
{
//Then I try to acces Sam's helath script and check if his boolean "dead" is true
//If it is, I turn the boolean on this script "shooter" to true, BUT it doesn't work.
if (hitTransform.GetComponent<Health>().dead)
{
shooter = true;
}
}
Transform FindClosestHitObject(Ray ray, out Vector3 hitpoint)
{
RaycastHit[] hits = Physics.RaycastAll(ray);
Transform closestHit = null;
float distance = 0f;
hitpoint = Vector3.zero;
foreach (RaycastHit hit in hits)
{
if(hit.transform != this.transform && (closestHit == null || hit.distance < distance))
{
//we have hit something that is not us:
//a: not us
//b: the first thing we hit that isn't us
closestHit = hit.transform;
distance = hit.distance;
hitpoint = hit.point;
}
}
//closest hit is now either null, or the closest thing that isn't us.
return closestHit;
}