-1
\$\begingroup\$

so in here there is a box to which i have attaches this script and ATTACH1 is a socket interactor here i want is when the box which i have attaches attaches to that socket interactor the text which is on canvas destroy!! But infortunately this is not working! do you see any issues here or something that u thing is wrong or I missed?

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

public class Box1 : MonoBehaviour
{

    private GameObject box2;
    private Text noBox;
    // Start is called before the first frame update
    void Start()
    {
        box2 = GameObject.Find("ATTACH1");
        noBox = GameObject.Find("text").GetComponent<Text>();
       
    }
    
    void Update()
    {
        
    }
    void onTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            Destroy(noBox);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Your question is a bit hard to read. Can you clean up the grammar a bit, please? \$\endgroup\$
    – Evorlor
    Commented Oct 6, 2023 at 7:13

1 Answer 1

2
\$\begingroup\$

You have to name the method void OnTriggerEnter with a capital O. Not void onTriggerEnter. Capitalization matters. If you don't name message handler methods exactly as written in the documentation, then the engine won't call them.

There are also a couple other problems in your code:

  1. Using GameObject.Find to create object relations is bad. It is slow. It doesn't work when you type the name of the object wrong. It breaks when you change the name of the object. It breaks when you make another object with the same name. It is better to make it a public Text noBox; variable and then assign the correct object in the inspector.
  2. The code will throw an error when the player enters the trigger a second time, because noBox will already be destroyed. I recommend to check beforehand if the box still exists:
    void OnTriggerEnter(Collider other)
    {
        if (noBox != null && other.gameObject.CompareTag("Player"))
        {
            Destroy(noBox);
        }
    }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .