So I’m currently building a survival game in Unity 5 and I already made sliders in a canvas etc to track the values of a player’s vitals like health hunger etc…
I have a C# script that currently controls the player vitals like checking if they reach zero, adding values to them, etc…
In one of the functions on that script I have an OnDeath void that basically sets the FPSController’s walk values and stuff to 0 so it basically disables the player in general. What I’m aiming to add to the function was a part where on death a death UI (That I’ve already created and set to be disabled) to become enabled so that the player knows they’ve died and is able to respawn. I put the canvas which holds all the UI parts into the FPSController game object but when I added “DeadCanvas.isActive = true;” to my death function it just errors out and says DeadCanvas doesn’t exist even though I already created it and the names match.
I think the issue is that I need to somehow access the DeadCanvas portion of my project inside of the PlayerVitals script, but I’m unaware of how to do that. If possible, please explain that to me and it would be greatly appreciated.
If you need screenshots or anything of that nature feel free to ask.
If the Death UI already exists in your canvas, you can do two things:
You could save a reference to the death UI through a GameObject reference. IsActive has been deprecated (retired, not in use anymore) for quite some time, use SetActive(true) instead.
public GameObject DeathCanvas;
void OnDeath()
{
DeathCanvas.SetActive(true);
}
Or you could have a UI manager script. Often you’ll find that your project is becoming quite large and holding all of the different logic for your UI causes your scripts to become large and hard to navigate. This becomes the case when you have lots of buttons to click, things to track etc.
However this isn’t much of an option until you’ve grasped the concept of GetComponent<>
Lets say that you have a script on the main camera for your user interface, and another script on your player to keep track of their health, hunger etc.
On your camera script, you might have something like this:
public class UserInterfaceManager : MonoBehaviour
{
public GameObject playerObject;
private PlayerScript player;
void Awake()
{
playerObject.GetComponent<PlayerScript>();
}
Debug.Log(player.Health);
}
You would then drag the player from your scene on to that script and it would then find the script for you. Because we’ve used GetComponent we can access all of the properties of our player and display the interface accordingly.