U Production U Production - 14 days ago 6
C# Question

Change GameObject Component on InitializeOnLoad

I created script that i want to use as main script when my game launch. Now i want to access specific button text via that script and change it's text. I have problem because my text is not changing. Here is what i was trying:

static main()
{
Debug.Log("Up and running");
GameObject devButtonText = GameObject.Find("devButtonText");
Text text = devButtonText.GetComponent<Text>();
text.text = "Test";
}


Button is
devButton
and text is
devButtonText


full script

using UnityEngine;
using UnityEditor;
using System.Collections;
using UnityEngine.UI;


[InitializeOnLoad]
public class main : MonoBehaviour {


static main()
{
Debug.Log("Up and running");
GameObject devButton = GameObject.Find("devButton");
Text text = devButton.GetComponentInChildren<Text>();
text.text = "Test";
}

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
}

Answer

I created script that i want to use as main script when my game launch.

The InitializeOnLoad attribute must be used to run a function when the Unity Editor starts, not the game. Every editor script won't run when you compile your game. Unity documentation

Sometimes, it is useful to be able to run some editor script code in a project as soon as Unity launches without requiring action from the user.


Instead, create an Empty GameObject and attach the following script :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class ChangeText : MonoBehaviour
{
    private void Awake()
    {
        GameObject devButton = GameObject.Find("devButton");
        Text text = devButton.GetComponentInChildren<Text>();
        text.text = "Test";
    }
}

Even better :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class ChangeText : MonoBehaviour
{
    // Drag & Drop the desired Text component here
    public Text TextToChange ;

    // Write the new content of the Text component
    public string NewText ;

    private void Awake()
    {
        TextToChange.text = NewText;
    }
}

The script will automatically be called when the scene starts.

Comments