Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Laser Beam Script in C#

Discussion in 'Scripting' started by vdek, Feb 8, 2012.

  1. vdek

    vdek

    Joined:
    Sep 2, 2011
    Posts:
    368
    Hey folks, I spent a little bit of time working on this script to create a laser beam effect. You can attach a particle system to it to create some sparks at contact point. I suggest placing the script in an empty game object that is aligned with your weapon so it rotates with it.

    You can see the effect here:


    Code (csharp):
    1.  
    2. //This is free to use and no attribution is required
    3. //No warranty is implied or given
    4. using UnityEngine;
    5. using System.Collections;
    6.  
    7. [RequireComponent (typeof(LineRenderer))]
    8.  
    9. public class LaserBeam : MonoBehaviour {
    10.    
    11.     public float laserWidth = 1.0f;
    12.     public float noise = 1.0f;
    13.     public float maxLength = 50.0f;
    14.     public Color color = Color.red;
    15.    
    16.    
    17.     LineRenderer lineRenderer;
    18.     int length;
    19.     Vector3[] position;
    20.     //Cache any transforms here
    21.     Transform myTransform;
    22.     Transform endEffectTransform;
    23.     //The particle system, in this case sparks which will be created by the Laser
    24.     public ParticleSystem endEffect;
    25.     Vector3 offset;
    26.    
    27.    
    28.     // Use this for initialization
    29.     void Start () {
    30.         lineRenderer = GetComponent<LineRenderer>();
    31.         lineRenderer.SetWidth(laserWidth, laserWidth);
    32.         myTransform = transform;
    33.         offset = new Vector3(0,0,0);
    34.         endEffect = GetComponentInChildren<ParticleSystem>();
    35.         if(endEffect)
    36.             endEffectTransform = endEffect.transform;
    37.     }
    38.    
    39.     // Update is called once per frame
    40.     void Update () {
    41.         RenderLaser();
    42.     }
    43.    
    44.     void RenderLaser(){
    45.        
    46.         //Shoot our laserbeam forwards!
    47.         UpdateLength();
    48.        
    49.         lineRenderer.SetColors(color,color);
    50.         //Move through the Array
    51.         for(int i = 0; i<length; i++){
    52.             //Set the position here to the current location and project it in the forward direction of the object it is attached to
    53.             offset.x =myTransform.position.x+i*myTransform.forward.x+Random.Range(-noise,noise);
    54.             offset.z =i*myTransform.forward.z+Random.Range(-noise,noise)+myTransform.position.z;
    55.             position[i] = offset;
    56.             position[0] = myTransform.position;
    57.            
    58.             lineRenderer.SetPosition(i, position[i]);
    59.            
    60.         }
    61.        
    62.        
    63.        
    64.     }
    65.    
    66.     void UpdateLength(){
    67.         //Raycast from the location of the cube forwards
    68.         RaycastHit[] hit;
    69.         hit = Physics.RaycastAll(myTransform.position, myTransform.forward, maxLength);
    70.         int i = 0;
    71.         while(i < hit.Length){
    72.             //Check to make sure we aren't hitting triggers but colliders
    73.             if(!hit[i].collider.isTrigger)
    74.             {
    75.                 length = (int)Mathf.Round(hit[i].distance)+2;
    76.                 position = new Vector3[length];
    77.                 //Move our End Effect particle system to the hit point and start playing it
    78.                 if(endEffect){
    79.                 endEffectTransform.position = hit[i].point;
    80.                 if(!endEffect.isPlaying)
    81.                     endEffect.Play();
    82.                 }
    83.                 lineRenderer.SetVertexCount(length);
    84.                 return;
    85.             }
    86.             i++;
    87.         }
    88.         //If we're not hitting anything, don't play the particle effects
    89.         if(endEffect){
    90.         if(endEffect.isPlaying)
    91.             endEffect.Stop();
    92.         }
    93.         length = (int)maxLength;
    94.         position = new Vector3[length];
    95.         lineRenderer.SetVertexCount(length);
    96.        
    97.        
    98.     }
    99. }
    100.  
     
    Last edited: Feb 8, 2012
    cyber_shawn, Shakkar and Liinnkk like this.
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    nice that you publish it but if you want people to also use it you should always include licensing information. something posted in the internet is not automatically free to use (for those hwo care about their legal status).
    if you dont care what happens with this code and dont require credits you should consider the http://en.wikipedia.org/wiki/WTFPL or http://en.wikipedia.org/wiki/Public_domain.

    also you should consider putting it in the wiki.
     
    Last edited: Feb 8, 2012
  3. vdek

    vdek

    Joined:
    Sep 2, 2011
    Posts:
    368
    It's free to use, no attribution required...
     
  4. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    i'm not a lawyer but as far as i know this is wrong. when no explicit licence is provided this is your intellectual property and everyone who uses it CAN be punished. if you do i or not does not matter but you could do it. therefore its always better to explicitely state the terms of use / licence with your product when you publish it.

    edit: thinking over your statement you could mean it as "terms of use". sorry for misunderstanding. language barrier sucks ;).
     
    Last edited: Feb 8, 2012
  5. sp00ks222

    sp00ks222

    Joined:
    May 12, 2011
    Posts:
    37
    awesome! thank you, it looks great. If I ever need a laser beam (which could be soon) I will be sure to give this a try
     
  6. tmanallen

    tmanallen

    Joined:
    Nov 8, 2009
    Posts:
    395
    Thanks for this script been looking for this. What did you use for particle system was it your own custom made system?
     
    Last edited: Feb 13, 2012
  7. vdek

    vdek

    Joined:
    Sep 2, 2011
    Posts:
    368
    I just used the Shuriken particle system with the Sparks texture that comes included with Unity.
     
  8. Appppppppp

    Appppppppp

    Joined:
    Dec 4, 2012
    Posts:
    2
    Can I use this in my game ??
     
  9. Destroypattern

    Destroypattern

    Joined:
    Aug 21, 2013
    Posts:
    10
    Jacksonds, nickdhawan1 and Leon-Fresh like this.
  10. Kirlim

    Kirlim

    Joined:
    Aug 6, 2012
    Posts:
    126
    Just because licenses was cited in this thread.
    Don't ever make a code public domain. Why? Because "public domain" definition can change from country to country, sometimes leading to unexpected legal issues. You can use something like BSD that basically says "you can use this as long as you don't sue me (for this work) afterwards".
     
  11. Deleted User

    Deleted User

    Guest

    can you please put a download link to this script? coz on my mac mlnodevelop doesn't work! so i must use SublimeText2... and i can't seem to put the script in unity... plz put download!!!!!!:eek::eek::eek::eek::eek::eek::eek::eek::eek:
     
  12. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Wont work with FPS mode because off missing Y offset calculations... Any ideas?
     
  13. Mirecsy23

    Mirecsy23

    Joined:
    Jan 9, 2015
    Posts:
    31
    Hi, I made asset that is solved your problem You can get in on AssetStore: http://u3d.as/qBx
     
  14. anhduyqh123

    anhduyqh123

    Joined:
    Nov 8, 2015
    Posts:
    1
    hi, you can watch my idea
     
    radicalappdev likes this.
  15. MikielSG

    MikielSG

    Joined:
    Dec 26, 2016
    Posts:
    47
    I just wanted to update people on this.

    Work that is published in public forms is consider "open source" and is free to be used and has no legal standing of "being sued" as its considered to be publicly distributed and accessible.

    Thus, if you post on something like this, discord, by default they have no grounds to sue when using it.