How can I make a button to act like a toggle or maybe using a toggle and make the toggle to looks like a button? - c#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GenerateUIButtons : MonoBehaviour
{
public Button buttonPrefab;
public GameObject parent;
public int numberOfButtons;
public float spaceBetweenButtons;
private Button[] buttons;
// Start is called before the first frame update
void Start()
{
buttons = new Button[Rotate.names.Length];
for (int i = 0; i < buttons.Length; i++)
{
buttons[i] = Instantiate(buttonPrefab) as Button;
buttons[i].name = Rotate.names[i];
buttons[i].transform.SetParent(parent.transform, false);
int j = i;
buttons[i].onClick.AddListener(() => ButtonClicked(j));
}
}
void ButtonClicked(int buttonNo)
{
Debug.Log("Clicked On " + buttons[buttonNo]);
}
// Update is called once per frame
void Update()
{
}
}
I want that inside the ButtonClicked when clicking on a button the text inside color will change to green and stay green for the clicked button. And if clicking on the same green button again change the color back to the original.
Like a switch.

I created a custom one few days ago, take a look on the code below.
Here you can see it in action: https://youtu.be/sl9EheTbmhE
ToggleButton.cs
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class ToggleButton : MonoBehaviour, IPointerClickHandler
{
public ToggleEvent CheckedChanged = new ToggleEvent();
Image _image;
Color _originalColor;
bool _checked;
[SerializeField] Color _checkedColor;
[SerializeField] ToggleButtonGroup _group;
[SerializeField]
public bool Checked
{
get
{
return _checked;
}
set
{
if (_checked != value)
{
_checked = value;
UpdateVisual();
CheckedChanged.Invoke(this);
}
}
}
void Start()
{
_image = GetComponent<Image>();
_originalColor = _image.color;
if (_group != null)
_group.RegisterToggle(this);
}
private void UpdateVisual()
{
_image.color = Checked ? _checkedColor : _originalColor;
}
public void OnPointerClick(PointerEventData eventData)
{
Checked = !Checked;
}
[Serializable]
public class ToggleEvent : UnityEvent<ToggleButton>
{
}
}
ToggleButtonGroup.cs
using System.Collections.Generic;
using UnityEngine;
public class ToggleButtonGroup : MonoBehaviour
{
List<ToggleButton> _toggles = new List<ToggleButton>();
public void RegisterToggle(ToggleButton toggle)
{
_toggles.Add(toggle);
toggle.CheckedChanged.AddListener(HandleCheckedChanged);
}
void HandleCheckedChanged(ToggleButton toggle)
{
if (toggle.Checked)
{
foreach (var item in _toggles)
{
if (item.GetInstanceID() != toggle.GetInstanceID())
{
item.Checked = false;
}
}
}
}
}

Related

Typewriter effect that shows one character per click on a button in Unity C#

I need help with creating a code for a typewriter effect that only displays one character per click(ui button), I'm really new to Unity and coding as a whole, and I used a tutorial to use the typewriter effect, then i tried to make it so it only works as one character per click on the button, but it didn't work.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TypeWriterEffect : MonoBehaviour {
public float delay = 0.1f;
public string fullText;
private string currentText = "";
public Button toggleButton;
bool toggle = false;
void Start () {
toggleButton.onClick.AddListener(Toggle);
}
void Toggle()
{
StartCoroutine(ShowText());
toggle = true;
}
IEnumerator ShowText(){
if (toggle == true)
{
for (int i = 0; i < fullText.Length; i++)
{
this.GetComponent<Text>().text = currentText;
currentText = fullText.Substring(0, i);
yield return new WaitForSeconds(delay);
}
toggle = false;
}
}
}
If you really want it to only display one character per click on a UI button, you can cut it down to something like this:
using UnityEngine;
using UnityEngine.UI;
public class TypeWriterEffect : MonoBehaviour
{
public string fullText;
public Button toggleButton;
public int carriage=0;
void Start () {
toggleButton.onClick.AddListener(Clicked);
GetComponent<Text>().text = fullText.Substring(0, carriage);
}
void Clicked()
{
carriage++;
GetComponent<Text>().text = fullText.Substring(0, carriage);
}
}

How to button enabled/disabled on Ironsource Rewarded Video

I have a button for showing rewarded advertisement. If the advertisement is loaded, I want to enable this button, also if the advertisement is not loaded, I want to disabled this button. But, the code is not working, When i have no internet connection, the button is always enabled. How can i do this issue?
Here is my code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RewardedShop : MonoBehaviour
{
public static RewardedShop Instance { get; set; }
private void Awake()
{
Instance = this;
}
public string appkey;
public GameObject afterRewardedScreen, mainScreen;
public Button btnWatchSHOP;
public GameObject btnActive;
RewardedGameObject[] go;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
btnWatchSHOP.interactable = false;
}
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
counter = 0;
IronSource.Agent.showRewardedVideo("ShopRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
BtnActive();
}
int counter = 0;
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
if (counter < 1)
{
RewardHandlerSHOP.Instance.Reward();
counter++;
}
}
public void Reward()
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("TxtTotalSHOPCoin").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
}
public void BtnActive()
{
bool available = IronSource.Agent.isRewardedVideoAvailable();
if (available)
{
btnWatchSHOP.interactable = true;
}
else
{
btnWatchSHOP.interactable = false;
}
}
}

How do I fix this Idle-Car Game Script

I am trying to have a game, in which everyone can buy cars (and I save that data to playerprefs). So I have 9 trails for the cars in my game and I am trying to write some code so that when you press a button the car & the trail for that car will show up.
When the button next to it is clicked, it saves that data so when people restart the game, they will still have the car & trail open and won't need to press the button again.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public Button[] TrailLevel;
public GameObject[] Cars, Trails;
public Text text;
public int CurrentCarToSpawn = 0;
private void Start()
{ }
private void FixedUpdate()
{
UpdateCar();
}
public void InstantiateCar()
{
TrailLevel[CurrentCarToSpawn].gameObject.active = false;
MineLevel[CurrentCarToSpawn+1].interactable = true;
PlayerPrefs.SetInt("TrailCountA", PlayerPrefs.GetInt("TrailCountA") + 1);
PlayerPrefs.Save();
CurrentCarToSpawn++;
UpdateCar();
}
void UpdateCar()
{
int TrailCountA= PlayerPrefs.GetInt("TrailCountA", 1);
for (int i = 0; i < TrailLevel.Length; i++)
{
if (i + 1 > TrailCountA)
{
TrailLevel.interactable = false;
}
if (TrailLevel.interactable)
{
Trains[CurrentCarToSpawn].gameObject.active = true;
Mines[CurrentCarToSpawn].gameObject.active = true;
}
}
text.text = PlayerPrefs.GetInt("TrailCountA").ToString();
}
}
From what I can see with your code, this is how I would approach it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public Button[] TrailLevel;
public GameObject[] Cars, Trails;
public Text text;
public int CurrentCarToSpawn = 0;
private void Start()
{
// Load the current car. ADDED
CurrentCarToSpawn = PlayerPrefs.getInt("savedSelection", 0);
// Since we are loading the last selection, we need to call our
// instantiation method so it can activate the appropriate
// GameObjects.
InstantiateCar();
}
private void FixedUpdate()
{
UpdateCar();
}
public void InstantiateCar()
{
TrailLevel[CurrentCarToSpawn].gameObject.active = false;
MineLevel[CurrentCarToSpawn+1].interactable = true;
PlayerPrefs.SetInt("TrailCountA", PlayerPrefs.GetInt("TrailCountA") + 1);
// Save that this is our current selection.
PlayerPrefs.SetInt("savedSelection", CurrentCarToSpawn);
PlayerPrefs.Save();
CurrentCarToSpawn++;
UpdateCar();
}
void UpdateCar()
{
int TrailCountA= PlayerPrefs.GetInt("TrailCountA", 1);
for (int i = 0; i < TrailLevel.Length; i++)
{
if (i + 1 > TrailCountA)
{
TrailLevel.interactable = false;
}
if (TrailLevel.interactable)
{
Trains[CurrentCarToSpawn].gameObject.active = true;
Mines[CurrentCarToSpawn].gameObject.active = true;
}
}
text.text = PlayerPrefs.GetInt("TrailCountA").ToString();
}
}

Button and PlayerPrefs

i have a code i want when i click button not set active (with PlayerPrefs) but problem when i run game a button not set active before i click it (button)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fcfg : MonoBehaviour
{
public GameObject butt;
void Start()
{
if (PlayerPrefs.GetInt("ButtonActivate") == 0)
{
butt.gameObject.SetActive(false);
}
else if (PlayerPrefs.GetInt("ButtonActivate") == 1)
{
butt.gameObject.SetActive(true);
}
}
void Update()
{
}
public void whenbuttonclick()
{
this.gameObject.SetActive(false);
PlayerPrefs.SetInt("ButtonActivate", 0);
}
}

Scenes are not loading

Something really odd happens when I'm trying to load a scene.
The code that generates an error (I guess):
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class playSc : MonoBehaviour {
public string levelToLoad;
public Animator menumusic;
public GameObject background;
public GameObject text;
public GameObject progressSlider;
public Text progressText;
public Slider progressBar;
private int loadProgress = 0;
public void close()
{
Application.Quit();
}
public void play()
{
menumusic.SetBool("FadeOUT", true);
GameObject.Find("Clock").SetActive(false);
progressText.text = "Think about the Universe to continue.\nThinking progress:";
StartCoroutine(DisplayLoadingScreen("Game"));
}
public void credits()
{
menumusic.SetBool("FadeOUT", true);
GameObject.Find("Clock").SetActive(false);
progressText.text = "Think about your behaviour.\nThinking progress:";
StartCoroutine(DisplayLoadingScreen("Credits"));
}
IEnumerator DisplayLoadingScreen(string level)
{
background.SetActive(true);
text.SetActive(true);
progressSlider.SetActive(true);
AsyncOperation async = SceneManager.LoadSceneAsync(level);
while (!async.isDone)
{
loadProgress = (int)(async.progress * 100);
progressBar.value = loadProgress;
yield return null;
}
}
}
I tried to use Application.LoadLevel() and it still is not working. It was working with this code but at one moment it stopped.

Categories