- Home /
how to send message every few seconds?
let me explain. i have a raycast and when it find an enemy it starts Attack(); function and the attack function has a sendmessage. my problem is that the raycast detects the enemy a few times a second and the attack becomes savage like. im happy with the raycast being in the update function but i just want to limit sending the message to maby like 1 every few seconds. any help is appreciated. btw im new to unity
ohh and i cant use InvokeRepeating("sendDecrease$$anonymous$$essage", 0, 1); because the function attack gets called from the raycast in the update function so its gonna call it few times a second anyways
Answer by AlucardJay · Jun 27, 2013 at 07:25 AM
Use a timer.
Example of a timer :
var timerMax : float = 1.0;
var timer : float = 0;
function Update()
{
timer += Time.deltaTime;
if ( timer > timerMax )
{
timer = 0;
Debug.Log( "SendMessage NOW!" );
}
}
Sorry DaveA, lack of confidence, and a bit wary of posting anything after my rant and rampage a couple of months ago.
Although I do believe this is the best way to go (over coroutine or invoke), it is basically the same as setting a fire rate for an automatic weapon (which is pretty much what the OP is describing).
Answer by moha · Jun 27, 2013 at 07:28 AM
or you can use a coroutine with a waitforsecondes() in it
Im having truble with that. Only becuase i cant get it to work the way i want, im not really good at program$$anonymous$$g im more of an artist
Answer by mohitramani · Jun 27, 2013 at 09:59 AM
You can do the following ways:
1. Use InvokeRepeating
void Start () {
InvokeRepeating("RepeatingFunc", initialDelay, repeatTime);
}
void RepeatingFunc () {
Debug.Log("Repeated at time"+Time.time);
}
2. You can use a coroutine
void Start() {
StartCoroutine(RepeatingFunc());
}
IEnumerator RepeatingFunc () {
yield return new WaitForSeconds(repeatTime);
StartCoroutine( RepeatingFunc() );
}
3. Coroutine with infinite loop
void Start() {
StartCoroutine( RepeatingFunc() );
}
IEnumerator RepeatingFunc () {
while(true) {
//your code here
yield return new RepeatingFunc(repeatTime);
}
}
Your answer
Follow this Question
Related Questions
How to Send Message to other GameObject 3 Answers
BroadcastMessage 1 Answer
Flame Thrower - Particle Collision Help 1 Answer
Pass Enum To Function Parameter 2 Answers
How do i Specify a Receiver for a Send Message Function? 2 Answers