Problems attaching a GameObject in a script

Hello Everyone

I’m new at Unity and programming in C#, so this might be a trivial question.
Right now I’m making the Space Shooter game of the tutorial and I need to display the score value in the scene. I created an UI Text Game Object and correctly placed at the left top side corner of the screen. Then, I made some changes in the script that controls the explosions and destroys the objects, in order to show the score correctly. So I created a “public Text scoreText”, to show in the inspector. The problem is that I can’t pull and drag the Text Game Object to the “Score Text” property of the script. Whenever I try to do it, my cursor indicates that it can’t do it. Is there any other way can do that?

You cannot drag a scene object into a prefab reference that’s not in the scene. If you want the Score Text to be available to all instances of the Asteroid prefab, then it needs to be a part of that prefab, or a part of another prefab that the Asteroid can instantiate when needed.

That’s probably not that useful in this case, so you’ll more likely want the Score Text and Asteroid to learn about eachother when the Asteroid is actually instantiated in the scene. This means that the Score Text needs to make itself more readily known-
maybe by registering itself to a static / singleton Game Manager of some sort, or being a singleton reference itself, etc. This puts it into a position where the Asteroid can easily find and reference it when needed.

I would personally go the other way- UI should know about game data, but game data shouldn’t know about UI. There should be a manager of some sort that handles the game score for the player, how many lives the player has, etc… This manager can be static, or it can be a singleton in the scene if you REALLY like GameObjects for some reason, or it can be attached to the player if you really want too. This manager should keep track of the Asteroids destroyed by the player, and increase the score when appropriate, and it should have a UnityEvent or some other kind of broadcast delegate (call it “OnScoreChangeEvent”) that fires whenever the score is updated. The UI should register for that event, and receive the signal whenever it’s fired, and update its own text to reflect the new score.

That way, the game works without knowing anything about the UI, and the UI can be completely swapped out without having any effect on the game except losing the display.

If your Score GameObject is really a Text type, then it should be possible. So make sure you are dragging a Text type object to this attribute.