Simple scripts to deactivate GameObject on collision/trigger enter.

2D Version of the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

//Deactivates given GameObject on collision

public class DeactivateOnCollision2D : MonoBehaviour {
    [SerializeField] private GameObject objectToDeactivate;
    [SerializeField] private string objectTagName;
    [SerializeField] private string objectName;

    [SerializeField] private bool deactivateThisObject = false;

    private void Start()
    {
        if (deactivateThisObject)
        {
            objectToDeactivate = gameObject;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag(objectTagName) || collision.gameObject.name == objectName)
        {
            objectToDeactivate.SetActive(false);
        }
    }

    private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.CompareTag(objectTagName) || collider.gameObject.name == objectName)
        {
            objectToDeactivate.SetActive(false);
        }
    }
}

 

3D Version of the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

//Deactivates given GameObject on collision

public class DeactivateOnCollision3D : MonoBehaviour {
    [SerializeField] private GameObject objectToDeactivate;
    [SerializeField] private string objectTagName;
    [SerializeField] private string objectName;

    [SerializeField] private bool deactivateThisObject = false;

    private void Start()
    {
        if (deactivateThisObject)
        {
            objectToDeactivate = gameObject;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag(objectTagName) || collision.gameObject.name == objectName)
        {
            objectToDeactivate.SetActive(false);
        }
    }

    private void OnTriggerEnter(Collider collider)
    {
        if (collider.gameObject.CompareTag(objectTagName) || collider.gameObject.name == objectName)
        {
            objectToDeactivate.SetActive(false);
        }
    }
}

 

Unity C# Deactivate GameObject On Collision/Trigger
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close