Button make object teleport (simple)

Hi, I have a script that makes an object teleport to random locations in my world:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Teleport : MonoBehaviour {

	public Vector3 offset;
	public Transform player;

	void Start() {
		float randomY = Random.Range(-10.0f, 10.0f); // Min = -10.0f, Max = 10.0f
		float randomX = Random.Range(-10.0f, 10.0f);
		offset += new Vector3(randomX, randomY, 0);
	}

 	void Update() {
		Vector3 position = transform.position;
		position.y = (player.position + offset).y;
		position.x = (player.position + offset).x;
		transform.position = position;
	}

}

And when I start the game, it teleports to a random spot, however, I would like to have a button run the script to make it teleport somewhere

How would I do this? Thanks so much for anyone who helps :slight_smile:

tl;dr: I have a script that on start, makes something teleport, but i want a button to do it instead.

Here is the code. Just moving your Start() contents into a DoTeleport() function so our button can call it when clicked.


using UnityEngine;

public class Teleport : MonoBehaviour
{
    public Vector3 offset;
    public Transform player;


    void Update()
    {
        Vector3 position = transform.position;
        position.y = (player.position + offset).y;
        position.x = (player.position + offset).x;
        transform.position = position;
    }

    // Assign this to your UI buttons onClick
    public void DoTeleport()
    {
        float randomY = Random.Range(-10.0f, 10.0f); // Min = -10.0f, Max = 10.0f
        float randomX = Random.Range(-10.0f, 10.0f);
        offset += new Vector3(randomX, randomY, 0);
    }
}

Next, you want to create a UI button. A the top of the editor click on GameObject → UI → Button. This will add a Canvas with a UI button in it. There is a button script on the button object. At the bottom hit the + sign to add an OnClick() event. Drag the gameObject that is holding your Teleport script into the reference. Next to it, it should say “No Function”. Click on this button and it opens a drop down. Hover over our Script ‘Teleport’, then hover over our function ‘Do Teleport’ and click it. Now we are all set.


Clicking the button will now send an event to that function that will execute your code.


Hope that helps!