I made a spike in my game… when the player touches it, I want the play to lose ten health. Then, if they are still touching it a second later, I want them to lose another ten health. Here’s my code so far:
function OnTriggerCollider (player : Collision) {
if (player.tag == “Player”) {
Player.gameObject.GetComponent(PlayerHealth).playerHealth -= 10;
}
}
The function you made will not be called. You need to call unity’s functions if you want this to work.
Do this for collision:
function OnCollisionEnter (collInfo: Collision)
{
if (collInfo.collider.tag == "Player")
{
StartCoroutine("DecreaseHealth", collInfo.gameObject.GetComponent(PlayerHealth));
}
}
function OnCollisionExit (collInfo: Collision)
{
if (collInfo.collider.tag == "Player")
{
StopCoroutine("DecreaseHealth");
}
}
function DecreaseHealth(ph : PlayerHealth)
{
ph.playerHealth -= 10;
yield WaitForSeconds(1f);
ph.playerHealth -= 10;
}
If you wish health to be reduced each second afterwards and not only the first, change the coroutine “DecreaseHealth” to this:
function DecreaseHealth(ph : PlayerHealth)
{
var run : boolean = true;
while ( run )
{
ph.playerHealth -= 10;
yield WaitForSeconds(1f);
}
}
This will work if what you are testing is collision and not a trigger. A collision means two objects will not cross each other, while a trigger means the collision is noticed but the objects can still cross each other. If you need trigger functionality you will need to change the “OnCollisionEneter” and “OnCollisionExit” to the following:
function OnTriggerEnter (other: Collider)
{
if (other.tag == "Player")
{
StartCoroutine("DecreaseHealth", collInfo.gameObject.GetComponent(PlayerHealth));
}
}
function OnTriggerExit (other: Collider)
{
if (other.tag == "Player")
{
StopCoroutine("DecreaseHealth");
}
}