Further confusion about prefabs!

Hello!

I think I have found my personal kryptonite: Prefabs.

I have managed to get the score to count up and stay persistent across the gameplay screen and the game over screen. However, I can’t get the score to display in different places.

To get the score to carry over I have made my canvas a child of my GameSession prefab. My TextMeshPro text is nested under the canvas. I pulled the Game Session prefab into my Game Over Screen, moved the text into the middle and didn’t press Apply All.

My main question is: How do I make sure the score carries over while being able to place UI elements in diffferent locations? I feel like there’s something fundamental about prefabs I’m not understanding!




1 Like

Hi MxHabit,

Maybe it will help to distinguish between the visual part and the code part. To display a string, you need a Text or TMP object. To change the value of the text property during runtime, you need code. Since the text property does not need a specific position within the game scene to be able to receive data, you could place your score display whereever you want.

When a new scene gets loaded, all game objects in the old scene get destroyed, except when Don’tDestroyOnLoad got called on them. If you call that method on “Game Session”, all its children will persist.

Don’t make the score display part of the Game Session object. There are different ways how you could make your score persistent anyway and to display the score in your game.

One way is to create a pure C# class with an actual singleton (first version). That pure C# class does not inherit from MonoBehaviour. It just stores an integer and returns it similar to what we did with our State objects in the AdventureGame class.

Then you need a “normal” component meaning a class inheriting from MonoBehaviour. That class/object calls a method in the aforementioned C# object and receives the score value, which it assignes to the text property of the Text or TMP component.

This might sound a bit complicated but it is relatively easy to implement with your current knowledge. If you use Debug.Logs in the class inheriting from MonoBehaviour, you’ll very likely be able to figure everything out yourself.

If you get stuck, feel free to share your results here and ask for help. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms