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

How to make a script edit a component in the game object it's in?

Discussion in '2D' started by unity_10212005, Mar 16, 2020.

  1. unity_10212005

    unity_10212005

    Joined:
    Mar 16, 2020
    Posts:
    5
    I'm a (very) new game developer and was wondering how I might do this.
    I'm using a UI Text game object and added a script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Test2 : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.     void Start()
    9.     {
    10.         Text test = GetComponent<Text>();
    11.         test.Text = "please";
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.        
    18.     }
    19. }
    20.  
    I had hoped this would make the text say please, but I got a string of errors that said that "Text" could not be found. I pretty much stole all of this code off the manual, so I'm sure I'm missing something obvious.

    Thanks for the help!
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
  3. unity_10212005

    unity_10212005

    Joined:
    Mar 16, 2020
    Posts:
    5
  4. PuppyPolice

    PuppyPolice

    Joined:
    Oct 27, 2017
    Posts:
    116
    got to add the
    using UnityEngine.UI;
    if you wanna use UI components.
     
    LiterallyJeff likes this.
  5. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Don't try random things and expect results, you'll only cause more bugs and headaches. The documentation I linked shows exactly what the syntax is, so do that.

    Also next time post the full error message and line number, because that is way more specific and tells you exactly where the issue is.

    "Text" is a class inside the UnityEngine.UI namespace (you can verify that in the documentation for the Text component at the top).

    Capture.PNG

    Since you did not have "using UnityEngine.UI;" at the top of your class as @PuppyPolice pointed out, that Text class didn't exist in the context of your code.

    Hopefully next time you see that error, you'll remember these things to double check.
     
  6. unity_10212005

    unity_10212005

    Joined:
    Mar 16, 2020
    Posts:
    5
    Thanks! Didn't know I needed that!
     
  7. unity_10212005

    unity_10212005

    Joined:
    Mar 16, 2020
    Posts:
    5
    Thanks! Didn't know I needed that!