substring requires a start index and a char count, or just a start index. Which means if you have no letters in your string and you try to substring it at index 3, there is no index 3 and it will be out of range.
You shouldn’t do this in update. You should simply when updating your text/string do a check at that point to see if it has more than 3 chars and then substring it. Otherwise, just set the value. But this also depends on how you are setting this. If this is an inputfield where a player can enter info, you may also want to provide feedback and there is also a way on inputfields to set char limits.
If you are doing an inputfield, why not just use the character limiter built into the input field?
And as KelsoMRK said, you aren’t assigning the value back.
Like a keyboard?
If so, just create a variable int and every time a button is pressed add 1 to it. Everytime a ‘backspace’ occurs take 1. In the function on the button where you add a letter have an if characterCount < maxCharacter, do something, else return, this is not allowed, too many characters.
/* It wasn’t easy, but I came up with a solution to detect which button is being pressed in Unity.
I still have to program the C# code to run only once for every key but it’s almost what I need.
Never mind… I figured that out within a couple minutes. */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
public string key;
private string keySet;
// Start is called before the first frame update
void Start()
{
key = “None”;
}
void OnGUI()
{
key = Input.inputString;
if (key.Length > 1)
{
// index of string array and number of characters accepted
key = key.Substring(0, 1);
}
if (Input.anyKeyDown && key != keySet)
{
if (key != “None”)
{
Debug.Log(key);
keySet = key;
}
}
}
}
public TMP_InputField mainInputField;
public string playerName;
public Text Text;
void Start()
{
//Changes the character limit in the main input field.
mainInputField.characterLimit = 10;
}
public void Update()
{
playerName = mainInputField.text;
Text.text = playerName;
}