Search code examples
c#unity-game-enginecollider

How to check the text found on an object in OnTriggerEnter


I have a question, I created a game where I need to collect a Ballon, and check the number of the text that I attached on it: Example

  public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Ballon")
        {
       //now I want to check the text//
        }
     }

Solution

  • This is very simple to do. As your example you have a TextMeshPro in the child of the other object. Now in this situation there are two way for you to get the child object.

    I'll Add reference links at the bottom of the answer.

    1. other.transform.Find();
    2. other.transform.GetChild();

    1. other.transform.Find()

    Using transform.find() method it will go through all the Game Objects that are child of the the parent object in your case this method will go through all the children of other object, as ass soon as it finds the object which matches the name it will return that object.

    Here is an example:

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Ballon")
        {
             TextMeshPro tmp = other.transform.Find("Text (TMP) (1)").GetComponent<TextMeshPro>();
             if(tmp.text == "text of your liking")
             {
                 Debug.Log("Do what you want");
             }
        }
     }
    

    2. other.transform.GetChild()

    This method will directly return the child from the index that you enter. And this method is quit an efficient one to use.

    Here is the example:

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Ballon")
        {
             TextMeshPro tmp = other.transform.GetChild(0).GetComponent<TextMeshPro>();
             if(tmp.text == "text of your liking")
             {
                 Debug.Log("Do what you want");
             }
        }
     }
    

    References:

    1.Transform.Find()
    2.Transform.GetChild()