x


Instantiate spawns 2 instead of 1, help?

var newBoat : Transform;

var dockboat = true;

function OnTriggerEnter (){

    if(GameObject.FindWithTag("Player") && dockboat == true){
            Destroy(GameObject.FindWithTag("Player"));
            dockboat = false;
            StartCoroutine("spawn");
    }
}

function spawn () {
    Instantiate( newBoat, transform.position, transform.rotation);
    dockboat = false;
    StartCoroutine("trueagain", 1);
}

function trueagain () {
    dockboat = true;
}

I'm having trouble with this script. When I collide with the trigger I want to destroy my character and spawn a different one. Most of the time it spawns 2 characters in the same place at the same time, other times it just spawns one character. I have absolutely no idea why it is doing this. Is there an easy fix to this problem?

more ▼

asked Apr 05 '11 at 01:17 PM

Confuseddd gravatar image

Confuseddd
3 1 1 2

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

2 answers: sort voted first

I believe its being caused by the 'StartCoroutines' that you have.

Try replacing them with a:

Invoke("spawn", 0);

and

Invoke("trueagain", 0);

Hint:

The '0' in the Invoke is if you would like a time delay to trigger the function, so if you have a: Invoke("spawn", 10); - then your spawn function will be called in 10 seconds.

Hope that helps.

more ▼

answered Apr 05 '11 at 01:38 PM

oliver-jones gravatar image

oliver-jones
2.5k 206 226 254

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

The basic problem seems to be that Instantiating the new boat is reTriggering the trigger box. In other words, new spawns can cause OnTriggerEnter. You've got the "flag" spawnBoat to prevent that.

The rest of the problem is likely that coroutines can run in any order. Sometimes it sets dockboat=false, spawns, resets it to true, then reruns OnTriggerEnter for the 2nd boat, with spawnBoat back to true.

Adding a Wait or yield command to TrueAgain would cause everything else to run first (with a false spawnBoat.) Likewise adding a delay to Invoke would do the same thing.

A comment: I don't think you could move the lines from spawn into OnTriggerEnter.

more ▼

answered Apr 06 '11 at 08:14 PM

Owen Reynolds gravatar image

Owen Reynolds
11.6k 1 7 45

(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:

x5098
x1683
x810
x764
x337

asked: Apr 05 '11 at 01:17 PM

Seen: 855 times

Last Updated: Apr 06 '11 at 06:08 PM