Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Access TextField after pushing Button

Discussion in 'Scripting' started by mm_unity870, Apr 2, 2020.

  1. mm_unity870

    mm_unity870

    Joined:
    Feb 7, 2020
    Posts:
    8
    Hi all,

    When a button is used, the "OnClick ()" processes a script.
    In the script I want wo change a textfield with the ID "TxtToleranz".

    But I am getting a n error
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. ToleranceField.setTolerance (System.String tolerance) (at Assets/Skripts/ToleranceField.cs:14)
    3.  

    The script:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class ToleranceField : MonoBehaviour
    5. {
    6.  
    7.     public void setTolerance(string tolerance)
    8.     {
    9.         Debug.Log("ToleranceField -> setTolerance: " + tolerance);
    10.         Transform transform1 = transform.Find("TxtToleranz");
    11.         Text text = transform1.GetComponent<Text>();
    12.  
    13.     }
    14. }
    Thanks, regards
    Mario
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    This script is dependent on having a child EXACTLY below the transform this script is on called "TxtToleranz"

    If you instantiated that object it might be called "TxtToleranz (Clone)" and this script will fail.

    If it is located below the first row of children or elsewhere, it won't be found either and this script will fail.

    Unfortunately there are like 57000 varieties of finding GameObjects and Transforms if you google for it.

    The one takeway from all this is, if you are going to use any flavor of Find by a string, you need to be 100% cognizant of all the ways it can fail spectacularly.

    Or else, do like is traditional in Unity and make public Text field that you can drag that text field into. If you do this correctly, it will tend to work all the time.
     
  3. mm_unity870

    mm_unity870

    Joined:
    Feb 7, 2020
    Posts:
    8
    Hi Kurt,

    many thanks. I agree with you, finding an objects by a String is not a good idea. Im programming for over 20 years.But I am totally new in unity.

    You suggested the "traditional" way. But I wanted the build-in function using the "event" of the button. But I think I will do it the way you suggested.

    P.S. I hat a look at your twitter's page. Cool!

    Regards
    Mario
     
    Kurt-Dekker likes this.