![](/img/trans.png)
[英]How can I change GameObjects location on the Hierarchy in [InitializeOnLoad] script type?
[英]Change GameObject Component on InitializeOnLoad
我在游戲發布時創建了我想用作主腳本的腳本。 現在我想通過該腳本訪問特定的按鈕文本並更改它的文本。 我有問題,因為我的文字沒有改變。 這是我在嘗試的:
static main()
{
Debug.Log("Up and running");
GameObject devButtonText = GameObject.Find("devButtonText");
Text text = devButtonText.GetComponent<Text>();
text.text = "Test";
}
按鈕是devButton
,文本是devButtonText
完整的腳本
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 () {
}
}
我在游戲發布時創建了我想用作主腳本的腳本。
必須使用InitializeOnLoad
屬性在Unity Editor啟動時運行函數,而不是游戲。 編譯游戲時,每個編輯器腳本都不會運行。 Unity文檔
有時,只要Unity啟動而無需用戶操作,就可以在項目中運行一些編輯器腳本代碼。
而是創建一個Empty GameObject並附加以下腳本:
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";
}
}
更好的是:
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;
}
}
場景啟動時將自動調用腳本。
初始化MonoBehaviour時
您應該使用Start,Awake或OnEnable。
你不應該使用構造函數,靜態構造函數或字段初始化(如public GameObject go = GameObject.Find("devButton");
)
這應該工作:
using UnityEngine;
using UnityEditor;
using System.Collections;
using UnityEngine.UI;
public class main : MonoBehaviour {
void Awake () {
Debug.Log("Up and running");
GameObject devButton = GameObject.Find("devButton");
Text text = devButton.GetComponentInChildren<Text>();
text.text = "Test";
}
}
鑒於名稱main我猜這是你項目的起點,所以如果你的腳本沒有附加到任何游戲對象,那么將不會調用Start,Awake或OnEnable。 在這種情況下,您應該將它附加到游戲對象並更改統一腳本執行順序並將腳本帶到最早的點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.