- Home /
Script for a GUI button to change an object's rotation?
I'm making a racing game, and I've encountered an issue where the car would accidentally get stuck after getting flipped upside down or on it's side.
I want to know how to create a button that allows the car's rotation to be set upright again.
Basically, I want the car's X and Z rotation values to be set to 0 whenever the button is pressed.
The object name that contains the car's prefab, camera etc. is called 'Player 1'.
I could really use a full detailed description as to how to go about this, as I have no C# knowledge and completely rely on tutorials... Thanks in advance.
Answer by Vega4Life · Nov 13, 2018 at 03:09 PM
Here is a quick thing to get you going -
using UnityEngine;
public class ResetRotation : MonoBehaviour
{
public void RotationReset()
{
transform.eulerAngles = new Vector3(0f, transform.eulerAngles.y, 0f);
}
}
You can add this script to your car object or just copy the method and put it in your car manager script if you have one.
Next you need a button. Add on by clicking on GameObject -> UI -> Button.
This will add a Canvas, EventSystem, and a Button in the scene. Find the button script on the button, it's should be under the Canvas.
The button script at the bottom will have an OnClick() event, drag the gameobject that contains the script with the reset rotation method on it onto OnClick() reference. Next, there is a drop down that should say "No Function". Click on that and find the name of script where the reset rotation function is (This should show all the scripts on the object you referenced). Then, it should slide out and you click on the reset function name.
Once that is all setup, run your game, flip the car over and hit the button. It will send a notification to the reset rotation function. This will reset your cars rotation.
It's quick and dirty but gets to the point. You then change out the button, visual, move it around, etc.