0
\$\begingroup\$

I have two objects that when they collide disable another gameobject. The problem is that I only want to have the other game object disabled while the two objects are touching and that I want to have it enabled again as soon as the two objects are no longer touching. My script is below:

using UnityEngine;
using System.Collections;

public class DestroyObject : MonoBehaviour {

public GameObject ObjectToDestroy;
public GameObject TheObject;
public GameObject Player;

void OnCollisionEnter(Collision col)    {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (false);
    }
}
}
\$\endgroup\$
3
  • \$\begingroup\$ What happens when you do OnCollisionExit() { if (col.gameObject == TheObject) { ObjectToDestroy.SetActive(true); } } Why doesn't that work? \$\endgroup\$ – jgallant Jun 9 '16 at 12:59
  • \$\begingroup\$ Thanks. I already tried that and you made me realize a mistake. Instead of putting (Collision col) as an argument, I put down (Collider col). Simple mistake. \$\endgroup\$ – alexo1001 Jun 9 '16 at 13:05
  • \$\begingroup\$ Ah, yeah that will get you ;) cheers. \$\endgroup\$ – jgallant Jun 9 '16 at 13:06
0
\$\begingroup\$

I fixed this issue as I noticed a simple mistake that I made when I was trying to fix this myself. Here is the whole piece of code.

using UnityEngine;
using System.Collections;

public class DestroyObject : MonoBehaviour {

public GameObject ObjectToDestroy;
public GameObject TheObject;
public GameObject Player;

void OnCollisionEnter(Collision col)    {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (false);
    }
}

void OnCollisionExit(Collision col) { 
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (true);
    }
}
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.