Home > database >  How to destroy instantiated button upon collision exit - Unity 3D
How to destroy instantiated button upon collision exit - Unity 3D

Time:09-19

I am a beginner in Unity and I am currently making a simple game. I have a problem where the instantiated Button is not destroyed.

The process of the script is to instantiate a button and destroy it upon collision exit. But when I move out of the object, the object stays and it is not destroyed. i don't know if there is something wrong with the Destroy code of line.

Here is the script for the collision:

using UnityEngine;
using UnityEngine.UI;

public class InteractButtonPosition : MonoBehaviour
{

    public Button UI;
    private Button uiUse;
    private Vector3 offset = new Vector3(0, 0.5f, 0);
    // Start is called before the first frame update
    void Start()
    {
        //uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
    }

    // Update is called once per frame
    void Update()
    {
        //uiUse.transform.position = Camera.main.WorldToScreenPoint(this.transform.position   offset);
    }

    private void OnCollisionEnter(Collision collisionInfo)
    {
        if(collisionInfo.collider.name == "Player")
        {
            uiUse = Instantiate(UI, FindObjectOfType<Canvas>().transform).GetComponent<Button>();
            uiUse.gameObject.SetActive(true);
            uiUse.transform.position = Camera.main.WorldToScreenPoint(this.transform.position   offset);
        }
    }

    private void OnCollisionExit(Collision collisionInfo)
    {
        if(collisionInfo.collider.name == "Player")
        {
            Destroy(uiUse);
        }
    }
        
}

CodePudding user response:

The code does exactly what you have written, which is destroying uiUse which is a Button component. If you go and inspect your game object in the scene, you will see, that indeed, the button component has been destroyed.

What you want to do is to destroy the GameObject the button component is attached to, like: Destroy(uiUse.gameObject)

  • Related