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 *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504