-1

I have a simple scene in unity where I have a canvas with an input field and the code I have is simple

using System.Collections;   
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextRecstriction : MonoBehaviour
{

    public Text text;

    public string a = "a";
    public string b = "a";
    public string c = "a";
    public string d = "a";
    public string e = "a";
    public string f = "a";
    public string g = "a";
    public string h = "a";
    public string i = "a";
    public string j = "a";
    public string k = "a";
    public string l = "a";
    public string m = "a";
    public string n = "a";
    public string o = "a";
    public string p = "a";
    public string q = "a";
    public string r = "a";
    public string s = "a";
    public string t = "a";
    public string u = "a";
    public string v = "a";
    public string w = "a";
    public string x = "a";
    public string y = "a";
    public string z = "a";
    

    // Update is called once per frame
    void Update()
    {
        
    }
}

I want to add if statements to check if any of the letters are in the text element how do i go through the text to fetch if any of the strings are included in the text

can123ten
  • 1
  • 3

1 Answers1

0

If you use the the .Contains() method, it returns a bool with whether or not the string contains a given letter.


    string textOnCanvas
    
    void update(){

     if(textOnCanvas.Contains('a'))
     {
      //whatever you want to happen if it does contain the letter
     }

    }

Additionally you could create an array[] with all of the letters, and use a for/foreach loop to check for each of them.

public string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
 abcdefghijklmnopqrstuvwxyz"

 char[] alphabetArray = alphabet.ToCharArray();

 foreach(char character in alphabet)
 {
   if(textOnCanvas.Contains(character)
     {
      //whatever you want to happen if it does contain the letter
      //if you want the test to stop once a match has been found, you can add:
      break;//To take you out of the loop
     }
 }

Kailokk
  • 11
  • 2
  • Even though it is a duplicate (see link on question) this answer still brings value in specific for Unity in terms of the alphabet + `ToCharArray` which makes it quite handy and expandable .. I would still rather use a `string` as public field since it is just way easier to maintain in the Unity Inspector than a `char[]` ;) – derHugo Dec 14 '21 at 18:21
  • Also note that currently you might also have multiple matches .. to be fair OP didn't define what happens in such case but you might want to `break` after the first match – derHugo Dec 14 '21 at 18:23
  • Excellent points, thank you! – Kailokk Dec 14 '21 at 18:32