How to change button image on click Unity - image

I got unlock button for game, it works,but I want to user himself can press button, and then button image change. As you can see in code below when score is >= 10, buttons image change immediately. How can I achieve that?
public GameObject lockBtn;
Image lockComp;
public Sprite myLockImage;
public Sprite myLockSecondImage;
/////////////////////////////////////////
lockComp = lockBtn.GetComponent<Image> ();
if (bestScore >= 10) {
lockComp.sprite = myLockImage;
}
else
{
lockComp.sprite = myLockSecondImage;
}

Simply add an event listener to your button so as to change the image.
lockComp.sprite = myLockSecondImage;
if (bestScore >= 10) {
lockBtn.GetComponent<Button>().onClick.addEventListener( OnLockButtonClicked ) ;
}
// ...
private void OnLockButtonClicked()
{
lockComp.sprite = myLockImage ;
}
Be carefull to not add this snippet of code into the Update function. Otherwise, you will add a new event listener every frame
Saving the "unlocked state" of the button into a file so as to not show the unlocked sprite when the user starts the game again could be a good idea.

Put your code in a file and class named ButtonScript and in a method named OnButtonClick()
public class ButtonScript : MonoBehaviour {
public void OnButtonClick(){
lockComp = lockBtn.GetComponent<Image> ();
if (bestScore >= 10) {
lockComp.sprite = myLockImage;
}
else
{
lockComp.sprite = myLockSecondImage;
}
}
}
Then add this script on your Button and in the OnClick event add a reference to the Button and his Method:

Related

How can I make title screen?

I am trying to make title screen when i press a button. It goes when i press the button game stops
with Time.timeScale = 0f; and I am trying to do is when I click button time stops and two buttons shows up for quit and resume and I am trying to do when I press the button it sets show = true; in script for Menu button. This work but when I type script for button "resume" witch is:
private void Awake()
{
gameObject.SetActive(false);
}
private void Update()
{
show();
}
private void show ()
{
if (show = true)
{
gameObject.SetActive(true);
}
}
But there is an Error: Cannot assign to show because it is a method group.
I don't know what this mean and how I can repair my code.
it would be great if you made bool
here some example of your code
public bool show;
private void Awake()
{
gameObject.SetActive(false);
}
private void Start()
{
show = false;
gameObject.SetActive(false);
}
private void gameobject()
{
if (show = true)
{
gameObject.SetActive(true);
}
else(show = false){
gameobject.SetActive(false);
}
}
Deleted show() and replaced update() with Start()
Useful information about bool
https://docs.unity3d.com/ScriptReference/30_search.html?q=bool
source: unity documentary

Is there a way to set a button onClick function to a function on a prefab that is not in a Scene in Unity?

I have a prefab that instantiate on running the program. The prefab is not already in the scene. On this prefab there is a script with a function that should be called when a button is clicked.The button is in the scene. In the button's inspector I drag and dropped the prefab and chose the function to execute. But on running, I get an exception. Is there a way for the button to reference a function on a prefab that is not in the scene?
Apart from making handler static, you can just find the instance of the button:
public class MyScript: MonoBehaviour
{
void Awake()
{
Button myButton = GetReferenceToButton();
myButton.onClick.AddListener ((UnityEngine.Events.UnityAction) this.OnClick);
}
public void OnClick()
{
Debug.Log("Clicked!");
}
private Button GetReferenceToButton()
{
Button btn = null;
//Find it here
return btn;
}
}
Also you need to cast the delegate to UnityEngine.Events.UnityAction before adding is as listener.
If you have a user interface with multiple buttons in a prefab instantiated programmatically, you can use GetComponentsInChildren to access all the buttons:
public void onUIcreated()
{
// Add event listeners to all buttons in the canvas
Button[] buttons = canvasPrefab.GetComponentsInChildren<Button>();
for (int i = 0; i < buttons.Length; i++)
{
string identifier = buttons[i].name;
buttons[i].onClick.AddListener(delegate { OnButtonTapped(identifier); });
}
}
public void OnButtonTapped(string identifier)
{
Debug.Log("Pressed button:" + identifier);
}

How to know if Unity UI button is being held down?

I am using Unity 5.2 UI. I am working on a game for iOS. I have a custom keyboard. I want to add the functionality to the del/backspace key so that when i hold the del key for more than 2 secs, it deletes the whole word instead of a single letter, which it deletes on single clicks. How do I achieve that?
Using the UGUI event you'd create a script like the following and attach it to your button:
using UnityEngine;
using UnityEngine.EventSystems;
public class LongPress : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
private bool isDown;
private float downTime;
public void OnPointerDown(PointerEventData eventData) {
this.isDown = true;
this.downTime = Time.realtimeSinceStartup;
}
public void OnPointerUp(PointerEventData eventData) {
this.isDown = false;
}
void Update() {
if (!this.isDown) return;
if (Time.realtimeSinceStartup - this.downTime > 2f) {
print("Handle Long Tap");
this.isDown = false;
}
}
}

unity object reset button and slider

I want to make that on keyboard r button press reset object into position: x112 y8 z153. Object name is Sphere i can rename it.
And i want a gui slider that can change forceadder 50f in game from 0 to 500.
I am a beginner. Just finished begginer tutorials. What code do i need to get? i tried to make that reset button my self but dosent do anything to me it says in debug that its pressed but it dosent reset it. Soo i removed that code.
My code right now:
using UnityEngine;
using System.Collections;
public class ShootMeBall : MonoBehaviour
{
public float forceadder = 500f;
void OnMouseDown()
{
rigidbody.AddForce (transform.forward * forceadder);
rigidbody.useGravity = true;
}
void Awake()
{
Debug.Log ("I am awake.");
Screen.lockCursor = true;
gameObject.renderer.material.color = Color.yellow;
}
}
Here's the solution(You will need to drag the object you're moving into the scripts GameObject variable in the inspector, and the slider into the slider slot):
using UnityEngine;
using UnityEngine.UI;
using System;
public class Example : MonoBehavior
{
public GameObject go;
public Slider slider;
private float force;
void Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
go.transform.position = new Vector3(112f, 8f, 153f);
}
force = (float)slider.value;
}
}
Don't forget to set the min/max values of the slider, and the value "Use whole numbers" to true if it matters.

How to Work With GUI button in unity

I want to get user input through GUI Button in unity3d unityscript. I have write this script to get user input through keyboard
var f_hor : float = Input.GetAxis("Horizontal");
//Get Vertical move - move forward or backward
var f_ver : float = Input.GetAxis("Vertical");
if (f_ver < 0) {
b_isBackward = true;
} else {
b_isBackward = false;
}
its work fine and its give me 0 and 1 accordingly..But i want the same action through GUI button.Like if i have four GUI button..and they work same as this did...I can make GUI button in ONGUI function..But how can i achieve this functionaility...Any help
Altough I don't know if it is the best way to go (Unity's gui element are not the best for ingame HUD or menu), this should do the job:
private bool buttonPressed = false;
public void Update()
{
if (buttonPressed)
{
//do what you want
buttonPressed = false;
}
}
Sorry for using C# code, but I don't know JS. It should be easy to translate tough.
public void OnGui()
{
Rect rect = new Rect(...); //your button dimension
if (GUI.Button(rect, "AButton")
{
buttonPressed = true;
}
}
EDIT:
If you want to manually handle input from mouse you can use methods of MonoBehavior such as OnMouseDown or OnMouseUp.
Alternatively you can check from inside Update if a mouse event occured, have a look at Input.GetMouseButton or similar methods of Input class.

Resources