- Home /
Question by
TheYoyii · Aug 18, 2013 at 07:16 PM ·
audiosourcerunbehaviour
Can't add script behaviour Run.
Hi ! I found a script to make my FPS run for a limited time. The script is correct but i dont understand why i can't put it on my First Person Player. This is the script.
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();
}
}
}
Im new on unity and sorry for my bad english.
Comment
This is the message that popup when i try :
Can't add the script Run. The scripts file name does not match the name of the class defined in the script!
and yes he dont let me put the script on my First Person Player.
That's precisely the error I was expecting. The answer is provided by @DaveA.