Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by LEMONVirus99 · Dec 14, 2012 at 09:28 PM · c#soundrunning

How can i add a time limit to running?

I have a C# script that makes my player (FPS) run and crouch but i want to add a time limit to running. so i want to make it 5 seconds running time and 15 seconds regeneration time with out of breath sound effects. How would i go about doing so?

Here's the script i'm using

 using UnityEngine;
 using System.Collections;
 
 public class RunAndCrouch : MonoBehaviour 
 {
     public float walkSpeed = 7; // regular speed
     public float crchSpeed = 3; // crouching speed
     public float runSpeed = 20; // run speed
 
     private CharacterMotor chMotor;
     private Transform tr;
     private float dist; // distance to ground
 
     // Use this for initialization
     void Start () 
     {
        chMotor =  GetComponent<CharacterMotor>();
         tr = transform;
         CharacterController ch = GetComponent<CharacterController>();
         dist = ch.height/2; // calculate distance to ground
     }
 
     // Update is called once per frame
     void FixedUpdate ()
     {
        float vScale = 1.0f;
         float speed = walkSpeed;
 
         if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
         {
             speed = runSpeed;       
         }
 
         if (Input.GetKey("c"))
         { // press C to crouch
             vScale = 0.5f;
             speed = crchSpeed; // slow down when crouching
         }
 
         chMotor.movement.maxForwardSpeed = speed; // set max speed
         float ultScale = tr.localScale.y; // crouch/stand up smoothly 
 
        Vector3 tmpScale = tr.localScale;
        Vector3 tmpPosition = tr.position;
 
        tmpScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5 * Time.deltaTime);
        tr.localScale = tmpScale;
 
        tmpPosition.y += dist * (tr.localScale.y - ultScale); // fix vertical position       
        tr.position = tmpPosition;
     }
 }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Dec 15, 2012 at 07:49 PM 1
Share

in unity for very simple timers, just use Invoke()

it is incredibly simple

So it would be like

Invoke( "StopRunning", 5.0 );

and perhaps

Invoke( "HardAgain", 15.0 );

you just write the two routines StopRunning() etc which would be extremely simple (no more than one or two lines of code each)

there is vast discussion of this on unityGE$$anonymous$$S.com

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by clunk47 · Dec 14, 2012 at 09:58 PM

I would add a runDuration float, a regenTime float, and use an Enumerator to be able to count the durations. I haven't had time to test this, but I did run my scene with the script involved and no errors or warnings. This might not work exactly as you wanted but this should get you to the point where you can get this idea to work. This is more of an edit of your code with the necessary additions that you can experiment with, hope this helps :)

 using UnityEngine;
 using System.Collections;
 
 [RequireComponent(typeof(AudioSource))]
 
 public class RunAndCrouch : MonoBehaviour 
 {
     public float walkSpeed = 7; // regular speed
     public float crchSpeed = 3; // crouching speed
     public float runSpeed = 20; // run speed
     public float runDuration = 5.0f;
     public float runRegenTime = 15.0f;
 
     private CharacterMotor chMotor;
     private Transform tr;
     private float dist; // distance to ground
 
     bool canRun = true;
     bool tryRun = false;
     
     public AudioClip outOfBreath;
 
     // Use this for initialization
     void Start () 
     {
         ///AUDIO
         if(!GetComponent<AudioSource>())
             gameObject.AddComponent<AudioSource>();
         audio.clip = (AudioClip)outOfBreath;
         audio.loop = false;
         audio.playOnAwake = false;
         ///
         StartCoroutine("CheckRunEnergy");
         chMotor =  GetComponent<CharacterMotor>();
         tr = transform;
         CharacterController ch = GetComponent<CharacterController>();
         dist = ch.height/2; // calculate distance to ground
     }
 
     // Update is called once per frame
     void FixedUpdate ()
     {
         print (canRun);
        float vScale = 1.0f;
         float speed = walkSpeed;
 
         if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
         {
          tryRun = true;
          if(canRun)
                 speed = runSpeed;
          else if(!canRun)
           speed = walkSpeed;
         }
        else
          tryRun = false;
 
         if (Input.GetKey("c"))
         { // press C to crouch
             vScale = 0.5f;
             speed = crchSpeed; // slow down when crouching
         }
 
         chMotor.movement.maxForwardSpeed = speed; // set max speed
         float ultScale = tr.localScale.y; // crouch/stand up smoothly 
 
        Vector3 tmpScale = tr.localScale;
        Vector3 tmpPosition = tr.position;
 
        tmpScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5 * Time.deltaTime);
        tr.localScale = tmpScale;
 
        tmpPosition.y += dist * (tr.localScale.y - ultScale); // fix vertical position       
        tr.position = tmpPosition;
     }
 
     IEnumerator CheckRunEnergy()
     {
        while(true)
        {
          if(tryRun)
          {
           while(canRun)
           {
               yield return new WaitForSeconds(runDuration);
               canRun = false;
               audio.PlayOneShot(outOfBreath, 1.0f);
           }
           while(!canRun)
           {
               yield return new WaitForSeconds(runRegenTime);
               canRun = true;
           }
          }
 
 
          yield return new WaitForEndOfFrame();
        }
     }
 }
Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image LEMONVirus99 · Dec 14, 2012 at 10:08 PM 1
Share

the code has worked, it brings up the option of duration time however my player seems to still run forever. Any ideas why?

avatar image clunk47 · Dec 15, 2012 at 12:10 AM 2
Share

I have edited the script above and added audio, and it will play when your player is "out of breath" or out of running energy. I have included 2 different ways of adding an Audio Source component which are [RequireComponent(typeof(AudioSource))], and by checking for an audiosource in void Start(), and adding one if there is not one. Then I set the clip to the public clip you drag onto the script. Don't worry about dragging a clip on the AudioSource Component in the inspector. Just drag your breathing sound onto the "Out Of Breath" option on this script in the inspector. I've tested and this works, use whatever sound you want. For best results, click on your sound clip in the inspector and set it to 2D sound (uncheck the 3D Sound box).

avatar image LEMONVirus99 · Dec 15, 2012 at 08:07 AM 2
Share

It works like a charm! Thanks again for your wonderful help. However i must ask, is there a volume control for the sound effect? right now its louder than the background music

avatar image clunk47 · Dec 15, 2012 at 04:31 PM 2
Share

Yes Sir! You notice when I say PlayOneShot(audio.clip, 1.0f)... The 1.0f is the volume. Volume ranges as a float in script from 0.0f to 1.0f (1.0f being the loudest.) Try using 0.5f or so :)

avatar image LEMONVirus99 · Dec 15, 2012 at 04:43 PM 1
Share

I thank you once again :) I know this is completely off topic from the question but, may i ask how did you learn scripting? and do you thing its possible to learn it independently from books and videos?

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Play audio from directory? 0 Answers

useing WWW Class 1 Answer

Distribute terrain in zones 3 Answers

[C#]Toggle Run on/off 2 Answers

Multiple Cars not working 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges