Unity How to combine each object name? - unity3d

I put several button and i linked onClick() each buttons.
It's okay to print each button name.
But when i click another button, The text didn't combine previous text...
========================================================
public Text showText; //print text
public int count = 0; // count how many times click button
public void ButtonClick_1()
{
Debug.Log("Button Clicked!");
print(gameObject.name);
if (count == 0) { showText.text = gameObject.name; }
else { showText.text += gameObject.name; }
count++;
}
==================================================
First
click button1 => it's okay to print " button1 "
Second
click button1 again => It's okay to print " button1button1"
Third
click button2 => It's not okay to print. print like "button2". I hope it print"button1button1button2"
==========================================================
I want to figure out this.....
I have to put several buttons so use tag is more useful?
I'm not used to use tag. Hope someone help me out.

So as I understood you have this script on multiple buttons.
You have a check on count which initially is 0 for each individual instance.
So instead you could make it static so it is "shared" between all instances or better said makes it a static class member which is not related to any instance.
public Text showText;
public static int count = 0;
public void ButtonClick_1()
{
Debug.Log("Button Clicked!");
print(gameObject.name);
if (count == 0)
{
showText.text = gameObject.name;
}
else
{
showText.text += gameObject.name;
}
count++;
}
So that the text is only overwritten by the very first button click.
Your comment
Actually i print like "000" ,"001",,"012","123".
sounds like you actually want to print always the last three buttons.
I would rather use e.g. a static List<string> like
private static List<string> lastThreeButtons = new List<string>();
public void ButtonClick()
{
lastThreeButtons.Add(name);
if(lastThreeButtons.Count == 3)
{
showText.text = lastThreeButtons[0] + lastThreeButtons[1] + lastThreeButtons[3];
lastThreeButtons.Clear();
}
}

This is how I would do it :
Have a singleton class :
public class TextManager : MonoBehaviour
{
public static TextManager Instance;
public UnityEngine.UI.Text myUIText;
private void Awake()
{
Instance = this;
}
public void AddLine(string _line)
{
myUIText.text += $"{_line} \n";
}
}
Put this Component on a GameObject and link the UIText in the inspector
Then on my ButtonScript I would have this :
public void ButtonClick()
{
Debug.Log($"{gameObject.name} Clicked!");
TextManager.Instance.AddLine(gameObject.name);
}

Related

Start highest unlocked level(scene) on button click

Im new in developing so need some help for my game!
On my game I have 2 buttons one is "Play" and other "Level Select"
I stuck at the "Play" button, need to make a script that is always loading the highest level that is unlocked, not current but highest.
Here is the code that im using for level manager
public List<Button> levelButton;
public Sprite lockimage;
public bool delete;
private void Start()
{
int saveIndex = PlayerPrefs.GetInt("SaveIndex");
for (int i = 0; i < levelButton.Count; i++)
{
if (i <= saveIndex)
{
levelButton[i].interactable = true;
}
else
{
levelButton[i].interactable = false;
levelButton[i].GetComponent<Image>().sprite = lockimage;
}
}
}
public void LevelSelect()
{
int level = int.Parse(EventSystem.current.currentSelectedGameObject.name);
SceneManager.LoadScene(level);
}
public void PlayGame()
{
//code here
}
public void ResetGame()
{
PlayerPrefs.SetInt("SaveIndex", 0);
SceneManager.LoadScene(0);
}
public void DontResetGame()
{
SceneManager.LoadScene(0);
}
}
SceneManager.LoadScene(PlayerPrefs.GetInt("SaveIndex"));
edit: adding some info/context.
I realized that you set level buttons interactivity on the start functions based on the int save_index value you get from PlayerPrefs.
From there, I assumed that you could load the level directly using that same value on the PlayGame function.
Do note that the code I wrote will throw an error, if the "SaveIndex" key is not yet on PlayerPrefs

Write a letter in InputField at Caret Position

I have created some buttons in Unity. When a button is clicked a function is called to write text on an InputText component. The function is following for example:
public void JButton()
{
textshowed.text = textshowed.text + "J";
}
But if I want to write a letter in between a line, the word is written at last of line.
What should i do for the letter to written where the cursor/caret is?
note that it doesnt handle selections in InputField. Below might be enough for your purpose?
public class button : MonoBehaviour
{
public InputField myInput;
int caretposition;
public void JButton()
{
myInput.text = myInput.text.Insert(caretposition, "J");
//Debug.Log(myInput.caretPosition);
}
private void Update()
{
if (myInput.isFocused)
{
caretposition = myInput.caretPosition;
}
}
}

How to focus inputfields while click on 'Tab' button in unity 3d

I want focus input fields using tab button. I have found some code for focusing input fields but that one not satisfied my requirement. In my application one page design like number of input field in both horizontal and vertical formate. In my page have 3 rows of input field and each row have 3 input fields. my requirement is when user click on tab button focus next input field it's working but when reach end of the row, how can I focus next row contain input field. Please suggest any idea. Thank you. You can find my sample page design in below.
Here is the code I have tried.
Selectable next = system.currentSelectedGameObject.GetComponent<Selectable().FindSelectableOnRight();
if (next != null)
{
InputField inputfield = next.GetComponent<InputField>();
if (inputfield != null)
{
inputfield.OnPointerClick(new PointerEventData(system));
system.SetSelectedGameObject(next.gameObject, new BaseEventData(system));
}
}
I had implemented the a similar function by NGUI, you can make some modify if using UGUI. The idea is set the nextInput manually by public variable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIInputTab : MonoBehaviour {
UIInput thisInput;
public GameObject nextInput;
void Start () {
thisInput = transform.GetComponent<UIInput>();
}
void Update () {
if (thisInput.isSelected)
{
if (nextInput != null && Input.GetKeyDown(KeyCode.Tab))
{
UICamera.selectedObject = nextInput;
}
}
}
}
Update
: Dynamic generate random number InputField and assign the next InputField.
InputfieldTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class InputfieldTest : MonoBehaviour {
public GameObject inputFieldPrefab;
public GameObject panel;
private GameObject lastInput;
EventSystem m_EventSystem;
void Start () {
m_EventSystem = EventSystem.current;
for(int i = 0; i < Random.Range(5,10);i++){
GameObject column = new GameObject();
column.transform.parent = panel.transform;
column.name = "Column" + i;
for (int j = 0; j < Random.Range(2, 8);j++){
GameObject input = Instantiate(inputFieldPrefab);
input.transform.parent = column.transform;
input.GetComponent<RectTransform>().position = new Vector3(300+ 200 * j, 300+ 200 * i, 0);
input.name = "InputField" + i + "-" + j;
// set nextInput
if(lastInput != null) {
lastInput.GetComponent<InputTabControl>().nextInput = input;
}
lastInput = input;
}
}
}
void Update () {
GameObject currentSelect = m_EventSystem.currentSelectedGameObject;
if (currentSelect != null)
{
print(currentSelect.name);
GameObject nextInput = currentSelect.GetComponent<InputTabControl>().nextInput;
if (nextInput != null && Input.GetKeyDown(KeyCode.Tab))
{
InputField inputfield = nextInput.GetComponent<InputField>();
if (inputfield != null)
{
inputfield.OnPointerClick(new PointerEventData(m_EventSystem));
m_EventSystem.SetSelectedGameObject(nextInput.gameObject, new BaseEventData(m_EventSystem));
}
}
}
}
}
InputTabControl.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputTabControl : MonoBehaviour {
public GameObject nextInput;
}
Result:
Here's my solution, pretty similar.
public class TabToNextController : MonoBehaviour {
public InputField nextField;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (GetComponent<InputField> ().isFocused && Input.GetKeyDown (KeyCode.Tab)) {
nextField.ActivateInputField ();
}
}
Just add this script to the item you want to be tabbed from. Then in the GUI drop in the inputfield you want to be tabbed to as the "nextField".
I recently ran into this problem and it drove me crazy to think there was no tabs feature. I had never noticed it before. A simple solution that seems to work so far is to use the Selectable class that the UI elements inherit from.
I tested this with the most common types (for me) - InputField, Buttons and drop down lists.
It tabs to each of them as expected
use spacebar to click the button
use spacebar to open the drop down
If you want full web style controls (eg arrow keys) to invoke the drop down, you need to write that code.
public class TabToNextController : MonoBehaviour, IUpdateSelectedHandler
{
public Selectable nextField;
public void OnUpdateSelected(BaseEventData data)
{
if (Input.GetKeyDown(KeyCode.Tab))
nextField.Select();
}
}
Cheers
This is what worked for me:
public Selectable next; //if you want the cursor to start at a specific field
//you can set this in the inspector to any input field
private EventSystem system;
private int tabIndex; //to keep track of cursor
void Start()
{
system = EventSystem.current;// EventSystemManager.currentSystem;
//if you don't want to set next in the inspector, you can do it here
//next = Selectable.allSelectables[0];
tabIndex = 0;
next.Select(); //make sure to do this!
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (tabIndex >= Selectable.allSelectables.Count)
{
next = Selectable.allSelectables[0];
tabIndex = 0;
}
else
{
//if nothing is selected then system.currentSelectedGameObject
//will throw a nullPointer Exception
next = system.currentSelectedGameObject.GetComponent<Selectable>()
.FindSelectableOnDown();
tabIndex++;
}
Debug.Log(next);
if (next != null)
{
InputField inputfield = next.GetComponent<InputField>();
if (inputfield != null)
inputfield.OnPointerClick(new PointerEventData(system)); //if it's an input field, also set the text caret
system.SetSelectedGameObject(next.gameObject, new BaseEventData(system));
}
}
}

Using PlayerPrefs (unity)

I have recently been creating a game with tutorials. Unfortunately, they didn't cover a save score feature. Thanks to another user, I was able to figure out that I needed to use playerprefs. I watched tutorials online, but none of them were helpful. If you can, please help me!
Gold Per Sec Script:
using UnityEngine;
using System.Collections;
public class GoldPerSec : MonoBehaviour {
public UnityEngine.UI.Text gpsDisplay;
public Click click;
public ItemManager[] items;
void Start () {
StartCoroutine(AutoTick ());
}
void Update () {
gpsDisplay.text = GetGoldPerSec() + " Money Per Sec";
}
public float GetGoldPerSec() {
float tick = 0;
foreach (ItemManager item in items) {
tick += item.count * item.tickValue;
}
return tick;
}
public void AutoGoldPerSec() {
click.gold += GetGoldPerSec() / 10;
}
IEnumerator AutoTick() {
while (true) {
AutoGoldPerSec();
yield return new WaitForSeconds(0.10f);
}
}
}
Gold Per Click script:
using UnityEngine;
using System.Collections;
public class Click : MonoBehaviour {
public UnityEngine.UI.Text gpc;
public UnityEngine.UI.Text goldDisplay;
public float gold = 0.00f;
public int goldperclick = 1;
void Update () {
goldDisplay.text = "" + gold.ToString("F0");
gpc.text = "Money Per Click: " + goldperclick;
}
public void Clicked(){
gold += goldperclick;
}
}
My idea was for the game to save when the game is quit, and load as soon as you load the game back up. I am a complete beginner, if anyone can tell me how to do this, please tell me! Thanks! :D
You can use unity's existing functions to achieve this.
For saving data use unity's OnApplicationQuit function like this
void OnApplicationQuit() {
PlayerPrefs.SetFloat("key", value);
}
And for Restoring the values use unity's Awake function like this
void Awake(){
value = PlayerPrefs.GetFloat("key");
}
Please note that PlayerPrefs is an easy way to save data but also an very unsafe way. The player can easily manipulate his "goldValue" since it's just stored as an integer in some file on his device. PlayerPrefs should usually just be used for values the player can changed any way within in game, like volume setting etc.
EXAMPLE CODE
void Save()
{
string filename = "/filename.dat";
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath+filename);
bf.Serialize(file, goldValue); //Use can easily use e.g. a List if you want to store more date
file.Close();
}
bool Load()
{
string filename = "/filename.dat";
if (File.Exists(Application.persistentDataPath + filename))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + filename, FileMode.Open);
goldValue=(int) bf.Deserialize(file);
file.Close();
return true;
}
return false;
}
Add the following code to Click class:
void Awake()
{
LoadData();
}
void OnApplicationQuit()
{
SaveData();
}
void SaveData()
{
PlayerPrefs.SetFloat("gold",gold);
}
void LoadData()
{
gold = PlayerPrefs.GetFloat("gold",0f);
}

gwt get array button value

My gwt project have flexTable show data of image and button on each row and coll.
But my button won't work properly. this is my current code:
private Button[] b = new Button[]{new Button("a"),...,new Button("j")};
private int z=0;
...
public void UpdateTabelGallery(JsArray str){
for(int i=0; i str.length(); i++){
b[i].setText(str.gettitle());
UpdateTabelGallery(str.get(i));
}
}
public void UpdateTabelGallery(GalleryData str){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[z] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[z].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan to show the clicked button text" + b[z].getText());
}
});
z++;
}
I'm still confuse where I should put my button handler. With this current code seems the clickhandler didn't work inside a looping. And if I put it outside loop its not working because I need to know which button clicked. I need to get my index button.but how? Is there any option than array button?
thanks
I was using this method me too, then I've created a new Button with an additional argument.
When I add the ButtonArg I set also the argument:
Panel.add(new ButtonArg("B1", i));
...
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
ButtonArg btn=(ButtonArg) e.getSource();
Window.alert("Button Text="+btn.getArgument());
}
}
public class ButtonArg extends Button {
int argument;
public ButtonArg(String html, int arg) {
super(html);
setArgument(arg);
}
public int getArgument() {
return argument;
}
public void setArgument(int argument) {
this.argument = argument;
}
[...]
The problem is that you refer to 'z' in your click handler, but the value of z changes, so that when your click handler is actually called the value of z is wrong.
You need a local final variable in UpdateTabelGallery which you assign the current value of z to to allow it to be captured by the handler you create. Even better, get rid of z entirely and pass i to UpdateTableGallery:
public void updateTableGallery(GalleryData str, final int i){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[i].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan't to show the clicked button text" + b[i].getText());
}
});
}
But what do you expect:
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
to do? Aside from the incorrect HTML syntax, I don't think adding ypur button to the string will work.
I know this is old, but it didn't look answered and I was looking to do the same thing. Here's one solution:
public void onModuleLoad() {
Button[] b=new Button[26];
RootPanel rp=RootPanel.get("body");
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
Button btn=(Button) e.getSource();
Window.alert("Button Text="+btn.getText());
}
}
MyHandler handler = new MyHandler();
for(int i=0;i<26;i++) {
b[i] = new Button(String.valueOf((char)(65+i)));
b[i].addStyleName("sendButton");
rp.add(b[i]);
b[i].addClickHandler(handler);
}
SimplePanel sPanel = new SimplePanel();
}