x


InvokeRepeating()

I have just stared down the wonderful road of InvokeRepeating methods. What I would like to know is; is there a easy way to toggle these methods on and off. For example lets say I have a class with

    InvokeRepeating("SpawnNewCharacter", 4, 4);
    InvokeRepeating("AddResource", 4, 4);

and I want the component to spawn new characters only when its not adding resources, and vice versa. I had thought about making one method that will spawn either or based on a toggle, but I know I will be extending this class and adding other possible actions.

more ▼

asked Apr 29 '11 at 12:03 AM

Siegeon gravatar image

Siegeon
45 6 6 15

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You can use CancelInvoke where necessary, but it sounds like coroutines would be more appropriate for this than InvokeRepeating.

private var addingResource : boolean;

function Loop () {
    while (true) {
        yield SpawnNewCharacter(4.0);
        yield AddResource(4.0);
    }
}

function SpawnNewCharacter (delay : float) {
    while (!addingResource) {
        Instantiate(character); 
        yield WaitForSeconds(delay);
    }
}

function AddResource (delay : float) {
    while (addingResource) {
        resources++;    
        yield WaitForSeconds(delay);
    }
}

In this case, setting "addingResource" to true or false toggles between the two functions.

more ▼

answered Apr 29 '11 at 12:54 AM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

Yeah I think your right, co routines would be more appropriate, thanks.

Apr 29 '11 at 12:57 AM Siegeon
(comments are locked)
10|3000 characters needed characters left
more ▼

answered Apr 29 '11 at 12:46 AM

DaveA gravatar image

DaveA
26.5k 151 171 256

Thank you for your quick reply, the example that you posted(and I had already looked at) does not show how you would toggle the method back on once I were no-longer collecting resources.

Apr 29 '11 at 01:01 AM Siegeon
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x50

asked: Apr 29 '11 at 12:03 AM

Seen: 2630 times

Last Updated: Apr 29 '11 at 12:03 AM