Unity C# dialogue system script displays only first letter of public var - c#

I have a pretty strange problem. I was coding a simple dialogue system, for now it will only display a letter every 0.1 seconds.
I have a TextMeshPro text that contains the text to be displayed.
Here is attached my DialogueLine.cs script:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
namespace DialogueSystem
{
public class DialogueLine : DialogueBaseClass
{
private TextMeshProUGUI textHolder;
[Header ("Text Options")]
[SerializeField] private string input;
private void Awake()
{
textHolder = GetComponent<TextMeshProUGUI>();
StartCoroutine(WriteText(input, textHolder));
}
}
}
it gets the value of my "input" variable, setted from Unity interface. The script calls the "WriteText" coroutine, in the DialogueBaseClass.cs script:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class DialogueBaseClass : MonoBehaviour
{
protected IEnumerator WriteText(string input, TextMeshProUGUI textHolder)
{
for (int i= 0; i < input.Length; i++)
{
textHolder.text += input[i];
yield return new WaitForSeconds(0.1f);
}
}
}
A pretty simple script that adds on my "textHeader" component a letter from the input every 0.1 seconds.
But, here is the problem. The output of my component is only the first letter of the input variable: if in the input I write "Hello" it displays "H".
I really can't find the problem in this script...

Related

Unity c# change light temperatur with script

im trying to write a script that makes the temperature of the light whatever number is set in the float
i need this for later reference when i add a slider or selectable options that determine the temperature of the light
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class lightchange : MonoBehaviour
{
public float Temp = 2000f;
private void pp()
{
Light lightcomp = GetComponent<Light>();
lightcomp.colorTemperature = Temp;
}
}
this is my code but it doesnt seem to work and this is all i could find online to edit componentswhat im trying to change

How can I use indexof and substring and string.format to add random numbers/text in specific place in text?

This is my original code and it's working fine but the text content is already in the editor in a Text UI and therefore it's also in the variable textField.
So I don't want to type the text over again also inside the code. For example the word toBeSearched is "almost" so using the string format it will generate new random number each time I press on space between the words: "almost" and "hours".
But since the text is already in the textField variable I want to parse the place I want to add the random numbers automatic using indexof and substring.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private void Start()
{
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format("Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.", numberName);
}
}
This is the code with the indexof and substring I tried to use but it#s not working good.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private void Start()
{
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string result = null;
string result1 = null;
int ix = textField.text.IndexOf(toBeSearched);
if (ix != -1)
{
result = textField.text.Substring(0, ix + toBeSearched.Length);
result1 = textField.text.Substring(ix + toBeSearched.Length, textField.text.Length - (ix + toBeSearched.Length));
}
result1 = result1.TrimStart();
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format(result + " {0} " + result1, numberName);
}
}
Again the word toBeSearched is "almost" and I used a breakpoint and result contain the text until almost: "Hello my friend, It's about time to wakeup. You were sleeping for almost" and the variable result1 contain the rest of the text: "hours. My name is NAVI and i'm your navigation helper in the game."
But now when I'm pressing the space key it's inserting each time a new random number but it's not replacing the whole text like in the original code above.
So the result is many numbers in the text.
Not sure why it's not working like the original code.
The reason why it's not working is because you're changing the value of textField.text, so when you repeat the process the substrings are generated with this new value, including the number. You shouldn't give up your first solution, it's much cleaner. Store the original value of the text field on Start:
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CustomText : MonoBehaviour
{
public string toBeSearched;
public Text textField;
private string defaultValue;
private void Start()
{
defaultValue = textField.text;
GenerateRandomHour();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GenerateRandomHour();
}
}
private void GenerateRandomHour()
{
string numberName = Random.Range(1, 10).ToString();
textField.text = string.Format(defaultValue, numberName);
}
}
Add the {0} directly to your text field value in the inspector:
Hello my friend, It's about time to wakeup. You were sleeping for almost {0} hours. My name is NAVI and i'm your navigation helper in the game.
The problem is when you are adding a number in a specified spot, so every time you press space, it is using the existing text as the template and thus the old number stays,along with adding a new one.
Instead, you want to search between the two words "almost" and "hours" so you can replace whatevers between them. You can do this the by adding another indexOf search, but itll be easier using regex.
string result = Regex.Replace(textField.text, "(? <=almost).+?(?=hours)" , numberName);
textField.text = result;
Although your first solution looks cleaner, and if you want to keep the text in the inspector, Nathalia's answer would work

How can I get the text and save it in InputField?

I have an array InputFields, in my situation - six InputFields. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
Well, you are using a single variable for all the different player prefs variables, n. So when you change a field (with SubmitName) it uses that n pref variable and changes it. This will correspond to the last value you gave to n in your loop.
An option would be to have that be an array too (private string prefValues[]) or to pass the calling input field to SubmitName (or rather it's name) and use that instead of n.
A little example (from your code you can actually change your GameObject[] to InputField[] which saves some GetComponent calls):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventTest : MonoBehaviour
{
public InputField[] inputFields;
void Start ()
{
foreach(InputField field in inputFields)
{
var se = new InputField.SubmitEvent();
se.AddListener(delegate {
SubmitText(field.name, field.text);
});
field.onEndEdit = se;
}
}
public void SubmitText(string prefKey, string prefVal)
{
Debug.Log("Saved " + prefVal + " to " + prefKey);
}
}
Edit:
Added lines for saving/loading from prefs in the code below. For my test setup I just have two scenes. Both have two input fields and a button that calls that scene change. I can type stuff on the fields as I like, change scenes and it stays. Also upon restarting playmode in the editor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class EventTest : MonoBehaviour
{
public InputField[] inputFields;
void Start ()
{
foreach(InputField field in inputFields)
{
// Get field values from player prefs if existing
// (it should only not exist the very first time or if you delete/clear the prefs)
if(PlayerPrefs.HasKey(field.name))
field.text = PlayerPrefs.GetString(field.name);
var se = new InputField.SubmitEvent();
se.AddListener(delegate {
SubmitText(field.name, field.text);
});
field.onEndEdit = se;
}
}
public void SubmitText(string prefKey, string prefValue)
{
// store the typed text of the respective input field
PlayerPrefs.SetString(prefKey, prefValue);
}
public void ChangeScene()
{
if(SceneManager.GetActiveScene().name == "Scene1")
{
SceneManager.LoadScene("Scene2");
}
else
{
SceneManager.LoadScene("Scene1");
}
}
}
If you want to save the data, after the application stopped or if it gets paused, you need to add some more functions to your MonoBehavior so that it can handle additional actions on a system end or pause.
Look at following functions in the documentation
OnApplicationQuit()
OnApplicationPause()
These functions will be called automatically. Inside these functions you need to iterate through the textfields and save them. It is one of the last functions that will be called before the program will lose it's recourses.
Regarding the Scene change, you would need the new scene to tell the old one to do any further actions. Like you can read in this post, there is only a way to know if a new scene was loaded.
Maybe you have a place where you can save the last active scene object and then call the last scenes function to do the saving process while the object is not cleared.

Saving Data to Variable With Different Script File Unity C#

Iam confused saving data to variable with different script file.
For Example :
File player.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class player : MonoBehaviour {
public int coin = 1000;
}
File levelupstorage1raw.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Linq;
public class levelUpStorage1Raw : MonoBehaviour {
public player Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnClickWood () {
Player.coin = Player.coin + 1000;
}
}
In this script player.cs :
public class player : MonoBehaviour {
public int coin = 1000;
}
I have inisial the coin = 1000, this mean int coin have 1000.
In Other script file levelupstorage1raw.cs :
public player Player;
// Use this for initialization
public void OnClickWood () {
Player.coin = Player.coin + 1000;
}
I have add more coin 1000 to Player.coin.
Now my question is : where the Player.coin 1000 is save ? is it save to it own file variable Player.coin or
is it save to player.cs file variable coin ?
If it save to player.cs file variable coin then variable coin now should have 2000.
You clearly have to learn a bit more about programming. Try looking for tutorials online.
Regarding your question, if I simplify things a bit to give you an idea:
A variable is something that can change. What is written in your Player.cs file is the default value, the one it will have when starting the program. When you write Player.coin = Player.coin + 1000;, the variable value changes, so Player.coin is now 2000.
At this point the first value (1000) is lost because the variable in your program has been set to 2000. But this has nothing to do with the file.
When you run your program, your file has already been transformed to a program. The file with the code is just there to tell the computer how to create the program, but it won't be modified when you run the program.
I hope this helps you understand what happens in your example. I still thing you should look for tutorials. Even basic stuff will be really difficult to achieve if you don't know the basics

PointerClick only works once

I have a problem & it's annoying me.
I have a prefab that containing just one UI Image (supposed to be square). I'm trying to create (via script) many of them (Like 5x5 or 10x10). I added a pointerClick event with eventTrigger for detect click & print the clicking objects' name. But there is a problem. PointerClick event only works once. It is supposed to give result for every click. Thanks for helping.
Here is my prefabs' photo & my scripts:
prefab_photo
Creation
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class gameSlots : MonoBehaviour {
public GameObject gameSlot;
public int gameLevel=5;
void Start(){
gameLevel = PlayerPrefs.GetInt ("levelSelect");
RectTransform gameTable=gameObject.GetComponent<RectTransform>();
float width = gameTable.rect.width/gameLevel;
for (int i=0; i<gameLevel; i++){
for(int j=0;j<gameLevel;j++){
GameObject slot=(GameObject)Instantiate(gameSlot);
slot.transform.SetParent(gameObject.transform,false);
slot.name=(i+1)+"-"+(j+1);
RectTransform rectTrans = slot.GetComponent<RectTransform>();
float x= -gameTable.rect.width/2 + width*i;
float y= gameTable.rect.height/2 - width*j-width;
rectTrans.offsetMin=new Vector2(x,y);
x= rectTrans.offsetMin.x + width;
y= rectTrans.offsetMin.y + width;
rectTrans.offsetMax=new Vector2(x,y);
}
}
}
script for PointerClick event
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class slotCheck : MonoBehaviour {
public void name(){
Debug.Log (transform.name);
}
}

Categories

Resources