If you remove the Destroy(gameObject)
from the HealthPickup
script, it will not get destroyed, but the controller will disable it. When the player’s health drops below 50% again, it will get enabled again.
Randomizing it’s spawn time can be done by randomly picking the level at which it appears. It is 50% now, but once the player takes it, you can pick a new value, like 75% or 22%. There are some things to consider with this, though: if the player has maximum 100 health and picks it up at 50 and gets 25 health added, they will have 75 health. If the new, random value is above 75%, it will not get disabled because the player’s health is still below the threshold.
To randomly pick a new threshold, you can just use Random.value
. That’s a value between 0 and 1 and matches the health percentage. But you may not want that much range. Perhaps you want it between 25% and 60% (0.25f - 0.6f). For that you can just Lerp
the value:
healthThreshold = Mathf.Lerp(0.25f, 0.6f, Random.value);
You will have to know when the health has been picked up, though. There are many ways to do that:
- Fire an event from the
HealthPickup
script when it gets picked up, or
- Find the controller and call a public method on it to pick a new threshold, or
- Let the controller set a flag when it enables the pickup, and then - when it disables it, it can check if the flag was set and if it was, pick a new threshold and reset the flag
and several more