- Home /
 
Teleport to a random height
In my game I have some objects that I want to teleport to a fixed x position but a random y position when they hit another game object. I have tried many times to find a way to do this but none of them work the right way. With this script, the objects just spawned at one positions and with a older script, the objects did teleport to random positions, but the position that an object would teleport to would seem to loop. It was like that gameobject had a random position chosen at the start, but it wouldn't make another random position. So my question actually is how would I generate a random position every time the objects collide? here is script:
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Teleport : MonoBehaviour {
     public GameObject teleportto;
     float x;
     float y;
     float z;
     Vector2 pos;
     public bool teleport;
     // Use this for initialization
     void Start () {
         x = -5;
         y = Random.Range(0, 7);
         pos = new Vector2(x, y);
     }
     
     // Update is called once per frame
     void Update () {
         Debug.Log (this.transform.position);
         if (teleport == true) {
             y = Random.Range (0, 7);
         }
     }
 
     void OnTriggerEnter2D (Collider2D col) {
         if (col.gameObject.tag == "teleport") {
             this.transform.position = pos;
             teleport = true;
         }
         teleport = false;
     }
 }
 
              Answer by bobisgod234 · Aug 11, 2017 at 12:52 AM
Move the code in start to the top of your OnTriggerEnter function:
      void OnTriggerEnter2D (Collider2D col) {
          x = -5;
          y = Random.Range(0, 7);
          pos = new Vector2(x, y);
          if (col.gameObject.tag == "teleport") {
              this.transform.position = pos;
              teleport = true;
          }
          teleport = false;
      }
 
              Your answer
 
             Follow this Question
Related Questions
Transform to a random height 0 Answers
Generating a Displacement Map in Unity3d? 1 Answer
Make an Object teleport a Random distance away. 1 Answer
How to transform position? 2 Answers
transform postion trigger problem HELP! 0 Answers