Random Teleport Script

I’m having trouble with a method that is supposed to randomly teleport my player to an instance of a prefab called “Teleport”. I have multiple instances of this prefab. I am able to teleport, however occasionally I will ‘teleport’ back to the same instance of a prefab.

The following is the code relevant:

void Start () {

             teleportArray = GameObject.FindGameObjectsWithTag("Teleport")
     }

void OnTriggerEnter(Collider other)
{
        
        if (other.transform.tag == "Teleport")
        {

            int number = Random.Range(1, teleportArray.Length);

            transform.position = teleportArray[number].transform.position;
           
        }

    }

I have tried a couple ways to prevent teleporting to the same instance of a prefab, but no good results. I’m new to unity, any help?

You need to save the number each time you generate a new position. So at the top of the file put:

private int prevNum = -1;

Then your code becomes:

       int number;
       do {
            number = Random.Range(1, teleportArray.Length);
        } while (number == prevNum);

       prevNum = number;

        transform.position = teleportArray[number].transform.position;

This way your code will repeatedly generate random numbers until it gets one that is not the same as the previous one.

Ahh, I see the issue, the problem is that sometimes it randomly selects your teleporter that you are coming from, so you are going to have to exclude that from your array. I am unsure of the best way to do this, perhaps try

void Teleport(){
int i = Random.Range(1, teleportArray.Length);
if(teleportArray*.transform.position != other.transform.position){*

transform.position = teleportArray*.transform.position;*
}else{
Teleport();
}
}
In your OnCollision function you would have to call teleport(); after the player hits a teleporter