Instantiate spawns 2 instead of 1, help?

var newBoat : Transform;

var dockboat = true;

function OnTriggerEnter (){

    if(GameObject.FindWithTag("Player") && dockboat == true){
            dockboat = false;

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?

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

Try replacing them with a:

Invoke("spawn", 0);


Invoke("trueagain", 0);


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.

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.