Chain Lightning Attack

G’Day
I am currently working on a project that has a chain lightning attack which jumps to targets at a certain distance.

So far I can instantiate the effect and scale depending on distance to the closest enemy.
The issue i have is making the effect now jump to the next closest target but I am unsure how to go about it.
Any help or examples will be appreciated
Heres an example of the effect im currently after.

I use C#

Kind Regards

Would you mind explaining how you created the lightning asset? Is it using a line renderer between the source and the target and scrolling a texture along it?

Preparation:

  1. Create a trigger sphere prefab
  2. Animate the sphere to scale up ( start from 0 to MaximumRange ), so the effect will strike the closest enemy first

Steps:

  1. Instantiate the trigger sphere when you hit a enemy, marked the enemy as hit
  2. Any enemy that is not hit that enters the trigger will struck by the lightning ( this is the one you have completed )
  3. Repeat step one for each enemy the lightning struck in step 2

Sample Script:

// LightningField.cs, Attach this to a trigger sphere
public class LightningField : MonoBehaviour {

   public float enemyRestruckDelay = 5f; 

   void OnTriggerEnter( Collider other ) {
      Enemy e = other.gameObject.GetComponent<Enemy>();

      if( e == null ) {  // It is not enemy
         return;
      }

      Hit h = other.gameObject.GetComponent<Hit>();
      
      if( h == null ) { // the enemy is yet to be hit

         //Call you lightning strike effect here
         ...

         //Create another copy of this lightning field, by doing this, it will start chaining when the condition is right
         Instantiate( gameObject, other.gameObject.transform.position, Quaternion.identity );

         //Mark the enemy as hit
         h = other.gameObject.AddComponent<Hit>();

         h.killDelay = enemyRestruckDelay;

         //Kill this gameObject once you have struck the closest enemy
         //Remove the Kill() if you want to strike everyone in the proximity
         Kill();
      }
   }

   //Call this using an animation event, just in case the sphere strike nothing at all
   void Kill() {
      Destroy(gameObject);
   }
}

// Hit.cs, Temporary script to mark a enemy that is just hit by lightning    
public class Hit : MonoBehaviour {
   public float killDelay = 3f;
   void Start() {
      //Destroy this component only after killDelay-second passed
      Destroy( this, killDelay ); 
   }
}

Quick Explanation

LightningField.cs

  • This is way from completed, you have to fill in the code to work with your current lightning strike
  • Kill() is called via animation event, at the end of the expansion of the sphere, you can use animation event to destroy the sphere.

Hit.cs

  • This script is used to mark an enemy, this state that the enemy is already in the lightning chain ( if this is not used, enemies will be re-struck by the same chain again )