Manipulating existing ui text from a runtime created prefab

I am having a problem trying to manipulate an existing UI Text “score” after destroying a runtime instantiated prefab.

  • public variables don’t link on a prefab
  • tried from a prefab script

//// make a script component for “scoreTxt” called “scoreTrckr”
//// make a public text scrTxt in “scoreTrckr”, link it to “scoreTxt”
//// make a public int thScr in “scoreTrckr”,

/// remember * scrTxt is linked to scoreTxt.text
//// update scrTxt = thScr.ToString ();

void OnMouseDown(){
GameObject thscr = GameObject.FindWithTag (“scoreTxt”); //find the gameObject /w tag
thscr.GetComponent().thScr += 500;
Destroy (this.gameObject);
}

This works while compiling and testing the game, but not when the game is deployed.

How do I get runtime created prefabs to communicate with existing GameObjects and public variables?

When you instantiate the game object, you can get the component script (on the return value from instantiate).
Then, pass a reference to the text object to the script on the new object.

nevermind, got it working

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

public class ScoreTracker : MonoBehaviour {

public Text scoreText;

private int ttlScr;
public static int scrCst;

void Update(){
ttlScr += scrCst;
scrCst = 0;
scoreText.text = ttlScr.ToString();
}
}

Attached this to all my prefabs, and the ui text. It calls a null public text on the prefabs, but the static scrCst adds up and updates. Hopefully this holdsup and doesn’t cause future issues.

I think you could improve upon that if you use my suggestion, that i posted above. You could send the reference to the text component or to the ScoreTracker script.

One other small addition I’d mention is that you could use a ScoreAdd method, and only update the score text when your score changes. Doing that, you would avoid modifying the text every frame, even when it doesn’t change.