Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Raycast Shooting doesn't work.

Discussion in 'Scripting' started by markrashera, Aug 15, 2014.

  1. markrashera

    markrashera

    Joined:
    Aug 15, 2014
    Posts:
    10
    hey everybody, i'm trying to make an fps multiplayer game, so i created a raycast shooting script, but when i run the game, and try to shoot, it doesn't do anything and sends this error in the console:

    NullRefrenceException: Object refrence not set to an instance of an object
    RayCastShooting.Update () (at Assets/blabalbalbalbalbla/blabba/RayCastShooting.js:9)

    here is the script of the RayCastShooting:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var Effect : Transform;
    4. var TheDammage = 100;
    5. var line : LineRenderer;
    6. function Update () {
    7.    
    8.     var hit : RaycastHit;
    9.     var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));
    10.    
    11.     if (Input.GetButton("Fire1"))
    12.     {
    13.         if (Physics.Raycast (ray, hit, 100))
    14.         {
    15.             var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
    16.             Destroy(particleClone.gameObject, 2);
    17.             hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
    18.             Debug.Log("Bam!");
    19.         }
    20.     }
    21.    
    22.    
    23. }
    i inserted the code to my main camera.
    please help :)
     
  2. daemon3000

    daemon3000

    Joined:
    Aug 13, 2012
    Posts:
    139
    You probably don't have a main camera in your scene. Select the camera and make sure it has the "Main Camera" tag.
    If the script is attached to the camera then you can use camera.ScreenPointToRay instead of Camera.main.ScreenPointToRay and it should fix your problem.
     
    markrashera likes this.
  3. markrashera

    markrashera

    Joined:
    Aug 15, 2014
    Posts:
    10
    Thanks!!! it worked. Thank you so much :D
     
  4. Yuutje

    Yuutje

    Joined:
    May 16, 2016
    Posts:
    1
    Heeii, I did every step what was needed and still it doesn't do it. I don't know what is wrong and what I can do about it.
    Do you guys know?
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    necro'ing an old thread and not providing any details or code which tells us what you've done isn't going to get very far...