RaycastAll better alternatives? Problem with my Lazer attack.

Hi folks!

I want to create an attack that is based on RaycastHits (Think of a laser shot that can affect several enemies.) and I’ve been able to do so via Physics,RaycastAll()! … But it makes the game freeze each time I am building the enemy list… Here is my piece of code:

if(myBulletType == BulletType.Laser)
{
		//First, let's see if the Raycast hits nothing
		if (!Physics.Raycast(theCrosshairRay, 160))
		{
			//If list of affected enemies is greater than 0, clear it
			if (raycastHitsToAffect.Count > 0)
				raycastHitsToAffect.Clear();
		}
		else //If you hit something...
		{
			//... Force the list to copy RaycastHits List
			raycastHitsToAffect = Physics.RaycastAll(theCrosshairRay, 160).Where (go => go.transform.tag == "Enemy" || go.transform.tag == "Neutral").ToList ();

			conAudioSource.PlayOneShot(hittenSound);

			//Loop in the targets
			for (int i = 0; i < raycastHitsToAffect.Count; i++)
			{
				//Modify the value 1 script at a time in the List
				scr_enemy enemyScript = raycastHitsToAffect*.collider.gameObject.GetComponent<scr_enemy>();*
  •  		//If valid (or not dead)*
    
  •  		if (enemyScript != null)*
    
  •  		{*
    
  •  			//If can take damage*
    
  •  			if (enemyScript.canTakeDamage)*
    
  •  			{*
    
  •  				enemyScript.hp -= rayHitDamage;*
    

_ enemyScript.Splat (raycastHitsToAffect*.point);_
_
}*_

* //If killed by player*
* if (enemyScript.hp <= 0)*
* {*
* enemyScript.killedByPlayer = true;*

* //Add Value*
* con.SetKillValues(enemyScript.myEnemyType);*
* }*
* }*
* }*
* }*
* }*
* //End of rayCasthits*
When I perform (the very similar) method for single hit bullet, the game is running perfectly! But when the List is build in this method… Glitch… :cry:
I need your experience to find another alternatives or to increase performance.
Thank you very much!

yeah, loop through the generated array from the raycast. I’d suggest not using LINQ to sort stuff up front. check in the for loop. continue if both tags are wrong. you iterate them twice already, once for sorting, once for execution. the for loop should be sufficient.