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

simple shoot script?

Discussion in 'Scripting' started by Bulslayer90, Jan 8, 2013.

  1. Bulslayer90

    Bulslayer90

    Joined:
    Dec 24, 2012
    Posts:
    40
    var shot:GameObject;

    function Update () {
    if(Input.GetMouseButtonDown(0))
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hit : RaycastHit;
    if (Physics.Raycast (ray, 100)) {
    print ("Hit something");
    Instantiate(shot, hit.point, Quaternion.identity);
    }
    }

    ok the idea was i click the mouse button down and it does a raycast then creates an object where the raycast hits, it seems to be working cause i see the clones appear in the hiarchy window but i cant see them in the game scene itself and im wondering why?
     
  2. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    i don't know if this will help but have you defined the bullet variable as a transform i.e:

    var shot : Transform;

    Then highlight your Game Object you are shooting from in your scene then from the inspector under your script drag the bullet to your transform option to populate it
     
  3. Bulslayer90

    Bulslayer90

    Joined:
    Dec 24, 2012
    Posts:
    40
    k this is odd, i added some debug commands to print out where the hit point is and what collider it hit and its saying all 0s for point and null for collider but its saying it hit something. this makes no sense.
     
  4. Bulslayer90

    Bulslayer90

    Joined:
    Dec 24, 2012
    Posts:
    40
    OK i figured it out,

    if (Physics.Raycast (ray, 100)) {

    the issue was that hit although being assigned RaycastHit was not storing the info returned from the collision so the correct code is:

    if (Physics.Raycast (ray, hit, 100)) {
     
  5. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606
    Edit yuou fixed it :)
     
    Last edited: Jan 9, 2013
  6. Kwaung

    Kwaung

    Joined:
    Sep 19, 2012
    Posts:
    3
    I think you didn't pass the hit variable to the function. That why you get null for the collider.