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 :)
tl;dr: I have a script that on start, makes something teleport, but i want a button to do it instead.
Answer by Vega4Life · Dec 15, 2018 at 02:11 AM
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!
Your answer
Follow this Question
Related Questions
How do I change a state in an FSM with an UI button? 0 Answers
How to fix button clones that aren't working? 0 Answers
Dymanic buttons with different openURL links 0 Answers
How to make an object keep move when pressing a button? 0 Answers
How to make button rotate when another button is pressed? 0 Answers