So i want a string to change in my ui from a script. No errors but it dosent change upon start of the game.

So the script is like this

public int JobID;
public string Jobname;
GameObject JobUI;


void Start () {
    JobUI = GameObject.Find("Job");
    JobID = 0;
    Jobname = ("Unemployed");
    
}


void Update () {

    if (JobID == 0 )
    {
        Jobname = "Unemployed";
        JobUI.GetComponent<Text>().text = Jobname;

    }

    if (JobID == 1)
    {
        Jobname = "Lumberjack";
        JobUI.GetComponent<Text>().text = Jobname;

    }

}

}

You can reference a text component directly like this:

public Text JobUI;

and you will see it i and drag text component reference into it in inspector.


then you can use it directly without GetComponent:

JobUI.text = Jobname;

don’t forget to type

using UnityEngine.UI

at the top of your script.

The way you’re doing this is strange in more than one way.

With the code you have now, it looks like your GameObject for JobUI should be a Canvas. But you have it doing GetComponent<Text>(), which doesn’t make sense because the Text script should be on a child object attached to the Canvas.

I would just delete all UI elements you have in the inspector now. Simply right click on the Hierarchy, go to UI → Text. Rename everything accordingly, attach the text object to the script, and boom you’re done.

AFTER YOU’VE SET UP YOUR SCENE CORRECTLY:

Don’t worry about the canvas through code. Just drag the Text object in through the inspector. Here’s an example of how you could change the text through code:

private int JobID;
private string Jobname;
public Text JobText;

private void UpdateJob(int ji) {

    JobID = ji;
    
    switch (JobID) {
        
        case 1:
            Jobname = "Unemployed";
            JobText.text = Jobname;
            break;
        
        case 2:
            Jobname = "Lumberjack";
            JobText.text = Jobname;
            break;
    }
}

/* Call Update Job when you need it. Wouldn't call it in the Update loop like you have it currently, but just as a test */
private void Update() {
    UpdateJob(0);
}