The sound plays when I release the space bar instead of when I press it

I am following the Rocket boost part of the unity 3d course, and I am at the part where I need to connect the boost sound to the rocket.

I have added the if statements when the space bar is pressed the boost sound will play. But for some reason this is happening in reverse instead of when I press the space bars no sound is played, it is when I release the space bar the rocket sound will play.

I have added my code below.

I’ve tried to figure out what happens by adding a dev log line to see when the two if statement are triggered, but only the else statement is triggered when I press the space bar.


    AudioSource RocketfuelSource;
    Rigidbody rigid;
   [SerializeField] float speedThrust = 1000f;
   [SerializeField] float speedThrustBack = 1000f;
   [SerializeField] float RotateShip = 10f;

    // Start is called before the first frame update
    void Start()
    {
      rigid = GetComponent<Rigidbody>();
      RocketfuelSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        ProcessTrustShip();
        ProcessRotationShip();
    }

   void ProcessTrustShip()
   {
       if (Input.GetKey(KeyCode.Space))
       {
           
           rigid.AddRelativeForce(Vector3.up * speedThrust * Time.deltaTime);
           rigid.AddRelativeForce(Vector3.forward * speedThrust * Time.deltaTime);

             if(!RocketfuelSource.isPlaying)
           {
                 RocketfuelSource.Play();
                 Debug.Log("sound staterd");

           }

           else 
           {
               RocketfuelSource.Stop();
               Debug.Log("sound stoped");
           }

         
           
       }
       if (Input.GetKey(KeyCode.S))
       {
           rigid.AddRelativeForce(Vector3.back * speedThrustBack * Time.deltaTime);
       }
      
   }

   void ProcessRotationShip()
   {
        if (Input.GetKey(KeyCode.D))
        {
            ApplyRotationShip(RotateShip);
        }

        else if (Input.GetKey(KeyCode.A))
       {
          ApplyRotationShip(-RotateShip);
       }
      
   }

    private void ApplyRotationShip(float rotatethisframe)
    {
       rigid.freezeRotation = true; // freezing rotation so we can manually rotation
        transform.Rotate(Vector3.left * rotatethisframe * Time.deltaTime);
        rigid.freezeRotation = false; // unfreezing rotation so the physics system can take over
    }
}

Hi,

Please take a close look at your code and to which if-statement the else belongs. Remember you can also look at the lecture code changes via the link in the Resources of each lecture. Hopefully, this helped. :slight_smile:


See also:

1 Like

Thank you very much that help me a lot! didn’t see that else state was still inside the if input section.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms