user3681449
user3681449

Reputation:

OnCollisionEnter in unity won't call function

I'm a complete unity novice. I want to make a simple scene where you have three lives and you lose a live if you collide with a cube. This is my script:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Lives : MonoBehaviour {

public Transform player;
public static int lives;
public Image live1;
public Image live2;
public Image live3;

// Use this for initialization
void Start () {
    lives = 3;
    live1.enabled = true;
    live2.enabled = true;
    live3.enabled = true;

}

void Update () {
    DisplayOfHearts();
}

public static void Damage() {
       lives -= 1;
}

public void OnCollisionEnter(Collision col) {
    if (col.gameObject.tag == "cube") {
        Lives.Damage();
    }
}

public void DisplayOfHearts() {
    if (lives == 2) {
        live3.enabled = false;
    }
    else if (lives == 1) {
        live2.enabled = false;
    }
    else if (lives == 0) {
        live1.enabled = false;
    }
}

}

What happens is the player can't move through the cube but the amount of lives stays three. Is there something I'm missing?

Upvotes: 0

Views: 1669

Answers (1)

Bizhan
Bizhan

Reputation: 17085

The problem is you have attached the script to a wrong game object. The script and the collider must be attached to the same game object.

Unity methods inside a MonoBehaviour script (such as OnEnable, Update, FixedUpdate, Awake, Start, OnTriggerEnter, OnCollisionStay, etc..) only work for the game object which the script is attached to.

If you attach the script to another game object don't expect any of those to work. Update only works while that game object is active. OnCollisionEnter only works when a collision occurs on a collider which is attached directly to that game object. (it doesn't even work when a child has the collider instead of the actual game object where script is attached to)

Upvotes: 1

Related Questions