C# Challenge - Script Communication
Hey, script B! I need some things from you…
Whenever you will develop something with Unity (or any other game engine) you probably won’t ever get around script communication. Not even if you just want to show some UI elements like the current player lives or the score. Those pieces of information are usually stored inside another script.
That’s what todays challenge is all about. Let’s take a look at it!
Okay, let’s break the task down into little pieces:
- We are not allowed to change the Player.cs script.
That means, we need to create a new script, or more specifically, a UIManager.cs script - This challenge is about UI.
To make it work properly, we need to include the UI library of Unity - We need to grab some information from the Player script which is attached to the player GameObject. We need a handle to the player!
- The script prints out five pieces of information. Therefore, we need five variables of type Text.
- As the end-user starts the application, the values shall be printed out immediately, without any delay.
I. Setting up the variables
We need five variables in total.
As the task is telling you already, we need the following variables:
- One for the player name
- One for the attack level
- One for the magic level
- One for the smiting level
- One for the mining level
- A handle to the player GameObject
In code, it will look like this:
II. Creating the script communication logic
We want to access the player script and populate some information out of it. For that, we need to create a handle to the player and null-check it.
After that, we only need to manipulate the text of all GameObjects.
As every variable is public in the provided Player.cs script, it’s easy to access them.
In code, this is the way to go here:
III. Final preparations
In order to run this script, we need to do two small things within the Unity Inspector:
- Assign the Text GameObjects inside the script
- Assign the variables of the Player.cs script
IV. Final end result
Now you’re ready to run the application! If everything works, you should see that the UIManager script is collecting the information from the Player script and populates them, so you are able to see them.
That’s it for todays article!
Take care and until next time!