Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Updating text via script not working

So, i got a scipt which updates a text every times the player enteres the trigger

public class AddScore : MonoBehaviour

{

  float scorenum = 0;

  public Text score;

  void Update()

  {

    if (scorenum > 0)

    {

      score.text = scorenum.ToString();

      Debug.Log(scorenum.ToString());

    }

  }

  private void OnTriggerEnter(Collider other)

  {

      scorenum++;

   

  }

}

but when the payer enteres the first trigger(yes there a many) it updates but when it enteres the second triiger or any other trigger it doesn't update. I've tried to convert the text to a textmeshpro but it didn't work.

Answers

  • Is this script on every trigger

    If so it means that every trigger has its own scorenum which means every time you trigger the next one it just does the same thing exactly on repeat so it will stay 1.

    What i suggest is to make another script(class) that contains the scorenum and the triggers with need refrence to that other script at which they will add a scorenum every time you enter it.

    So exact what you did but just make sure they is only one instance of the scorenum

  • FissionerFissioner Member

    So here is the problem I can see:

    When you add the script you posted to multiple objects, all of them will try to update score.text's value, basically they are going to fight for setting that value.

    Here is 2 easy steps to fix it:

    1. make scroenum static field. (public static float scorenum = 0; and you might want to change float into int, because it is always a whole number)
    2. make sure there is only one class trying to alter value of score.text. For example, make one class which controls text value of the score object. and the value you want to assign is 'AddScore .scorenum.ToString();'

    Hope it help, if something is not clear, let me know.

  • Thanks for helping me I will try it later

Sign In or Register to comment.