Preface: I started with the Survival Shooter tutorial and added a ton of stuff. Here I’m trying to add a power-up that will shoot through every enemy in a line. I have put in a counter so later on when I want to tweak the power-ups I can select how many enemies should be shot through.
The problem: In the game and scene view I can see the Raycast (in the form of a line render implemented in the tutorial) pass through multiple enemies or even single ones and not return that it has hit. I have tested it by playing the game and shooting from different angles and ranges. It seems that the Raycast will hit the enemy about 50% or less of the time. This is in the PlayerShooting script.
The tutorial’s working code in C# that hits only 1 enemy at a time 100% of the time:
if (Physics.Raycast(shootRay, out shootHit, range, shootableMask))
{
//Debug.Log(shootHit.transform.name);
//Debug.Log(shootHit.transform.position);
// Get the enemy health script in order to apply damage.
// The thing that has been hit might not be an enemy.
EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();
// So first check if the script is empty or not, otherwise an error or crash will occur.
if (enemyHealth != null)
{
damagePerShot = Random.Range(damageMin, damageMax);
//Debug.Log(damagePerShot);
//Debug.Log(enemyHealth.transform);
// Damage done to an enemy causes the amount of damage done to be displayed on the canvas.
FloatingTextManager.CreateFloatingText("-" + damagePerShot.ToString() + " HP", enemyHealth.transform);
enemyHealth.TakeDamage(damagePerShot, shootHit.point);
}
// End the line render when the line hits an object.
gunLine.SetPosition(1, shootHit.point);
}
else
{
// Draw a line that's 100 units.
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
}
Testing non-working code in C# that hits all enemies in a line <50% of the time:
RaycastHit[] hits = Physics.RaycastAll(shootRay, range, shootableMask);
int i = 0;
while(i < hits.Length)
{
//Debug.Log(hits*.transform.name);*
EnemyHealth enemy = hits*.transform.GetComponent();*
//Debug.Log(enemy);
Debug.Log(hits*.point);*
if (enemy != null)
{
counter += 1;
gunLine.SetPosition(1, hits*.point);*
enemy.TakeDamage(damageMin, hits*.transform.position);*
}
else
{
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
return;
}
i++;
}
Debug.Log(counter);
counter = 0;
If you need more information or the entire script, please let me know. I’ve tried for a couple hours and nothing I’ve looked up or tried has worked.