I am trying to access a button on the UI and use the onClick() event with a button of my VR controller (primary button). After the button is pressed I want to call a method. Now how do I do this with a controller and not with a click with the mouse? I hope you can help me out.
Kind regards
So create a script similar to the rough psuedo code below and drop it onto the UI button.
public class ButtonHandler : MonoBehaviour
{
private Button _button;
void Awake()
{
_button = GetComponent<Button>();
}
void Update()
{
if (Input.GetButtonDown("x")) {
_button.onClick.Invoke();
}
}
}
This will check for the button press (need to update that so it checks for the correct button) and then invoke the unity event that you already have assigned in the onClick() on the button.
Related
I have a prefab button and a non prefab Game manager. I want this button to be cloned and call a function in Game Manager. How can I do that?
[SerializeField]
private GameObject buttonPrefab;
[SerializeField]
private Transform canvas;
public void CloneButton()
{
var buttonComponent = Instantiate(buttonPrefab, canvas).GetComponent<Button>();
buttonComponent.onClick.AddListener(TaskOnClick);
}
public void TaskOnClick()
{
// things happen when the button clicked
}
You have to give a reference for the prefab, and the canvas object as a parent for the button via inspector.
I've made a 3d game and I have a first person controller, control by a joystick. I want my player to shoot only when I touch a button on the screen, but now my player shoots if I touch anything on the screen. This is the script for the shoot function:
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public Button button;
// Start is called before the first frame update
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
button.onClick.AddListener(TaskOnClick);
}
// Update is called once per frame
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
}
void Shoot()
{
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
void OnCollisionEnter(Collision collision)
{
Debug.DrawRay(collision.contacts[0].point, collision.contacts[0].normal, Color.green, 2, false);
}
void TaskOnClick()
{
Shoot();
}
}
Your Shoot() method runs whenever you press the "Fire1" button, since the only check you are doing is if (Input.GetButtonDown("Fire1")).
If you want to depend on a button to fire you need to take this part of the code out and call Shoot() whenever you click the button.
You can add the event to the button using code, as explained here
public Button m_YourFirstButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
or you could call it from the inspector by referencing your Gun monobehaviour.
I want to wait until "next" button is pressed then continue
child.addChild(tmp);
childrenAdded.Push(tmp);
neighbor.GetComponent.<Renderer>().material.mainTexture = null;
-WAIT UNTIL CLICK ON NEXT BUTTON THEN CONTINUE-
toExpand.Push(tmp);
any idea? I tried:
while(true) {
if(GUI.Button(Rect(500,680 ,100,30),"Next"))
break
}
But it doesn't work; it freezes.
Instead of waiting, you can just have your code called when the button is clicked, like this:
void OnGUI() {
if(GUI.Button(Rect(500,680 ,100,30),"Next"))
toExpand.Push(tmp);
}
}
If possible, consider using Unity 4.6 or later so you can use the new UI which is much easier work with.
You can use Toggle button instead of button so you controll a boolean with toogle and loops what you need in your Update or LateUpdate function like this:
private Rect myRect = new Rect(500,680 ,100,30);
private bool myToggle = false;
void OnGui() {
myToggle = GUI.Toogle(myRect, myToggle, "Next");
}
void Update() {
if(myToggle){
// what I need to create while true;
}
}
Note that is not a good practice to create a new Rect every OnGUI cycle because it runs more than once per frame and it will create a performance issue.
Reading your code again may I could've misinterpreted your needing so if you could clarify what you really what your code to do would be easier to help.
Also, if you just need a "wizard" like sequence of actions I suggest you to take a look on delegates and use something like this:
delegate void MyDelegate();
private MyDelegate myDelegate;
private Rect myRect = new Rect(500,680 ,100,30);
void Start () {
myDelegate = FirstFunction;
}
void FirstFunction() {
// will execute until next button is clicked
}
void SecondFunction() {
// will execute after next button is clicked
}
void OnGui() {
if(GUI.Button(myRect, "Next")) {
myDelegate = SecondFunction;
}
}
How do I prevent the Scroll Rect from moving with the mouse say for example I only want a scroll bar to move it and not by dragging across the image or text with the mouse?
SubClass ScrollRect and override it's drag handlers?
Untested but should work:
public class NoDragScrollRect : ScrollRect {
public override void OnBeginDrag(PointerEventData eventData) { }
public override void OnDrag(PointerEventData eventData) { }
public override void OnEndDrag(PointerEventData eventData) { }
}
A simpler solution would be to add a canvas group to the scrollable RectTransform and set it to not block raycast. That way no drag will happen on the RectTransform. This of course only works if you dont need the RectTransform to be interactable at all, otherwise the other answer will do the trick
In a scene of my quiz game I have an animation object that changes for another animation when a button to move to the next question is pressed (the button reload the scene). I would like to keep the animation, the last animation referenced to the object, after the scene is reloaded, but I don't know how. The object always returns to its normal state (the first animation).
I currently have a script called 'tower' referenced to the object where I make a static object and a DontDestroyOnLoad function:
public static SpriteRenderer towerAnimation;
void Awake()
{
DontDestroyOnLoad(gameObject);
towerAnimation = GetComponent<SpriteRenderer>();
}
And this code in the Update of 'GameManager' script:
public static int counterQuestionChances = 2;
void DestroyTower()
{
if (counterQuestionChances == 1)
{
Tower.towerAnimation.SetTrigger("error 1");
}
else
{
if (counterQuestionChances == 0)
{
Tower.towerAnimation.SetTrigger("error 2");
}
}
But it doesn't work. I'm taking shots in the dark because I don't know how to solve this. I'd appreciate if you could give me any ideas that can help me with this. Thanks!
You're going to have to use the SceneManagement library that Unity has so when the scene changes the method below called OnActiveSceneChanged gets called.
using UnityEngine.SceneManagement;
public class Tower : MonoBehaviour
{
public static SpriteRenderer towerAnimation;
public int storedCounter = 0;
void Awake()
{
DontDestroyOnLoad(gameObject);
towerAnimation = GetComponent<SpriteRenderer>();
SceneManager.activeSceneChanged += OnActiveSceneChanged;
}
private void OnActiveSceneChanged(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.Scene currentScene)
{
//tower animation stuff here
}
}