- Home /
How can I apply a text variable to a prefab
Hello,
I have a script which updates on screen text. This script is attached to a coin gameObject which is a prefab in my scene. The script is below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coin : MonoBehaviour {
//coins
[HideInInspector] public static int coinCount;
public Text coinText;
void Awake() {
coinCount = 0;
}
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.CompareTag ("Player")) {
//gameObject.SetActive(false);
Destroy (gameObject);
//coin counter
coinCount = coinCount + 1;
Debug.Log ("Coins collected: " + coinCount);
//update text
coinText.text = "Coins: " + coinCount;
}
}
}
My problem is that Unity will not allow me to apply the text variable to the prefab. When I drag it in to the space where the variable is, it stays bold after I hit apply (to apply it to the prefab).
Why will it not let me apply it to the prefab?
Thanks in advance
Where does the coinText
gameobject comes from? If you drag&drop it from the scene, then, it's normal. A prefab (which is an asset file) can't store a reference of an object belonging to the scene.
Yes I am just dragging and dropping it. And now I understand why it's not applying (because it is only specific to the scene. So how can I make the text object a global asset?
Answer by TanselAltinel · Oct 28, 2017 at 02:58 PM
Unity's behavior is correct in this situation. Your Text object is on the scene, however your prefab is independent on the scene.
You are basically trying to assign a scene dependent object to a scene independent object. A basic question would be that, what will happen when you use that prefab in a scene where there is no text objects in the scene?
Your solution would be that either keep that prefab specific to that scene and do not worry about the variable being bold / unsaved, or better, find the Text object in the scene via script with name or type at the beginning.
So how can I assign the text object via a script rather than dragging and dropping it.
I think it's something along the lines of
void Awake () {
coinText = GetComponent<Text> ();
}
but I'm not sure. Can you tell me how to do it
Answer by Hugo12343 · Oct 29, 2017 at 12:45 AM
Ahh I figured it out. I just made the text object (not the canvas just the text) a prefab. Then dragged that as an asset in. But thanks @TanselAltinel I didn't realise that the gameObject had to be global