I am making a Sci-Fi game where the player it’s on a planet without oxygen.
I want a script where the player health drains over time, and when he collides with some objects (Like his spaceship or dead bodies) he refills his health.
I tried to make it alone, but my coding it’s…rusty.
What have you tried? What you’re looking for is probably two scripts, or at least a number of functions in one. You need a timed function to drain health, and some methods that react to collisions. See OnCollision(), OnTrigger() etc. for the latter ![]()
Check out the function InvokeRepeating:
(found under the Functions section of this page, along with related functions e.g. cancelling invokes, checking if a function is scheduled to be invoked: Unity - Scripting API: MonoBehaviour)
Set it to invoke every N seconds, then each time your method runs, first check to see if the player is not colliding with any oxygen tanks, or within a trigger, and if not, then decrease the players oxygen level.
You’ll probably want more functionality to pause/resume the script, and you’ll need to hook up the script to wherever you’re keeping track of the players oxygen. Alternatively, you can put this code directly into the same script where you manage the player’s oxygen.
I hope that helps you some.
Another method to accomplish this, if writing in C#, would be to use a coroutine that has a while loop nested within in, using yield, you can check conditions every interval, and then run the method if needed.