- Home /
Help with code efficiency
I am trying to create a conversation system between a player object and another NPC object. So far it works. When i enter the NPC trigger and press the mouse button down, it will scroll through the dialogue i've assigned in the inputField array, the biggest issue I potentially see with this is the following line:
NPCtext.text = inputField[conversation];
I am performing this code in the update function, so i'm not sure if this is performing unnecessary calculations. So my question is, is there a more efficient way to put my code? Or am I on the right track with this? Regards
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class showText : MonoBehaviour
{
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
conversation+=1;
}
NPCtext.text = inputField[conversation];
}
void OnTriggerEnter(Collider collide)
{
input.active = true;
cam.active = true;
}
void OnTriggerExit()
{
NPCtext.text = "";
input.active = false;
cam.active = false;
}
}
Answer by Kona · Dec 20, 2014 at 09:09 PM
You could make use of IEnumerator that toggles active as the player enters and leaves the NPC's trigger zone. That way Unity won't make the if( Input.GetButtonDown() ) check all the time even if not necessary.
private bool _isTalking;
private IEnumerator Speaking() {
while( _isTalking ) {
if( Input.GetButtonDown( "Fire1" )) {
conversation++;
NPCtext.text = inputField[ conversation ];
}
yield return null;
}
}
public void OnTriggerEnter( Collider other ){
//Make sure to identify what collider entered
//else we will trigger for any collider
if( other.CompareTag( "Player" )) {
cam.active = true;
if( !_isTalking ) {
_isTalking = true;
StartCoroutine( Speaking() );
}
}
}
public void OnTriggerExit( Collider other ) {
if( other.CompareTag( "Player" )) {
if( _isTalking) {
NPCtext.text = "";
cam.active = false;
_isTalking= false;
StopCoroutine( Speaking() );
}
}
}
Hey this is great, easy to understand too, thanks very much for your help :)