- Home /
RayCast Delay?
How would I go about scripting a delay for a raycast? Initially how would I change this script so that instead of it shooting the raycast every frame I can change the tempo of it?
function Update(){ if (Input.GetButton("Fire1")){ Shoot(); } }
var shotSound: AudioClip; var bloodPrefab: GameObject; var sparksPrefab: GameObject;
function Shoot(){ if (shotSound) audio.PlayOneShot(shotSound); var hit: RaycastHit; if (Physics.Raycast(transform.position, transform.forward, hit)){
var rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
if (hit.transform.tag == "Enemy"){
if (bloodPrefab) Instantiate(bloodPrefab, hit.point, rot);
hit.transform.SendMessage("ApplyDamage", 20, SendMessageOptions.DontRequireReceiver);
} else {
if (sparksPrefab) Instantiate(sparksPrefab, hit.point, rot);
}
}
}
Dammit you people stop double posting! It wastes people's time.
Answer by syclamoth · Nov 14, 2011 at 09:12 PM
You could do something like split the shooting off into a separate Coroutine, which gets fired off from Start()
function ShotPoller()
{
while(true)
{
if(Input.GetButton("Fire1"))
{
Shoot();
yield WaitForSeconds(refireRate);
} else {
yield;
}
}
}
function Start()
{
StartCoroutine(ShotPoller());
}
Then just modify 'refireRate' until it shoots at the right speed!
would I put this as a differant script or would I add it onto the other one?
No, add it as part of the existing script. You wouldn't be able to call 'Shoot' if it were in a different script!
I have an error saying "unknown identifyer: refireRate" can you help?
Well, obviously you have to declare a variable called refireRate somewhere! I didn't write your entire script for you, you need to know how to adapt this stuff! refireRate should be a public variable that you can change in the inspector (or from another script) so that you have fine control over your shoot speed.
Im sorry if i have annoyed you, its just im pretty pathetic at scripting and im a still learning. one more question would this variable be a bollean?
Your answer
![](https://koobas.hobune.stream/wayback/20220613042943im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C# Check Physics.Raycast Once 0 Answers
A node in a childnode? 1 Answer
Enemy damage error 1 Answer
Stop animation when no more bullets 1 Answer
C# More Accurate or Larger Raycast 1 Answer