1. Code
  2. Game Development

How to Generate Shockingly Good 2D Lightning Effects in Unity (C#)

There are plenty of uses for lightning effects in games, from background ambiance during a storm to the devastating lightning attacks of a sorcerer. In this tutorial, I'll explain how to use C# and Unity to programmatically generate awesome 2D lightning effects: bolts, branches, and even text.
Scroll to top

There are plenty of uses for lightning effects in games, from background ambiance during a storm to the devastating lightning attacks of a sorcerer. In this tutorial, I'll explain how to programmatically generate awesome 2D lightning effects: bolts, branches, and even text.

This tutorial is written specifically for Unity, with all code snippets in C#. The same tutorial is also available with JavaScript code. If you don't use Unity, take a look at this platform-agnostic version of the same tutorial; it's written for XNA, but you should be able to use the same techniques and concepts in any gamedev engine and platform.

Demo

Check out the demo below:

Click the Unity object, then use the number keys to switch between demos. Some demos require you to click in one or two locations to activate them.

Basic Setup

To get started, you'll need to create a new 2D project in Unity. Name it whatever you'd like. In Unity, create four folders: Materials, Prefabs, Scripts, and Sprites.

Next, click the Main Camera and make sure that its Projection is set to Orthographic. Set the camera's Size to 10.

Right-click on the Materials folder and select Create > Material. Rename it to Additive. Select this material and change its Shader to Particles > Additive. This will help your lightning "pop" later on.

Step 1: Draw a Glowing Line

The basic building block we need to make lightning from is a line segment. Start by opening your favourite image editing software and drawing a straight line of lightning with a glow effect. Here's what mine looks like:

We want to draw lines of different lengths, so we will cut the line segment into three pieces as shown below (crop your image as necessary). This will allow us to stretch the middle segment to any length we like. Since we are going to be stretching the middle segment, we can save it as only a single pixel thick. Also, as the left and right pieces are mirror images of each other, we only need to save one of them; we can flip it in the code.

Drag your image files onto the Sprites folder in the Project panel. This will import the image files into the Unity project. Click on the sprites to view them in the Inspector panel. Make sure the Texture Type is set to Sprite(2D \ uGUI), and set the Packing Tag to Line.  

The Packing Tag will help Unity save on draw calls when drawing our lightning, so make sure you give both sprites the same Packing Tag or else it won't improve performance.

Now, let's declare a new class to handle drawing line segments:

1
using UnityEngine;
2
using System.Collections;
3
4
public class Line : MonoBehaviour
5
{
6
    //Start

7
    public Vector2 A;
8
    
9
    //End

10
    public Vector2 B;
11
    
12
    //Thickness of line

13
    public float Thickness;
14
    
15
    //Children that contain the pieces that make up the line

16
    public GameObject StartCapChild, LineChild, EndCapChild;
17
    
18
    //Create a new line

19
    public Line(Vector2 a, Vector2 b, float thickness)
20
    {
21
        A = a;
22
        B = b;
23
        Thickness = thickness;
24
    }
25
    
26
    //Used to set the color of the line

27
    public void SetColor(Color color)
28
    {
29
        StartCapChild.GetComponent<SpriteRenderer>().color = color;
30
        LineChild.GetComponent<SpriteRenderer>().color = color;
31
        EndCapChild.GetComponent<SpriteRenderer>().color = color;
32
    }
33
34
    //...

35
}

A and B are the line's endpoints. By scaling and rotating the pieces of the line, we can draw a line of any thickness, length, and orientation. 

Add the following Draw() method to the bottom of the Line class:

1
//Will actually draw the line

2
public void Draw()
3
{
4
    Vector2 difference = B - A;
5
    float rotation = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
6
    
7
    //Set the scale of the line to reflect length and thickness

8
    LineChild.transform.localScale = new Vector3(100 * (difference.magnitude / LineChild.GetComponent<SpriteRenderer>().sprite.rect.width), 
9
                                                 Thickness, 
10
                                                 LineChild.transform.localScale.z);
11
    
12
    StartCapChild.transform.localScale = new Vector3(StartCapChild.transform.localScale.x, 
13
                                                     Thickness, 
14
                                                     StartCapChild.transform.localScale.z);
15
    
16
    EndCapChild.transform.localScale = new Vector3(EndCapChild.transform.localScale.x, 
17
                                                   Thickness, 
18
                                                   EndCapChild.transform.localScale.z);
19
    
20
    //Rotate the line so that it is facing the right direction

21
    LineChild.transform.rotation = Quaternion.Euler(new Vector3(0,0, rotation));
22
    StartCapChild.transform.rotation = Quaternion.Euler(new Vector3(0,0, rotation));
23
    EndCapChild.transform.rotation = Quaternion.Euler(new Vector3(0,0, rotation + 180));
24
    
25
    //Move the line to be centered on the starting point

26
    LineChild.transform.position = new Vector3 (A.x, A.y, LineChild.transform.position.z);
27
    StartCapChild.transform.position = new Vector3 (A.x, A.y, StartCapChild.transform.position.z);
28
    EndCapChild.transform.position = new Vector3 (A.x, A.y, EndCapChild.transform.position.z);
29
    
30
    //Need to convert rotation to radians at this point for Cos/Sin

31
    rotation *= Mathf.Deg2Rad;
32
    
33
    //Store these so we only have to access once

34
    float lineChildWorldAdjust = LineChild.transform.localScale.x * LineChild.GetComponent<SpriteRenderer>().sprite.rect.width / 2f;
35
    float startCapChildWorldAdjust = StartCapChild.transform.localScale.x * StartCapChild.GetComponent<SpriteRenderer>().sprite.rect.width / 2f;
36
    float endCapChildWorldAdjust = EndCapChild.transform.localScale.x * EndCapChild.GetComponent<SpriteRenderer>().sprite.rect.width / 2f;
37
    
38
    //Adjust the middle segment to the appropriate position

39
    LineChild.transform.position += new Vector3 (.01f * Mathf.Cos(rotation) * lineChildWorldAdjust, 
40
                                                 .01f * Mathf.Sin(rotation) * lineChildWorldAdjust,
41
                                                 0);
42
    
43
    //Adjust the start cap to the appropriate position

44
    StartCapChild.transform.position -= new Vector3 (.01f * Mathf.Cos(rotation) * startCapChildWorldAdjust, 
45
                                                     .01f * Mathf.Sin(rotation) * startCapChildWorldAdjust,
46
                                                     0);
47
    
48
    //Adjust the end cap to the appropriate position

49
    EndCapChild.transform.position += new Vector3 (.01f * Mathf.Cos(rotation) * lineChildWorldAdjust * 2, 
50
                                                   .01f * Mathf.Sin(rotation) * lineChildWorldAdjust * 2,
51
                                                   0);
52
    EndCapChild.transform.position += new Vector3 (.01f * Mathf.Cos(rotation) * endCapChildWorldAdjust, 
53
                                                   .01f * Mathf.Sin(rotation) * endCapChildWorldAdjust,
54
                                                   0);
55
}

The way we position the middle segment and the caps will make them join seamlessly when we draw them. The start cap is positioned at point A, the middle segment is stretched to the desired width, and the end cap is rotated 180° and drawn at point B.  

Now we need to create a prefab for our Line class to work with. In Unity, from the menu, select GameObject > Create Empty.  The object will appear in your Hierarchy panel. Rename it to Line and drag your Line script onto it.  It should look something like the image below. 

We'll use this object as a container for the pieces of our line segment.

Now we need to create objects for the pieces of our line segment. Create three Sprites by selecting GameObject > Create Other > Sprite from the menu. Rename them to StartCap, MiddleSegment, and EndCap. Drag them onto our Line object so that they become its children—this should look something like the image below.

Go through each child and set its Material in the Sprite Renderer to the Additive material we created earlier. Assign each child the appropriate sprite. (The two caps should get the cap sprite and the middle segment should get the line sprite.) 

Click on the Line object so that you can see the script in the Inspector panel.  Assign the children to their appropriate slots and then drag the Line object into the Prefabs folder to create a prefab for it.  You can now delete the Line object from the Hierarchy panel.

Step 2: Create Jagged Lines

Lightning tends to form jagged lines, so we'll need an algorithm to generate these. We'll do this by picking points at random along a line, and displacing them a random distance from the line. 

Using a completely random displacement tends to make the line too jagged, so we'll smooth the results by limiting how far from each other neighbouring points can be displaced—see the difference between the second and third lines in the figure below.

We smooth the line by placing points at a similar offset to the previous point; this allows the line as a whole to wander up and down, while preventing any part of it from being too jagged. 

Let's create a LightningBolt class to handle creating our jagged lines.

1
using UnityEngine;
2
using System.Collections.Generic;
3
4
class LightningBolt : MonoBehaviour
5
{
6
    //List of all of our active/inactive lines

7
    public List<GameObject> ActiveLineObj;
8
    public List<GameObject> InactiveLineObj;
9
    
10
    //Prefab for a line

11
    public GameObject LinePrefab;
12
    
13
    //Transparency

14
    public float Alpha { get; set; }
15
    
16
    //The speed at which our bolts will fade out

17
    public float FadeOutRate { get; set; }
18
    
19
    //The color of our bolts

20
    public Color Tint { get; set; }
21
    
22
    //The position where our bolt started

23
    public Vector2 Start { get { return ActiveLineObj[0].GetComponent<Line>().A; } }
24
    
25
    //The position where our bolt ended

26
    public Vector2 End { get { return ActiveLineObj[ActiveLineObj.Count-1].GetComponent<Line>().B; } }
27
    
28
    //True if the bolt has completely faded out

29
    public bool IsComplete { get { return Alpha <= 0; } }
30
    
31
    public void Initialize(int maxSegments)
32
    {
33
        //Initialize lists for pooling

34
        ActiveLineObj = new List<GameObject>();
35
        InactiveLineObj = new List<GameObject>();
36
        
37
        for(int i = 0; i < maxSegments; i++)
38
        {
39
            //instantiate from our Line Prefab

40
            GameObject line = (GameObject)GameObject.Instantiate(LinePrefab);
41
            
42
            //parent it to our bolt object

43
            line.transform.parent = transform;
44
            
45
            //set it inactive

46
            line.SetActive(false);
47
            
48
            //add it to our list

49
            InactiveLineObj.Add(line);
50
        }
51
    }
52
    
53
    public void ActivateBolt(Vector2 source, Vector2 dest, Color color, float thickness)
54
    {
55
        //Store tint

56
        Tint = color;
57
        
58
        //Store alpha

59
        Alpha = 1.5f;
60
        
61
        //Store fade out rate

62
        FadeOutRate = 0.03f;
63
        
64
        //actually create the bolt

65
        //Prevent from getting a 0 magnitude

66
        if(Vector2.Distance(dest, source) <= 0)
67
        {
68
            Vector2 adjust = Random.insideUnitCircle;
69
            if(adjust.magnitude <= 0) adjust.x += .1f;
70
            dest += adjust;
71
        }
72
        
73
        //difference from source to destination

74
        Vector2 slope = dest - source;
75
        Vector2 normal = (new Vector2(slope.y, -slope.x)).normalized;
76
        
77
        //distance between source and destination

78
        float distance = slope.magnitude;
79
        
80
        List<float> positions = new List<float>();
81
        positions.Add(0);
82
        
83
        for (int i = 0; i < distance / 4; i++) 
84
        {
85
            //Generate random positions between 0 and 1 to break up the bolt

86
            //positions.Add (Random.Range(0f, 1f));

87
            positions.Add (Random.Range(.25f, .75f));
88
        }
89
        
90
        positions.Sort();
91
        
92
        const float Sway = 80;
93
        const float Jaggedness = 1 / Sway;
94
        
95
        //Affects how wide the bolt is allowed to spread

96
        float spread = 1f;
97
        
98
        //Start at the source

99
        Vector2 prevPoint = source;
100
        
101
        //No previous displacement, so just 0

102
        float prevDisplacement = 0;
103
        
104
        for (int i = 1; i < positions.Count; i++)
105
        {
106
            //don't allow more than we have in the pool

107
            int inactiveCount = InactiveLineObj.Count;
108
            if(inactiveCount <= 0) break;
109
            
110
            float pos = positions[i];
111
            
112
            //used to prevent sharp angles by ensuring very close positions also have small perpendicular variation.

113
            float scale = (distance * Jaggedness) * (pos - positions[i - 1]);
114
            
115
            //defines an envelope. Points near the middle of the bolt can be further from the central line.

116
            float envelope = pos > 0.95f ? 20 * (1 - pos) : spread;
117
            
118
            float displacement = Random.Range(-Sway, Sway);
119
            displacement -= (displacement - prevDisplacement) * (1 - scale);
120
            displacement *= envelope;
121
            
122
            //Calculate the end point

123
            Vector2 point = source + (pos * slope) + (displacement * normal);
124
            
125
            activateLine(prevPoint, point, thickness);
126
            prevPoint = point;
127
            prevDisplacement = displacement;
128
        }
129
        
130
        activateLine(prevPoint, dest, thickness);
131
    }
132
    
133
    public void DeactivateSegments()
134
    {
135
        for(int i = ActiveLineObj.Count - 1; i >= 0; i--)
136
        {
137
            GameObject line = ActiveLineObj[i];
138
            line.SetActive(false);
139
            ActiveLineObj.RemoveAt(i);
140
            InactiveLineObj.Add(line);
141
        }
142
    }
143
    
144
    void activateLine(Vector2 A, Vector2 B, float thickness)
145
    {
146
        //get the inactive count

147
        int inactiveCount = InactiveLineObj.Count;
148
        
149
        //only activate if we can pull from inactive

150
        if(inactiveCount <= 0) return;
151
        
152
        //pull the GameObject

153
        GameObject line = InactiveLineObj[inactiveCount - 1];
154
        
155
        //set it active

156
        line.SetActive(true);
157
        
158
        //get the Line component

159
        Line lineComponent = line.GetComponent<Line>();
160
        lineComponent.SetColor(Color.white);
161
        lineComponent.A = A;
162
        lineComponent.B = B;
163
        lineComponent.Thickness = thickness;
164
        InactiveLineObj.RemoveAt(inactiveCount - 1);
165
        ActiveLineObj.Add(line);
166
    }
167
    
168
    public void Draw()
169
    {
170
        //if the bolt has faded out, no need to draw

171
        if (Alpha <= 0) return;
172
        
173
        foreach (GameObject obj in ActiveLineObj)
174
        {
175
            Line lineComponent = obj.GetComponent<Line>();
176
            lineComponent.SetColor(Tint * (Alpha * 0.6f));
177
            lineComponent.Draw();
178
        }
179
    }
180
    
181
    public void UpdateBolt()
182
    {
183
        Alpha -= FadeOutRate;
184
    }
185
    
186
    //...

187
}

The code may look a bit intimidating, but it's not so bad once you understand the logic. Before we continue on, understand that we've chosen to pool our line segments in the bolts (since constantly instantiating and destroying objects can be costly in Unity).

  • The Initialize() function will be called once on each lightning bolt and will determine how many line segments each bolt is allowed to use.
  • The activateLine() function will activate a line segment using the given position data.
  • The DeactivateSegments() function will deactivate any active line segments in our bolt.
  • The ActivateBolt() function will handle creating our jagged lines and will call the activateLine() function to activate our line segments at the appropriate positions.

To create our jagged lines, we start by computing the slope between our two points, as well as the normal vector to that slope. We then choose a number of random positions along the line and store them in our positions list. We scale these positions between 0 and 1, such that 0 represents the start of the line and 1 represents the end point., and then sort these positions to allow us to easily add line segments between them.

The loop goes through the randomly chosen points and displaces them along the normal by a random amount. The scale factor is there to avoid overly sharp angles, and the envelope ensures the lightning actually goes to the destination point by limiting displacement when we're close to the end. The spread is to assist in controlling how far the segments deviate from the slope of our line; a spread of 0 will essentially give you a straight line.

So, like we did with our Line class, let's make this into a prefab.  From the menu, select GameObject > Create Empty.  The object will appear in your Hierarchy panel. Rename it to Bolt, and drag a copy of the LightningBolt script onto it. Finally, click on the Bolt object and assign the Line prefab, from the Prefabs folder, to the appropriate slot in the LightningBolt script.  Once you're done with that, simply drag the Bolt object into the Prefabs folder to create a prefab.

Step 3: Add Animation

Lightning should flash brightly and then fade out.  This is what our Update() and Draw() functions in LightningBolt are for. Calling Update() will make the bolt fade out. Calling Draw() will update the bolt's color on the screen. IsComplete will tell you when the bolt has fully faded out.

Step 4: Create a Bolt

Now that we have our LightningBolt class, let's actually put it to good use and set up a quick demo scene.

We're going to use an object pool for this demo, so we'll want to create an empty object to hold our active and inactive bolts (simply for organizational purposes). In Unity, from the menu, select GameObject > Create Empty. The object will appear in your Hierarchy panel. Rename it to LightningPoolHolder.

Right click on the Scripts folder and select Create > C# Script.  Name your script DemoScript and open it.  Here's some quick code to get you started:

1
using UnityEngine;
2
using System.Collections;
3
using System.Collections.Generic;
4
5
public class DemoScript : MonoBehaviour 
6
{
7
    //Prefabs to be assigned in Editor

8
    public GameObject BoltPrefab;
9
    
10
    //For pooling

11
    List<GameObject> activeBoltsObj;
12
    List<GameObject> inactiveBoltsObj;
13
    int maxBolts = 1000;
14
    
15
    //For handling mouse clicks

16
    int clicks = 0;
17
    Vector2 pos1, pos2;
18
    
19
    void Start()
20
    {
21
        //Initialize lists

22
        activeBoltsObj = new List<GameObject>();
23
        inactiveBoltsObj = new List<GameObject>();
24
        
25
        //Grab the parent we'll be assigning to our bolt pool

26
        GameObject p = GameObject.Find("LightningPoolHolder");
27
        
28
        //For however many bolts we've specified

29
        for(int i = 0; i < maxBolts; i++)
30
        {
31
            //create from our prefab

32
            GameObject bolt = (GameObject)Instantiate(BoltPrefab);
33
            
34
            //Assign parent

35
            bolt.transform.parent = p.transform;
36
            
37
            //Initialize our lightning with a preset number of max sexments

38
            bolt.GetComponent<LightningBolt>().Initialize(25);
39
            
40
            //Set inactive to start

41
            bolt.SetActive(false);
42
            
43
            //Store in our inactive list

44
            inactiveBoltsObj.Add(bolt);
45
        }
46
    }
47
    
48
    void Update()
49
    {
50
        //Declare variables for use later

51
        GameObject boltObj;
52
        LightningBolt boltComponent;
53
        
54
        //store off the count for effeciency

55
        int activeLineCount = activeBoltsObj.Count;
56
        
57
        //loop through active lines (backwards because we'll be removing from the list)

58
        for (int i = activeLineCount - 1; i >= 0; i--)
59
        {
60
            //pull GameObject

61
            boltObj = activeBoltsObj[i];
62
            
63
            //get the LightningBolt component

64
            boltComponent = boltObj.GetComponent<LightningBolt>();
65
            
66
            //if the bolt has faded out

67
            if(boltComponent.IsComplete)
68
            {
69
                //deactive the segments it contains

70
                boltComponent.DeactivateSegments();
71
                
72
                //set it inactive

73
                boltObj.SetActive(false);
74
                
75
                //move it to the inactive list

76
                activeBoltsObj.RemoveAt(i);
77
                inactiveBoltsObj.Add(boltObj);
78
            }
79
        }
80
        
81
        //If left mouse button pressed

82
        if(Input.GetMouseButtonDown(0))
83
        {
84
        	//if first click

85
        	if(clicks == 0)
86
        	{
87
                //store starting position

88
                Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
89
                pos1 = new Vector2(temp.x, temp.y);
90
        	}
91
        	else if(clicks == 1) //second click

92
        	{
93
                //store end position

94
                Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
95
                pos2 = new Vector2(temp.x, temp.y);
96
                
97
                //create a (pooled) bolt from pos1 to pos2

98
                CreatePooledBolt(pos1,pos2, Color.white, 1f);
99
        	}
100
        	
101
        	//increment our tick count

102
        	clicks++;
103
        	
104
        	//restart the count after 2 clicks

105
        	if(clicks > 1) clicks = 0;
106
        }
107
        
108
        //update and draw active bolts

109
        for(int i = 0; i < activeBoltsObj.Count; i++)
110
        {
111
            activeBoltsObj[i].GetComponent<LightningBolt>().UpdateBolt();
112
            activeBoltsObj[i].GetComponent<LightningBolt>().Draw();
113
        }
114
    }
115
        
116
        void CreatePooledBolt(Vector2 source, Vector2 dest, Color color, float thickness)
117
        {
118
        //if there is an inactive bolt to pull from the pool

119
        if(inactiveBoltsObj.Count > 0)
120
        {
121
        	//pull the GameObject

122
        	GameObject boltObj = inactiveBoltsObj[inactiveBoltsObj.Count - 1];
123
        	
124
        	//set it active

125
        	boltObj.SetActive(true);
126
        	
127
        	//move it to the active list

128
        	activeBoltsObj.Add(boltObj);
129
        	inactiveBoltsObj.RemoveAt(inactiveBoltsObj.Count - 1);
130
        	
131
        	//get the bolt component

132
        	LightningBolt boltComponent =  boltObj.GetComponent<LightningBolt>();
133
        	
134
        	//activate the bolt using the given position data

135
        	boltComponent.ActivateBolt(source, dest, color, thickness);
136
        }
137
    }
138
}

All this code does is give us a way to create bolts using object pooling. There are other ways you can set this up, but this is what we're going with! Once we've set it up, all you'll have to do is click twice to create a bolt on the screen: once for the start position and once for the end position.

We'll need an object to put our DemoScript on.  From the menu, select GameObject > Create Empty.  The object will appear in your Hierarchy panel.  Rename it to DemoScript and drag your DemoScript script onto it.  Click on the DemoScript object so we can view it in the Inspector panel. Assign the Bolt prefab, from the Prefabs folder, to the matching slot in the DemoScript.

That should be enough to get you going!  Run the scene in Unity and try it out!

Step 5: Create Branch Lightning

You can use the LightningBolt class as a building block to create more interesting lightning effects. For example, you can make the bolts branch out as shown below:

To make the lightning branch, we pick random points along the lightning bolt and add new bolts that branch out from these points. In the code below, we create between three and six branches which separate from the main bolt at 30° angles.

1
using UnityEngine;
2
using System.Collections.Generic;
3
4
class BranchLightning : MonoBehaviour
5
{
6
    //For holding all of our bolts in our branch

7
    List<GameObject> boltsObj = new List<GameObject>();
8
    
9
    //If there are no bolts, then the branch is complete (we're not pooling here, but you could if you wanted)

10
    public bool IsComplete { get { return boltsObj.Count == 0; } }
11
    
12
    //Start position of branch

13
    public Vector2 Start { get; private set; }
14
    
15
    //End position of branch

16
    public Vector2 End { get; private set; }
17
    
18
    static Random rand = new Random();
19
    
20
    public void Initialize(Vector2 start, Vector2 end, GameObject boltPrefab)
21
    {
22
        //store start and end positions

23
        Start = start;
24
        End = end;
25
        
26
        //create the  main bolt from our bolt prefab

27
        GameObject mainBoltObj = (GameObject)GameObject.Instantiate(boltPrefab);
28
        
29
        //get the LightningBolt component

30
        LightningBolt mainBoltComponent = mainBoltObj.GetComponent<LightningBolt>();
31
        
32
        //initialize our bolt with a max of 5 segments

33
        mainBoltComponent.Initialize(5);
34
        
35
        //activate the bolt with our position data

36
        mainBoltComponent.ActivateBolt(start, end, Color.white, 1f);
37
        
38
        //add it to our list

39
        boltsObj.Add(mainBoltObj);
40
        
41
        //randomly determine how many sub branches there will be (3-6)

42
        int numBranches = Random.Range(3,6);
43
        
44
        //calculate the difference between our start and end points

45
        Vector2 diff = end - start;
46
        
47
        // pick a bunch of random points between 0 and 1 and sort them

48
        List<float> branchPoints = new List<float>();
49
        for(int i = 0; i < numBranches; i++) branchPoints.Add(Random.value);
50
        branchPoints.Sort();
51
        
52
        //go through those points

53
        for (int i = 0; i < branchPoints.Count; i++)
54
        {
55
            // Bolt.GetPoint() gets the position of the lightning bolt based on the percentage passed in (0 = start of bolt, 1 = end)

56
            Vector2 boltStart = mainBoltComponent.GetPoint(branchPoints[i]);
57
            
58
            //get rotation of 30 degrees. Alternate between rotating left and right. (i & 1 will be true for all odd numbers...yay bitwise operators!)

59
            Quaternion rot = Quaternion.AngleAxis(30 * ((i & 1) == 0 ? 1 : -1), new Vector3(0,0,1));
60
            
61
            //calculate how much to adjust for our end position

62
            Vector2 adjust = rot * (Random.Range(.5f, .75f) * diff * (1 - branchPoints[i]));
63
            
64
            //get the end position

65
            Vector2 boltEnd = adjust + boltStart;
66
            
67
            //instantiate from our bolt prefab

68
            GameObject boltObj = (GameObject)GameObject.Instantiate(boltPrefab);
69
            
70
            //get the LightningBolt component

71
            LightningBolt boltComponent = boltObj.GetComponent<LightningBolt>();
72
            
73
            //initialize our bolt with a max of 5 segments

74
            boltComponent.Initialize(5);
75
            
76
            //activate the bolt with our position data

77
            boltComponent.ActivateBolt(boltStart, boltEnd, Color.white, 1f);
78
            
79
            //add it to the list

80
            boltsObj.Add(boltObj);
81
        }
82
    }
83
    
84
    public void UpdateBranch()
85
    {
86
    	//go through our active bolts

87
    	for (int i = boltsObj.Count - 1; i >= 0; i--)
88
    	{
89
            //get the GameObject

90
            GameObject boltObj = boltsObj[i];
91
            
92
            //get the LightningBolt component

93
            LightningBolt boltComp = boltObj.GetComponent<LightningBolt>();
94
            
95
            //update/fade out the bolt

96
            boltComp.UpdateBolt();
97
            
98
            //if the bolt has faded

99
            if(boltComp.IsComplete)
100
            {
101
                //remove it from our list

102
                boltsObj.RemoveAt(i);
103
                
104
                //destroy it (would be better to pool but I'll let you figure out how to do that =P)

105
                Destroy(boltObj);
106
            }
107
    	}
108
    }
109
    
110
    //Draw our active bolts on screen

111
    public void Draw()
112
    {
113
        foreach (GameObject boltObj in boltsObj)
114
        {
115
            boltObj.GetComponent<LightningBolt>().Draw();
116
        }
117
    }
118
}

This code works very similarly to our LightningBolt class with the exception that it does not use object pooling. Calling Initialize() is all you will need to do to create a branching bolt; after that, you will just need to call Update() and Draw(). I'll show you exactly how to do this in our DemoScript later on in the tutorial.

You may have noticed the reference to a GetPoint() function in the LightningBolt class.  We haven't actually implemented that function yet, so let's take care of that now.  

Add the following function in the bottom of the LightningBolt class:

1
// Returns the point where the bolt is at a given fraction of the way through the bolt. Passing

2
// zero will return the start of the bolt, and passing 1 will return the end.

3
public Vector2 GetPoint(float position)
4
{
5
    Vector2 start = Start;
6
    float length = Vector2.Distance(start, End);
7
    Vector2 dir = (End - start) / length;
8
    position *= length;
9
    
10
    //find the appropriate line

11
    Line line = ActiveLineObj.Find(x => Vector2.Dot(x.GetComponent<Line>().B - start, dir) >= position).GetComponent<Line>();
12
    float lineStartPos = Vector2.Dot(line.A - start, dir);
13
    float lineEndPos = Vector2.Dot(line.B - start, dir);
14
    float linePos = (position - lineStartPos) / (lineEndPos - lineStartPos);
15
    
16
    return Vector2.Lerp(line.A, line.B, linePos);
17
}

Step 6: Create Lightning Text

Below is a video of another effect you can make out of the lightning bolts:

Please accept marketing cookies to load this content.

We'll need to do a little more setup for this one. First, from the Project panel, select Create > RenderTexture. Rename it to RenderText and set its Size to 256x256px. (It doesn't necessarily have to be that exact size, but the smaller it is, the faster the program will run.)

From the menu, select Edit > Project Settings > Tags and Layers. Then, in the Inspector panel, expand the Layers drop down and add Text into User Layer 8.

We'll then need to create a second camera. From the menu, select GameObject > Create Other > Camera. Rename it to TextCamera, and set its Projection to Orthographic and its Clear Flags to Solid Color. Set its Background color to (R: 0, G: 0, B: 0, A: 0) and set its Culling Mask to only be Text (the layer we just created). Finally, set its Target Texture to RenderText (the RenderTexture we created earlier). You'll probably need to play around with the camera's Size later, in order to get everything to fit on the screen.

Now we'll need to create the actual text we'll be drawing with our lightning.  From the menu select GameObject > Create Other > GUI Text.  Select the GUI Text object from the Hierarchy panel and set its Text to LIGHTNING, its Anchor to middle center, and its Alignment to center. Then, set its Layer to the Text layer we created earlier. You'll probably have to play around with the Font Size in order to fit the text on the screen.

Now select the Main Camera and set its Culling Mask to be everything but our Text layer. This will cause our GUI Text to apparently disappear from the screen, but it should be drawn on the RenderTexture we created earlier: select RenderText from the Project panel and you should be able to see the word LIGHTNING on the preview on the bottom of the panel. 

If you can't see the word LIGHTNING, you'll need to play around with your positioning, font size, and (text) camera size. To help you position your text, click on TextCamera in the Hierarchy panel, and set its Target Texture to None. You'll now be able to see your GUI Text if you center it on the TextCamera. Once you have everything positioned, set the TextCamera's Target Texture back to RenderText.

Now for the code! We'll need to get the pixels from the text that we're drawing. We can do this by drawing our text to a RenderTarget and reading back the pixel data into a Texture2D with Texture2D.ReadPixels(). Then, we can store the coordinates of the pixels from the text as a List<Vector2>

Here's the code to do that:

1
//Capture the important points of our text for later

2
IEnumerator TextCapture()
3
{
4
    //must wait until end of frame so something is actually drawn or else it will error

5
    yield return new WaitForEndOfFrame();
6
    
7
    //get the camera that draws our text

8
    Camera cam = GameObject.Find("TextCamera").GetComponent<Camera>();
9
    
10
    //make sure it has an assigned RenderTexture

11
    if(cam.targetTexture != null) 
12
    {
13
        //pull the active RenderTexture

14
        RenderTexture.active = cam.targetTexture;
15
        
16
        //capture the image into a Texture2D

17
        Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
18
        image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
19
        image.Apply();
20
        
21
        //calculate how the text will be scaled when it is displayed as lightning on the screen

22
        scaleText = 1 / (cam.ViewportToWorldPoint(new Vector3(1,0,0)).x - cam.ViewportToWorldPoint(Vector3.zero).x);
23
        
24
        //calculate how the text will be positioned when it is displayed as lightning on the screen (centered)

25
        positionText.x -= image.width * scaleText * .5f;
26
        positionText.y -= image.height * scaleText * .5f;
27
        
28
        //basically determines how many pixels we skip/check

29
        const int interval = 2;
30
        
31
        //loop through pixels

32
        for(int y = 0; y < image.height; y += interval)
33
        {
34
            for(int x = 0; x < image.width; x += interval)
35
            {
36
                //get the color of the pixel

37
                Color color = image.GetPixel(x,y);
38
                
39
                //if the color has any r (red) value

40
                if(color.r > 0)
41
                {
42
                    //add it to our points for drawing

43
                    textPoints.Add(new Vector2(x,y));
44
                }
45
            }
46
        }
47
    }
48
}

Note: We'll have to run this function as a Coroutine at the start of our program in order for it to run correctly.

After that, each frame, we can randomly pick pairs of these points and create a lightning bolt between them. We want to design it so that the closer two points are to one another, the greater the chance is that we create a bolt between them. 

There's a simple technique we can use to accomplish this: we'll pick the first point at random, and then we'll pick a fixed number of other points at random and choose the nearest.  

Here's the code for that (we'll add it to our DemoScript later):

1
//go through the points we capture earlier

2
foreach (Vector2 point in textPoints)
3
{
4
    //randomly ignore certain points

5
    if(Random.Range(0,75) != 0) continue;
6
    
7
    //placeholder values

8
    Vector2 nearestParticle = Vector2.zero;
9
    float nearestDistSquared = float.MaxValue;
10
    
11
    for (int i = 0; i < 50; i++)
12
    {
13
        //select a random point

14
        Vector2 other = textPoints[Random.Range(0, textPoints.Count)];
15
        
16
        //calculate the distance (squared for performance benefits) between the two points

17
        float distSquared = DistanceSquared(point, other);
18
        
19
        //If this point is the nearest point (but not too near!)

20
        if (distSquared < nearestDistSquared && distSquared > 3 * 3)
21
        {
22
            //store off the data

23
            nearestDistSquared = distSquared;
24
            nearestParticle = other;
25
        }
26
    }
27
    
28
    //if the point we found isn't too near/far

29
    if (nearestDistSquared < 25 * 25 && nearestDistSquared > 3 * 3)
30
    {
31
        //create a (pooled) bolt at the corresponding screen position

32
        CreatePooledBolt((point * scaleText) + positionText, (nearestParticle * scaleText) + positionText, new Color(Random.value,Random.value,Random.value,1f), 1f);
33
    }
34
}
35
36
/* The code above uses the following function 

37
 * It'll need to be placed appropriately

38
--------------------------------------------- 

39
//calculate distance squared (no square root = performance boost)

40
public float DistanceSquared(Vector2 a, Vector2 b)

41
{

42
    return ((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));

43
}

44
---------------------------------------------*/

The number of candidate points we test will affect the look of the lightning text; checking a larger number of points will allow us to find very close points to draw bolts between, which will make the text very neat and legible, but with fewer long lightning bolts between letters. Smaller numbers will make the lightning text look wilder but less legible.

Step 7: Try Other Variations

We've discussed making branch lightning and lightning text, but those certainly aren't the only effects you can make. Let's look at a couple other variations on lightning you may want to use.

Moving Lightning

You may often want to make a moving bolt of lightning. You can do this by adding a new short bolt each frame at the end point of the previous frame's bolt.

1
//Will contain all of the pieces for the moving bolt

2
List<GameObject> movingBolt = new List<GameObject>();
3
4
//used for actually moving the moving bolt

5
Vector2 lightningEnd = new Vector2(100, 100);
6
Vector2 lightningVelocity = new Vector2(1, 0);
7
8
void Update()
9
{
10
    //loop through all of our bolts that make up the moving bolt

11
    for(int i = movingBolt.Count - 1; i >= 0; i--)
12
    {
13
        //get the bolt component

14
        boltComponent = movingBolt[i].GetComponent<LightningBolt>();
15
        
16
        //if the bolt has faded out

17
        if(boltComponent.IsComplete)
18
        {
19
            //destroy it

20
            Destroy(movingBolt[i]);
21
            
22
            //remove it from our list

23
            movingBolt.RemoveAt(i);
24
            
25
            //on to the next one, on on to the next one

26
            continue;
27
        }
28
        
29
        //update and draw bolt

30
        boltComponent.UpdateBolt();
31
        boltComponent.Draw();
32
    }
33
34
    //if our moving bolt is active

35
    if(movingBolt.Count > 0)
36
    {
37
        //calculate where it currently ends

38
        lightningEnd = movingBolt[movingBolt.Count-1].GetComponent<LightningBolt>().End;
39
        
40
        //if the end of the bolt is within 25 units of the camera

41
        if(Vector2.Distance(lightningEnd,(Vector2)Camera.main.transform.position) < 25)
42
        {
43
            //instantiate from our bolt prefab

44
            boltObj = (GameObject)GameObject.Instantiate(BoltPrefab);
45
            
46
            //get the bolt component

47
            boltComponent = boltObj.GetComponent<LightningBolt>();
48
            
49
            //initialize it with a maximum of 5 segments

50
            boltComponent.Initialize(5);
51
            
52
            //activate the bolt using our position data (from the current end of our moving bolt to the current end + velocity) 

53
            boltComponent.ActivateBolt(lightningEnd,lightningEnd + lightningVelocity, Color.white, 1f);
54
            
55
            //add it to our list

56
            movingBolt.Add(boltObj);
57
            
58
            //update and draw our new bolt

59
            boltComponent.UpdateBolt();
60
            boltComponent.Draw();
61
        }
62
    }
63
}

Burst Lightning

This variation offers a dramatic effect that shoots lightning out in a circle from the centre point:

1
Vector2 diff = pos2 - pos1;
2
    				
3
void Update()
4
{
5
    //define how many bolts we want in our circle

6
    int boltsInBurst = 10;
7
    
8
    for(int i = 0; i < boltsInBurst; i++)
9
    {
10
        //rotate around the z axis to the appropriate angle

11
        Quaternion rot = Quaternion.AngleAxis((360f/boltsInBurst) * i, new Vector3(0,0,1));
12
        
13
        //Calculate the end position for the bolt

14
        Vector2 boltEnd = (Vector2)(rot * diff) + pos1;
15
        
16
        //create a (pooled) bolt from pos1 to boltEnd

17
        CreatePooledBolt(pos1, boltEnd, Color.white, 1f);
18
    }
19
}

Step 8: Put It All Together in DemoScript

You're going to want to be able to try out all of these fancy effects we've created so far, so let's put all of them into the DemoScript we made earlier.  You'll be able to toggle between effects by hitting the number keys on your keyboard to select the effect, and then just clicking twice like we did with our bolts before. 

Here's the full code: 

1
using UnityEngine;
2
using System.Collections;
3
using System.Collections.Generic;
4
5
public class DemoScript : MonoBehaviour 
6
{
7
    //Prefabs to be assigned in Editor

8
    public GameObject BoltPrefab;
9
    public GameObject BranchPrefab;
10
    
11
    //For pooling

12
    List<GameObject> activeBoltsObj;
13
    List<GameObject> inactiveBoltsObj;
14
    int maxBolts = 1000;
15
    
16
    float scaleText;
17
    Vector2 positionText;
18
    
19
    //Different modes for the demo

20
    enum Mode : byte
21
    {
22
        bolt,
23
        branch,
24
        moving,
25
        text,
26
        nodes,
27
        burst
28
    }
29
    
30
    //The current mode the demo is in

31
    Mode currentMode = Mode.bolt;
32
    
33
    //Will contain all of the pieces for the moving bolt

34
    List<GameObject> movingBolt = new List<GameObject>();
35
    
36
    //used for actually moving the moving bolt

37
    Vector2 lightningEnd = new Vector2(100, 100);
38
    Vector2 lightningVelocity = new Vector2(1, 0);
39
    
40
    //Will contain all of the pieces for the branches

41
    List<GameObject> branchesObj;
42
    
43
    //For handling mouse clicks

44
    int clicks = 0;
45
    Vector2 pos1, pos2;
46
    
47
    //For storing all of the pixels that need to be drawn by the bolts 

48
    List<Vector2> textPoints = new List<Vector2>();
49
    
50
    //true in text mode

51
    bool shouldText = false;
52
    
53
    void Start()
54
    {
55
        //Initialize lists

56
        activeBoltsObj = new List<GameObject>();
57
        inactiveBoltsObj = new List<GameObject>();
58
        branchesObj = new List<GameObject>();
59
        
60
        //Grab the parent we'll be assigning to our bolt pool

61
        GameObject p = GameObject.Find("LightningPoolHolder");
62
        
63
        //For however many bolts we've specified

64
        for(int i = 0; i < maxBolts; i++)
65
        {
66
            //create from our prefab

67
            GameObject bolt = (GameObject)Instantiate(BoltPrefab);
68
            
69
            //Assign parent

70
            bolt.transform.parent = p.transform;
71
            
72
            //Initialize our lightning with a preset number of max sexments

73
            bolt.GetComponent<LightningBolt>().Initialize(25);
74
            
75
            //Set inactive to start

76
            bolt.SetActive(false);
77
            
78
            //Store in our inactive list

79
            inactiveBoltsObj.Add(bolt);
80
        }
81
        
82
        //Start up a coroutine to capture the pixels we'll be drawing from our text (need the coroutine or error)

83
        StartCoroutine(TextCapture());
84
    }
85
    
86
    void Update()
87
    {
88
        //Declare variables for use later

89
        GameObject boltObj;
90
        LightningBolt boltComponent;
91
        
92
        //store off the count for effeciency

93
        int activeLineCount = activeBoltsObj.Count;
94
        
95
        //loop through active lines (backwards because we'll be removing from the list)

96
        for (int i = activeLineCount - 1; i >= 0; i--)
97
        {
98
            //pull GameObject

99
            boltObj = activeBoltsObj[i];
100
            
101
            //get the LightningBolt component

102
            boltComponent = boltObj.GetComponent<LightningBolt>();
103
            
104
            //if the bolt has faded out

105
            if(boltComponent.IsComplete)
106
            {
107
                //deactive the segments it contains

108
                boltComponent.DeactivateSegments();
109
                
110
                //set it inactive

111
                boltObj.SetActive(false);
112
                
113
                //move it to the inactive list

114
                activeBoltsObj.RemoveAt(i);
115
                inactiveBoltsObj.Add(boltObj);
116
            }
117
        }
118
        
119
        //check for key press and set mode accordingly

120
        if(Input.GetKeyDown(KeyCode.Alpha1) || Input.GetKeyDown(KeyCode.Keypad1))
121
        {
122
            shouldText = false;
123
            currentMode = Mode.bolt;
124
        }
125
        else if(Input.GetKeyDown(KeyCode.Alpha2) || Input.GetKeyDown(KeyCode.Keypad2))
126
        {
127
            shouldText = false;
128
            currentMode = Mode.branch;
129
        }
130
        else if(Input.GetKeyDown(KeyCode.Alpha3) || Input.GetKeyDown(KeyCode.Keypad3))
131
        {
132
            shouldText = false;
133
            currentMode = Mode.moving;
134
        }
135
        else if(Input.GetKeyDown(KeyCode.Alpha4) || Input.GetKeyDown(KeyCode.Keypad4))
136
        {
137
            shouldText = true;
138
            currentMode = Mode.text;
139
        }
140
        else if(Input.GetKeyDown(KeyCode.Alpha5) || Input.GetKeyDown(KeyCode.Keypad5))
141
        {
142
            shouldText = false;
143
            currentMode = Mode.nodes;
144
        }
145
        else if(Input.GetKeyDown(KeyCode.Alpha6) || Input.GetKeyDown(KeyCode.Keypad6))
146
        {
147
            shouldText = false;
148
            currentMode = Mode.burst;
149
        }
150
        
151
        //If left mouse button pressed

152
        if(Input.GetMouseButtonDown(0))
153
        {
154
            //if first click

155
            if(clicks == 0)
156
            {
157
                //store starting position

158
                Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
159
                pos1 = new Vector2(temp.x, temp.y);
160
            }
161
            else if(clicks == 1) //second click

162
            {
163
                //store end position

164
                Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
165
                pos2 = new Vector2(temp.x, temp.y);
166
                
167
                //Handle the current mode appropriately

168
                switch (currentMode)
169
                {
170
                    case Mode.bolt:
171
                    	//create a (pooled) bolt from pos1 to pos2

172
                    	CreatePooledBolt(pos1,pos2, Color.white, 1f);
173
                    break;
174
                    
175
                    case Mode.branch:
176
                    	//instantiate from our branch prefab

177
                    	GameObject branchObj = (GameObject)GameObject.Instantiate(BranchPrefab);
178
                    	
179
                    	//get the branch component

180
                    	BranchLightning branchComponent = branchObj.GetComponent<BranchLightning>();
181
                    
182
                    	//initialize the branch component using our position data

183
                    	branchComponent.Initialize(pos1, pos2, BoltPrefab);
184
                    
185
                    	//add it to the list of active branches

186
                    	branchesObj.Add(branchObj);
187
                    break;
188
                    
189
                    case Mode.moving:
190
                    	//Prevent from getting a 0 magnitude (0 causes errors 

191
                    	if(Vector2.Distance(pos1, pos2) <= 0)
192
                    	{
193
                            //Try a random position

194
                            Vector2 adjust = Random.insideUnitCircle;
195
                            
196
                            //failsafe

197
                            if(adjust.magnitude <= 0) adjust.x += .1f;
198
                            
199
                            //Adjust the end position

200
                            pos2 += adjust;
201
                    	}
202
                    
203
                    	//Clear out any old moving bolt (this is designed for one moving bolt at a time)

204
                    	for(int i = movingBolt.Count - 1; i >= 0; i--)
205
                    	{
206
                            Destroy(movingBolt[i]);
207
                            movingBolt.RemoveAt(i);
208
                    	}
209
                    	
210
                    	//get the "velocity" so we know what direction to send the bolt in after initial creation

211
                    	lightningVelocity = (pos2 - pos1).normalized;
212
                    
213
                    	//instantiate from our bolt prefab

214
                    	boltObj = (GameObject)GameObject.Instantiate(BoltPrefab);
215
                    	
216
                    	//get the bolt component

217
                    	boltComponent = boltObj.GetComponent<LightningBolt>();
218
                    
219
                    	//initialize it with 5 max segments

220
                    	boltComponent.Initialize(5);
221
                    	
222
                    	//activate the bolt using our position data

223
                    	boltComponent.ActivateBolt(pos1, pos2, Color.white, 1f);
224
                    
225
                    	//add it to our list

226
                    	movingBolt.Add(boltObj);
227
                    break;
228
                    
229
                    case Mode.burst:
230
                    	//get the difference between our two positions (destination - source = vector from source to destination)

231
                    	Vector2 diff = pos2 - pos1;
232
                    	
233
                    	//define how many bolts we want in our circle

234
                    	int boltsInBurst = 10;
235
                    
236
                    	for(int i = 0; i < boltsInBurst; i++)
237
                    	{
238
                            //rotate around the z axis to the appropriate angle

239
                            Quaternion rot = Quaternion.AngleAxis((360f/boltsInBurst) * i, new Vector3(0,0,1));
240
                            
241
                            //Calculate the end position for the bolt

242
                            Vector2 boltEnd = (Vector2)(rot * diff) + pos1;
243
                            
244
                            //create a (pooled) bolt from pos1 to boltEnd

245
                            CreatePooledBolt(pos1, boltEnd, Color.white, 1f);
246
                    	}
247
                    
248
                    break;
249
                }
250
            }
251
        
252
            //increment our tick count

253
            clicks++;
254
            
255
            //restart the count after 2 clicks

256
            if(clicks > 1) clicks = 0;
257
        }
258
        
259
        //if in node mode

260
        if(currentMode == Mode.nodes)
261
        {
262
            //constantly create a (pooled) bolt between the two assigned positions

263
            CreatePooledBolt(pos1, pos2, Color.white, 1f);
264
        }
265
        
266
        //loop through any active branches

267
        for(int i = branchesObj.Count - 1; i >= 0; i--)
268
        {
269
            //pull the branch lightning component

270
            BranchLightning branchComponent = branchesObj[i].GetComponent<BranchLightning>();
271
            
272
            //If it's faded out already

273
            if(branchComponent.IsComplete)
274
            {
275
                //destroy it

276
                Destroy(branchesObj[i]);
277
                
278
                //take it out of our list

279
                branchesObj.RemoveAt(i);
280
                
281
                //move on to the next branch

282
                continue;
283
            }
284
            
285
            //draw and update the branch

286
            branchComponent.UpdateBranch();
287
            branchComponent.Draw();
288
        }
289
        
290
        //loop through all of our bolts that make up the moving bolt

291
        for(int i = movingBolt.Count - 1; i >= 0; i--)
292
        {
293
            //get the bolt component

294
            boltComponent = movingBolt[i].GetComponent<LightningBolt>();
295
            
296
            //if the bolt has faded out

297
            if(boltComponent.IsComplete)
298
            {
299
                //destroy it

300
                Destroy(movingBolt[i]);
301
                
302
                //remove it from our list

303
                movingBolt.RemoveAt(i);
304
                
305
                //on to the next one, on on to the next one

306
                continue;
307
            }
308
            
309
            //update and draw bolt

310
            boltComponent.UpdateBolt();
311
            boltComponent.Draw();
312
        }
313
        
314
        //if our moving bolt is active

315
        if(movingBolt.Count > 0)
316
        {
317
            //calculate where it currently ends

318
            lightningEnd = movingBolt[movingBolt.Count-1].GetComponent<LightningBolt>().End;
319
            
320
            //if the end of the bolt is within 25 units of the camera

321
            if(Vector2.Distance(lightningEnd,(Vector2)Camera.main.transform.position) < 25)
322
            {
323
                //instantiate from our bolt prefab

324
                boltObj = (GameObject)GameObject.Instantiate(BoltPrefab);
325
                
326
                //get the bolt component

327
                boltComponent = boltObj.GetComponent<LightningBolt>();
328
                
329
                //initialize it with a maximum of 5 segments

330
                boltComponent.Initialize(5);
331
                
332
                //activate the bolt using our position data (from the current end of our moving bolt to the current end + velocity) 

333
                boltComponent.ActivateBolt(lightningEnd,lightningEnd + lightningVelocity, Color.white, 1f);
334
                
335
                //add it to our list

336
                movingBolt.Add(boltObj);
337
                
338
                //update and draw our new bolt

339
                boltComponent.UpdateBolt();
340
                boltComponent.Draw();
341
            }
342
        }
343
        
344
        //if in text mode

345
        if(shouldText)
346
        {
347
            //go through the points we capture earlier

348
            foreach (Vector2 point in textPoints)
349
            {
350
                //randomly ignore certain points

351
                if(Random.Range(0,75) != 0) continue;
352
                
353
                //placeholder values

354
                Vector2 nearestParticle = Vector2.zero;
355
                float nearestDistSquared = float.MaxValue;
356
                
357
                for (int i = 0; i < 50; i++)
358
                {
359
                    //select a random point

360
                    Vector2 other = textPoints[Random.Range(0, textPoints.Count)];
361
                    
362
                    //calculate the distance (squared for performance benefits) between the two points

363
                    float distSquared = DistanceSquared(point, other);
364
                    
365
                    //If this point is the nearest point (but not too near!)

366
                    if (distSquared < nearestDistSquared && distSquared > 3 * 3)
367
                    {
368
                        //store off the data

369
                        nearestDistSquared = distSquared;
370
                        nearestParticle = other;
371
                    }
372
                }
373
                
374
                //if the point we found isn't too near/far

375
                if (nearestDistSquared < 25 * 25 && nearestDistSquared > 3 * 3)
376
                {
377
                    //create a (pooled) bolt at the corresponding screen position

378
                    CreatePooledBolt((point * scaleText) + positionText, (nearestParticle * scaleText) + positionText, new Color(Random.value,Random.value,Random.value,1f), 1f);
379
                }
380
            }
381
        }
382
        
383
        //update and draw active bolts

384
        for(int i = 0; i < activeBoltsObj.Count; i++)
385
        {
386
            activeBoltsObj[i].GetComponent<LightningBolt>().UpdateBolt();
387
            activeBoltsObj[i].GetComponent<LightningBolt>().Draw();
388
        }
389
    }
390
    
391
    //calculate distance squared (no square root = performance boost)

392
    public float DistanceSquared(Vector2 a, Vector2 b)
393
    {
394
        return ((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
395
    }
396
    
397
    void CreatePooledBolt(Vector2 source, Vector2 dest, Color color, float thickness)
398
    {
399
        //if there is an inactive bolt to pull from the pool

400
        if(inactiveBoltsObj.Count > 0)
401
        {
402
            //pull the GameObject

403
            GameObject boltObj = inactiveBoltsObj[inactiveBoltsObj.Count - 1];
404
            
405
            //set it active

406
            boltObj.SetActive(true);
407
            
408
            //move it to the active list

409
            activeBoltsObj.Add(boltObj);
410
            inactiveBoltsObj.RemoveAt(inactiveBoltsObj.Count - 1);
411
            
412
            //get the bolt component

413
            LightningBolt boltComponent =  boltObj.GetComponent<LightningBolt>();
414
            
415
            //activate the bolt using the given position data

416
            boltComponent.ActivateBolt(source, dest, color, thickness);
417
        }
418
    }
419
    
420
    //Capture the important points of our text for later

421
    IEnumerator TextCapture()
422
    {
423
        //must wait until end of frame so something is actually drawn or else it will error

424
        yield return new WaitForEndOfFrame();
425
        
426
        //get the camera that draws our text

427
        Camera cam = GameObject.Find("TextCamera").GetComponent<Camera>();
428
        
429
        //make sure it has an assigned RenderTexture

430
        if(cam.targetTexture != null) 
431
        {
432
            //pull the active RenderTexture

433
            RenderTexture.active = cam.targetTexture;
434
            
435
            //capture the image into a Texture2D

436
            Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
437
            image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
438
            image.Apply();
439
            
440
            //calculate how the text will be scaled when it is displayed as lightning on the screen

441
            scaleText = 1 / (cam.ViewportToWorldPoint(new Vector3(1,0,0)).x - cam.ViewportToWorldPoint(Vector3.zero).x);
442
            
443
            //calculate how the text will be positioned when it is displayed as lightning on the screen (centered)

444
            positionText.x -= image.width * scaleText * .5f;
445
            positionText.y -= image.height * scaleText * .5f;
446
            
447
            //basically determines how many pixels we skip/check

448
            const int interval = 2;
449
            
450
            //loop through pixels

451
            for(int y = 0; y < image.height; y += interval)
452
            {
453
                for(int x = 0; x < image.width; x += interval)
454
                {
455
                    //get the color of the pixel

456
                    Color color = image.GetPixel(x,y);
457
                    
458
                    //if the color has any r (red) value

459
                    if(color.r > 0)
460
                    {
461
                        //add it to our points for drawing

462
                        textPoints.Add(new Vector2(x,y));
463
                    }
464
                }
465
            }
466
        }
467
    }
468
}

Conclusion

Lightning is a great special effect for sprucing up your games. The effects described in this tutorial are a nice starting point, but it's certainly not all you can do with lightning. With a bit of imagination you can make all kinds of awe-inspiring lightning effects! Download the source code and experiment on your own.