Unity right click outside of update - c#

I'm working on a mouse manager script. I want to be able to left click on the instantiated text object and have it do one thing, and do something else when right clicked. Trouble is you can't send a parameter to an event trigger OnCLick and to send the base event data doesn't give you which button was clicked. I can't simply use Update because I only want them to right click on the text object not anywhere, especially since I want the right click to delete the object. I've looked and looked, one would think this were a common enough problem to find a solution, but alas.
I already have an OnEnter and OnExit, which changes the colors of the text.
Anyone have a solution?
Thanks!

In case anyone else has been pulling out their hair over this kind of issue. I finally found a solution and it works very well. So I will share it.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
public class RightClick : MonoBehaviour, IPointerClickHandler
{
public UnityEvent leftClick;
public UnityEvent middleClick;
public UnityEvent rightClick;
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
leftClick.Invoke ();
else if (eventData.button == PointerEventData.InputButton.Middle)
middleClick.Invoke ();
else if (eventData.button == PointerEventData.InputButton.Right)
rightClick.Invoke ();
}
}

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();
}

How to keep InputField keyboard open when focus is lost?

I'm making a typing game where the user types in words that fall down the screen, and I have buttons at the top that act as powerups (nuke, freeze, etc...) when the user presses them.
Now, when the user clicks one of the powerup buttons at the top of the screen, the keyboard will momentarily close before ButtonClicked re-opens it and it looks quite buggy. How do I make it so that when the user clicks one of the buttons at the top the keyboard stays open the whole time?
Currently, I have added a listener on the button that will re-open the keyboard.
myButton.onClick.AddListener(ButtonClicked);
void ButtonClicked()
{
//DoStuff();
inputField.ActivateInputField();
}
This is what it looks like now. I have to click once to get rid of the keyboard, and then once again on the button.
https://imgur.com/a/WTLLYEX
I tried overriding some InputField functions with a custom class but to no avail.
public class CustomInputField: InputField
{
public override void OnDeselect(BaseEventData eventData)
{
Debug.Log ("Overrides InputField.Deselect");
}
public override void DeactivateInputField()
{
Debug.Log ("Overrides InputField.DeactivateInputField");
}
}
The first method doesn't accomplish what I want, and the second method DeactivateInputField() gives me
error CS0506: CustomInputField.DeactivateInputField': cannot override inherited memberInputField.DeactivateInputField' because it is not marked virtual, abstract or override.
Any help would be greatly appreciated, thank you!
You could use the TouchScreenKeyboard.open Function to leave the Keyboard open over time (here the Link to the Unity Manual: https://docs.unity3d.com/ScriptReference/TouchScreenKeyboard.Open.html). I would then aswell try to not use Update for this there should be another way to do so in your script.
Your error Otherwise might be caused because you try to override a function that is like the error said not Virtual Abstract nor Override so you aren't allowed to do that. To this it is an Unity class so you won't be able to change this aswell.
Another Thing you could try would be LateUpdate that wouldn't be perfect but it may Help your case here an Example:
LateUpdate()
{
if(!TouchScreenKeyboard.visible)
TouchScreenKeyboard.Open()/inputField.ActivateInputField();
};
The input field opens the system keyboard and your control over it is limited. If I were you I would create UI keyboard in my app which could be customized in any way and would guarantee same results on different devices/systems.
Probably the dumbest code I've ever written, but it does the trick:
public class FocusInputField : TMP_InputField
{
protected override void OnDestroy()
{
this.StopAllCoroutines();
}
public override void OnDeselect(BaseEventData eventData)
{
base.OnDeselect(eventData);
this.StartCoroutine(ReselectCoroutine());
}
private IEnumerator ReselectCoroutine()
{
yield return null;
this.ActivateInputField();
this.Select();
}
}

Unity - OnMouseDown double click

I have four GameObjects in the game I am making and when I click on each one a dialogue box opens.
My problem is that I am using OnMouseDown and the first one always need to be clicked twice. It happens just on the OnMouseDown, I have buttons on the game that work just fine.
public static GameObject selectedClient;
public bool isBuying;
private Manager manager;
private void Start()
{
manager = GameObject.FindObjectOfType(typeof(Manager)) as Manager;
}
private void OnMouseDown()
{
if (isBuying == true)
{
selectedClient = this.gameObject;
manager.Talk();
}
else if (isBuying == false)
{
manager.NotTalk();
}
}
The Talk() and NotTalk() are as follows:
public void Talk()
{
dialogueBox.SetActive(true);
Time.timeScale = 0f;
actualClient = Client.selectedClient;
}
public void NotTalk()
{
dialogueBox.SetActive(false);
Time.timeScale = 1f;
}
Someone knows why this happens?
Thanks in advance.
Assuming manager.Talk() opens the dialog, perhaps isBuying is false initially, and is toggled when you click once?
Edit: User updated question with Talk and NotTalk methods.
Since your say that initially, only the time stops, but the dialogueBox doesn't show, by any chance, is this because it isn't populated, or correctly initialized? Can you show is code of what your expect to show up?
It may just be that dialogueBox has nothing to display, and therefore, doesn't, however, by the second click, it somehow it's correctly populated and can display.
If I understand correctly, it seems that OnMouseDown() and Talk() is being called successfully on the first mouse click, but a second mouse click is required to get the dialogueBox to show.
If dialogueBox.SetActive(true) is being called successfully, you could take a look at the Unity Scene Hierarchy window to see if it became active like you expect after the first mouse click. If it did, then you can examine that object to see why it's not appearing on screen. (As another poster mentioned, it may be related to dialogueBox initialization.)
Also, these questions might help us debug and figure out the issue:
What error do you get when you "click on one object and then on other"?
What happens if you click the buttons in a different order? If there are 4 buttons, is it the first button that is always affected, or the first button that you click?
In general, as other posters have suggested, using Debug.Log and Debug.Assert should help you narrow down the issue. Similarly, you can set breakpoints in the code and step through to see if the code is running like you expect. And as I mentioned in this post, the Unity Scene Hierarchy window is useful for debugging as well.
Add a Debug.log(isBuying); above (isBuying == true).
Then you'll know if the OnMouseDown() is being called in the first place and if it proceeds like you expect it to. After that, you should probably be able to fix it yourself, otherwise, please let me know what you found.

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).

Categories

Resources