- Home /
Question by
kurovskiy00 · Jan 27, 2019 at 08:01 AM ·
functiononceplaying
Running function once
Hello. I'm trying to make function or sth else which will run only one time. For example: I have a part of script when i can use any function if raycast hits player. So I'm setting playing sound here:
if (hit.transform == target)
{
int esvl = 1;
audioSource.PlayOneShot(GopnikAttacks[esvl], 0.7F);
}
But result is blood from my ears, because this sound plays every frame ray hits me. I'm tired of seeking the solution, so, please help me.
Comment
Answer by Hellium · Jan 27, 2019 at 10:32 AM
//outsid of your function
bool hittingTarget;
//....
// Inside of your function
if (hit.transform == target)
{
if( !hittingTarget )
{
hittingTarget = true;
int esvl = 1;
audioSource.PlayOneShot(GopnikAttacks[esvl], 0.7F);
}
}
else
{
hittingTarget = false;
}
You probably meant to set hittingTarget to true somewhere.
Nope. It doesn't work. I've already tried sth about this, no results. Its still plays every frame.
the whole function looks like this:
bool GetRaycast(Vector3 dir)
{
bool result = false;
RaycastHit hit = new RaycastHit();
Vector3 pos = transform.position + offset;
if (Physics.Raycast(pos, dir, out hit, distance, mask))
{
if (hit.transform == target)
{
if (!hittingTarget)
{
hittingTarget = true;
int esvl = 1;
audioSource.PlayOneShot(GopnikAttacks[esvl], 0.7F);
}
result = true;
Debug.DrawLine(pos, hit.point, Color.green);
}
else
{
hittingTarget = false;
}
Debug.DrawLine(pos, hit.point, Color.blue);
}
return result;
}
p.s. I didnt forget to make bool outside of function.