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.

Hard coded shooting offset sometimes randomly changes (why?)

Discussion in 'Scripting' started by Jason-H, Jun 23, 2011.

  1. Jason-H

    Jason-H

    Joined:
    Nov 5, 2010
    Posts:
    87
    Hello!

    Short story; I have coded an offset into some turrets but they don't stick to the offset - they sometimes randomly change and I've no idea why!


    Long story;

    I have the following code which shoots a bullet every 2 seconds. And then shoots the next bullet in the array.

    When they hit certain colliders they reset to the initial position and velocity (stationery).

    (In case you're wondering why I haven't simply instantiated and destroyed them it's because that takes a lot of processing power on iOS).

    Code (csharp):
    1.     var sodBullets : Rigidbody[];
    2.     var bulletForce : float;
    3.     var shootInterval : float = 2;
    4.     var offset : float;
    5.     var lastShot : float = 0;
    6.     var bulletIndex = 0;
    7.  
    8.     function Update()
    9.     {
    10.         if (Time.timeSinceLevelLoad + offset > lastShot + shootInterval)
    11.         {
    12.             sodBullets[bulletIndex].rigidbody.velocity = transform.TransformDirection(Vector3(0,0,bulletForce));
    13.             lastShot = Time.timeSinceLevelLoad + offset;
    14.             bulletIndex++;
    15.             if (bulletIndex > (sodBullets.length-1))
    16.             {
    17.                 bulletIndex = 0;
    18.             }
    19.         }
    20.     }
    21.  
    I have several of these turrets shooting with a slightly different offset to one another. For example the first is at 0 seconds offset, the second is at 0.5, the third at 1.0 and the fourth at 1.5 therefore they should hopefully all shoot one after another every half a second. But a bullet will only come out of the same turret every two seconds. Hopefully that made sense!

    The problem is that this works for a few times at first and then after playing for a little while (not sure how long as it's always different) they start shooting at different offsets which appears to have been changed randomly.

    Any ideas?

    Unity Answers post on same question; http://answers.unity3d.com/question...?viewedQuestions=133815&viewedQuestions=25537
     
  2. Moonjump

    Moonjump

    Joined:
    Apr 15, 2010
    Posts:
    2,525
    I think

    Code (csharp):
    1. lastShot = Time.timeSinceLevelLoad + offset;
    should be

    Code (csharp):
    1. lastShot = Time.timeSinceLevelLoad;
     
  3. Jason-H

    Jason-H

    Joined:
    Nov 5, 2010
    Posts:
    87
unityunity