So i’m trying to learn how this works. Basically just like silent hill and resident evil games or pretty much games today.
So your player enters a trigger, presses a button when you’re in the trigger, then text would display.
But not just one text. But an array of text which can be displayed individually by button press. Like this one in Silent Hill 2.
So as you can see, The moment I enter a trigger and press a button whilst on it, Text would display via GUI rectangle. And as I press the button again, the next array of text would be displayed replacing the first one.
Now im guessing a foreach loop would be used to display the arrays of text. I did the basic one in which you just enter a collider and display the text directly. But now I want to know how this is done with an array of texts and button press.
Any thoughts?
Initialize an current index variable to 0 and put your text in right order you want, in your array. then on button press event i. e. GetButtonDown, increment this index on each press and simultaneously set you UI text element by accessing your array[current index]. reinitialize to 0 index once you cover length of array
[SerializeField]
private string texts ; // Specify your texts in the inspector
private int currentTextIndex = -1 ;
private Rect textRect ;
public string CurrentText
{
get
{
return (currentTextIndex < texts.Length ) ?
texts[currentTextIndex] :
null ;
}
}
private bool FetchNextText()
{
currentTextIndex++ ;
if( currentTextIndex >= texts.Length )
return false ;
return true ;
}
void Awake()
{
textRect = new Rect( 0, 0.7f * Screen.height, Screen.width, 0.2f * Screen.height );
}
void OnGUI()
{
if ( !string.isNullOrEmpty( CurrentText ) && GUI.Button( textRect, CurrentText ) )
{
if( !FetchNextText() )
{
OnLastTextFetched() ;
}
}
}
private void OnLastTextFetched()
{
Debug.Log( "No more texts to display!" ) ;
}
@Hellium solution will work. Although, if you rather want to use Unity’s UI system, I’d recommend doing it with a Text companion component, and a component on your Triggers to update texts as you enter them.
using UnityEngine;
using UnityEngine.UI;
[RequireComponent (typeof(Text))]
public class MultiText : MonoBehaviour
{
[SerializeField] string [] texts;
private Text _text;
private int _index = -1;
void Awake ()
{
_text = GetComponent<Text>();
}
void DisplayText (int index)
{
_text.text = texts[index];
}
void HideText ()
{
_text.text = "";
}
public void DisplayNext ()
{
_index = _index < texts.Length-1 ? _index+1 : 0
DisplayText (_index);
}
// use this method to update texts from OnTriggerEnter
public void UpdateTexts (string [] texts)
{
this.texts = texts;
}
}