- Home /
Split string, add action to every word
There is a text. Which must be split into words and to create an action to every word, when pressed, plays a sound file, specified for this word.
How to do it automatically? Let's say I know how to split a string into words, and how to add action to every word?
I need to create gameObect according to each word and specify Rect according to a word position, then add script to interact with this Rect? But how to calculate each word position?
And maybe there are another solution?
I add a little more explanation:
I dont know how to do 1) and 2).
public class Texttext : MonoBehaviour {
public GUIText guiText;
public ActionOnClick actionScript;
// Use this for initialization
void Start () {
guiText.text = "Text, text text!\nText? Text!\nText, text text, text...";
string[] split = guiText.text.Split(new char[] { ' ', ',', '.', ':', '\t', '\n'});
foreach (string str in split)
if (str != "")
{
Debug.Log(str);
// Create GameObject
GameObject go = new GameObject(str);
// 1) Calculate word position (!!!)
Vector3 wordPosition = new Vector3(0, 0, 0);
// 2) Create Rect according this position (!!!)
Rect wordRect = new Rect(wordPosition.x, wordPosition.y, wordWidth,wordHeight);
// Add action to this gameObject
go.AddComponent<ActionOnClick>();
go.GetComponent<ActionOnClick>().wordPosition = wordPosition;
go.GetComponent<ActionOnClick>().wordRect = wordRect;
}
}
// Update is called once per frame
void Update () {
}
}
The problem is to automate this: Write text -> Calculate -> Click on Word get a Sound.
And that's what I want to get:
"HOW DO I CODE?" is basically the question you are asking. String manipulation, iteration and arrays are pretty basic concepts.
Answer by Sisso · Oct 09, 2013 at 12:29 PM
split a string into words,
http://msdn.microsoft.com/en-us/library/b873y76a.aspx
create gameObject
http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html
specify Rect according to a word position
http://docs.unity3d.com/Documentation/ScriptReference/Camera.WorldToScreenPoint.html
how to calculate each word position
http://docs.unity3d.com/Documentation/Manual/GameInterfaceElements.html