Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do I add a char to a string?

Discussion in 'Scripting' started by kaysteinhoff2003, Jul 21, 2020.

  1. kaysteinhoff2003

    kaysteinhoff2003

    Joined:
    Mar 22, 2020
    Posts:
    19
    Hi, so I'm trying to make a pokemon or whateverRetroGameYouWant style Task bar where you get you next objective. Currently I'm trying to make this happen through having to strings, one is my objective and the other one should get updated with a new character each frame(I know that this is a crappy solution but I will fix this). At the moment I get my next character through a char variable but I don't know how to add this to my string.

    Heres my code:
    Code (CSharp):
    1. public Text TaskBoxText;
    2.     public string Task;
    3.    
    4.     //[HideInInspector]
    5.     public bool setTaskActive = true;
    6.     int TaskLength;
    7.     [HideInInspector]
    8.     public string currTaskText;
    9.     public char nextLetter;
    10.    
    11.     void Start()
    12.     {
    13.         TaskLength = Task.Length;
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         if(setTaskActive)
    19.         {
    20.             StartCoroutine(WriteTask());
    21.         }
    22.     }
    23.    
    24.     IEnumerator WriteTask()
    25.     {
    26.         for(int i = 0; i < TaskLength; i++)
    27.         {
    28.             char nextLetter = Task[i];
    29.            
    30.            
    31.             yield return null;
    32.         }
    33.     }
     
  2. ScamTheMan

    ScamTheMan

    Joined:
    Oct 4, 2018
    Posts:
    75
    if you want to place char in the end of the string it's as simple as
    Code (CSharp):
    1. string += char;
    If you want to place char or string in for example middle of the string you may use string.Insert
    Code (CSharp):
    1. string currTaskText = "hello";
    2. int position = 2;
    3.  
    4. currTaskText = currTaskText.Insert(position, "text");
    5.  
    position is as it says position where your code should put a "text" in currTaskText

    Output should be: hetextllo
     
  3. kaysteinhoff2003

    kaysteinhoff2003

    Joined:
    Mar 22, 2020
    Posts:
    19
    Dude you don't know how dumb I fell right now :) Thanks for the reply I tryied it and it worked perfectly thanks man