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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Accessing a Property of a Component of another Game Object

Discussion in 'Scripting' started by SprinkledSpooks, Jul 20, 2016.

  1. SprinkledSpooks

    SprinkledSpooks

    Joined:
    Jun 1, 2016
    Posts:
    117
    I'm trying to write a script (that is attached to it's own Game Object) that can check the text property of UI game object and act according to said text. The only issue is that I do not know how to access the property of another game object through a script. Does anyone know how I can go about doing so?
     
  2. topsekret

    topsekret

    Joined:
    Apr 18, 2013
    Posts:
    69
    If you declare member variable of a script as public, you Unity draw a field for that variable on the inspector to allow you to set the initial value of the variable on instances of the script in a scene.

    So you could declare a public variable of type GameObject, then you would see a field in the inspector that would allow you to drag and drop a game object there. Or, if you know this is used for a UI text field specifically, you could declare the variable to be of type UIText, so you can drag and drop references to UIText components in your scene to your script.

    (An advanced thing you can do is declare the variable as private, like you are normally encouraged to due for encapsulation, and then put the attribute [SerializedField] above the variable to expose it in the inspector.)
     
  3. SprinkledSpooks

    SprinkledSpooks

    Joined:
    Jun 1, 2016
    Posts:
    117
    Thanks very much for the help. However, I still do have one last problem:

    When I type in the code
    Code (CSharp):
    1. public UIText Text;
    to create a public variable to drag and drop the UI element using the inspector, I get the error message "Error CS0103: The name 'UIText' does not exist in the current context."

    Should I just use the general term 'GameObject', or should I try a different term?
     
  4. topsekret

    topsekret

    Joined:
    Apr 18, 2013
    Posts:
    69
    Ah, I made a slight mistake: the name of the class is Text, not UIText. However, the Text class is in the UnityEngine.UI namespace. So you will either need to add a using statement to the top of your script or write out the fully qualified name. Make sense?
     
  5. SprinkledSpooks

    SprinkledSpooks

    Joined:
    Jun 1, 2016
    Posts:
    117
    Oh. Thanks for the help; very much appreciated.
     
    topsekret likes this.