QuitApplication Button on unity - c#

I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.
Here is my C# script:
using UnityEngine;
using System.Collections;
public class Quit_App : MonoBehaviour {
void OnClick() {
Application.Quit();
}
}
I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box.
There, I selected it as object MyButton and the Quit_App() function using a string name.

Your script assumes that calling the method OnClick will magically make the click detected, but that is not the case.
You need a Menu Manager script added to the scene exposing a public method to be binded to the Button component.
Here the setup you need:
The script MenuManager is attached to the MenuManager game object:
The code in the MenuManager script is real simple:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuManager : MonoBehaviour {
public void ExitNow()
{
Application.Quit();
}
}
I uploaded the package with a fully functional implementation here.

First, this answer assumes that your code works and the only problem is that the Application.Quit () command does not execute.
The Application.Quit () command does not work when testing the application in the Unity Editor (for example, by pressing the "Play" button). It would close the Unity Editor.
To test, go to the "Files / Build and Run" menu.
This will build and execute the project and Application.Quit() will be execute properly.

After a search I found that onclick not a member of MonoBehaviour look at OnMouseDown on the following link http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

I find a semi-solution for this problem.I used this script that allows me to exit when i press the escape button.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
if (Input.GetKey("escape"))
Application.Quit();
}
// Update is called once per frame
void Update () {
if (Input.GetKey("escape"))
Application.Quit();
}
}

if you mean exit Play Mode thats completely an other thing. because quit is only when its built into an app.
Quitting the app:
Application.Quit();
Quitting the play mode:
UnityEditor.EditorApplication.isPlaying = false;

Related

How to select an object by script - Unity

I am a beginner in Unity and I am currently making a simple game. I have a problem where I need to select an object automatically by script so I can click outside of it without clicking on it in the screen.
What I want to do is when I click the object another object or panel will show and it will be automatically be selected by script so I can click outside the panel and it will close or will setActive to false. I tried the Select() and it is not working for me. The two objects are originally an Image but I added a Button component so it can be selectable.
This is the script for the object that will show the Panel:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ShowPhone : MonoBehaviour, ISelectHandler
{
[SerializeField] Button phonePanel;
public void OnSelect(BaseEventData eventData)
{
phonePanel.gameObject.SetActive(true);
}
}
This is the script for the panel where I want to click outside to close it:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class HidePhoen : MonoBehaviour, IDeselectHandler
{
public Button phone;
private void OnEnable()
{
phone.Select();
}
public void OnDeselect(BaseEventData data)
{
Debug.Log("The Object will be setActive false when clicked outside the object");
}
}
You would use EventSystem.SetSelectedGameObject
EventSystem.current.SetSelectedGameObject(yourTargetGameObject);
Note though: Your panel would automatically be closed even if clicking any UI element within it (like e.g. InputField etc)
You can checkout the TMP_Dropdown source code and the way they implemented a "UI Blocker" which basically is an overlay over the entire screen except the drop-down popup and closes the pop-up when clicked on.
you could either replicate this or have a simpler version with a fully transparent background button behind your panel with onClick for closing the panel.
As alternative you could check RectTransformUtility.RectangleContainsScreenPoint

How do I make a restart button or use r for restarting the scene

See when my player dies you can restart well that's what I wanted but I can't get it to work and I want it to where you have an option of either pressing r or the button to restart.
Can I please get a couple of tips for this probably some code too but that's up to you btw I am a beginner and need much help my game is just a basic learning game and I will love help from you fellow gamedevs
This is my old code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResetManager : MonoBehaviour
{
public static ResetManager Instance { get; private set; }
public event System.Action ResetEvent = new delegate {};
public void Awake()
{
Instance = this;
}
public static void ResetScene()
{
Instance.ResetEvent();
}
}
I would like to know if I could make it without scene manager
Welcome to stack overflow, here I will show a brief tutorial on how to build the key in the UI as well as execute the reset code. To create a UI button, go to Hierarchy and right-click, you can create a Button from the UI menu as shown below.
After creating the button, attach the script to a Manager object, click the button and reference the reset command at the bottom of the event, as below, keeping in mind that the unity event does not support static method's.
public void ResetScene() => SceneManager.LoadScene(SceneManager.GetActiveScene().name);
After performing the above steps, your button will restart the scene when clicked.
You can also restart the scene when you press the R key by adding the following code.
private void Update()
{
if (Input.GetKeyDown(KeyCode.R)) ResetScene();
}

Unity object reference + serialized field. What am I missing?

I have a ui Button called "Attack Button". I have a script called HeroBattleController attached to my Gameobject. I have an attack button set as a serialized field and the attack button object dropped on the script in the editor.
[SerializeField]
private Button AttackButton;
public void SetButtonStatus(bool status) {
AttackButton.interactable=status;
}
Trying to access that gives me the error NullReferenceException: Object reference not set to an instance of an object
I thought putting the object in the editor would allow me to access it without having to "Find" the object. Can anyone point me in the right direction?
The error is on the line
AttackButton.interactable=status;
Complete HeroBattleController script
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HeroBattleController: MonoBehaviour {
public static string SelectedHero;
[SerializeField]
private Button AttackButton;
public void SetButtonStatus(bool status) {
AttackButton.interactable=status;
}
public void HeroTouch() {
Debug.Log("Hero was touched: "+this.name);
SetButtonStatus(false);
}
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
}
HeroTouch is called via onClick from the heroprefab object.
Update: I had the herobattlecontroller script attached to two objects, the gameobject at the root of the scene and the heroprefab object. I removed it from the gameobject and only have it on the prefab. However now when I drag the attack button to the script section on the prefab it stays bold and when I run the game the attack button reference is gone. I can drag the button to the running object and it functions as I expected. I'm clearly missing something on the connection between the object hierarchy and where the objects are usable. Putting the hero battle controller script on the root gameobject only acts the same way meaning it's bold and when ran it's missing the link.
hierarchy during edit
hierarchy during runtime
Does HeroBattleController attached to a prefab? and does the AttackButton is on the same prefab ? if not then there is a problem.

instantiate a Popup when click a button in unity

I want to show popup when press the button.
But now it looks like this
I have viewed many tutorials about how to make a popup when press the button.
But they all make the popup by script,not instantiate the prefab.
I'm not sure if I can instantiate the prefab as I hope or it's not a good idea.
Here is my code
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Purchase : MonoBehaviour,IPointerClickHandler
{
public GameObject purchasePanel;
public GameObject panelPosition;
public void OnPointerClick (PointerEventData eventData)
{
GameObject instantiatedPurchase = Instantiate(purchasePanel, panelPosition.transform.position,panelPosition.transform.rotation) as GameObject;
instantiatedPurchase.transform.SetParent(panelPosition.transform);
}
}
You would probably use Unity.UI, and just use a panel.
It is very easy (1) click "add canvas" (2) click "add panel".
Simply turn it on and off using
.SetActive
from your code. Enjoy! As you can see it's this easy:
Try turning it on and off in the Editor with that toggle on Inspector. In code it's just..
public GameObject popupPanel;
...
popupPanel.SetActive(false); or...
popupPanel.SetActive(true);
I describe my way how to make popup.
There is a .gif how it looks like.
And there is link where it is described (Dacke is nickname there).

Unity3D - Turning off a GameObject's guiTexture fails to respond

I've been struggling with what appears to be a simple task for the past few hours. I have been successfully able to turn a GameObject's guiTexture on an off using GameObject.guiTexture.enabled as I have read in other similar questions. I do this in a script that is attached to the GameObject I wish to toggle.
The problem arises when I try to preform this same command from another script that is attached to an empty game object in my scene. When I interact with the button, simply nothing happens.
To give this some context, I am trying to create functionality to switch menus on the screen. When a user taps a certain UI button, I want to call unloadMenu() so I can wipe everything off the screen and draw the textures that belong to the appropriate menu.
//When the user lifts their finger
void OnTouchEnded ()
{
switch (this.gameObject.name)
{
//If they have selected the quiz button
case "QuizButton":
//this.guiTexture.enabled = false;
//Call the unloadMenu function which will clear the GUITextures
menuMgr.unloadMenu();
break;
The commented out section is what works fine. But now, I wish to perform this code in a function that is located in another script - menuMgr.unloadMenu()
This is what the MenuManager script looks like:
public GameObject quizButton;
void unloadMenu()
{
quizButton.guiTexture.enabled = false;
}
I have ensured to drag the quizButton gameobject from my scene into the inspector and connect it properly with the variable I have created yet nothing happens when this function is called. Does anyone have any idea why? Thanks in advanced.
How you declare MenuManager creates a new script while the reference to quizButton is in your MenuManager GameObject. That is why your menuMgr.UnloadMenu didn't do anything.
I have created something similar to yours and I found it worked fine :
Quizbutton Script:
public GameObject menuMgr; // reference to the empty game object (menu manager)
void OnMouseDown() // In your case, this is OnTouchEnded
{
// get the script of menu manager here
MenuMgrScript menuscript = menuMgr.GetComponent<MenuMgrScript>();
// and execute the function you want
menuscript.UnloadMenu();
}
Menu Manager Script:
// this script is exactly the same as yours, nothing's wrong here
// oh except add public to function UnloadMenu, so it can be called
// in the quizbutton script
public GameObject quizButton;
public void UnloadMenu() {
quizButton.guiTexture.enabled = false;
}

Categories

Resources