C# 在初始化加载时更改游戏对象组件
我创建了一个脚本,希望在游戏启动时用作主脚本。现在我想通过该脚本访问特定的按钮文本并更改其文本。我有问题,因为我的文本没有改变。以下是我所尝试的:C# 在初始化加载时更改游戏对象组件,c#,unity3d,C#,Unity3d,我创建了一个脚本,希望在游戏启动时用作主脚本。现在我想通过该脚本访问特定的按钮文本并更改其文本。我有问题,因为我的文本没有改变。以下是我所尝试的: static main() { Debug.Log("Up and running"); GameObject devButtonText = GameObject.Find("devButtonText"); Text text = devButtonText.GetComponent<Text>();
static main()
{
Debug.Log("Up and running");
GameObject devButtonText = GameObject.Find("devButtonText");
Text text = devButtonText.GetComponent<Text>();
text.text = "Test";
}
初始化单一行为时
publicgameobject 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";
}
}
使用UnityEngine;
使用UnityEditor;
使用系统集合;
使用UnityEngine.UI;
公共课主要内容:单一行为{
无效唤醒(){
Debug.Log(“启动并运行”);
GameObject devButton=GameObject.Find(“devButton”);
Text Text=devButton.getComponentChildren();
text.text=“测试”;
}
}
编辑
给定名称main我想这是您项目的起点,因此如果您的脚本未附加到任何游戏对象,则不会调用Start、Awake或OneEnable。在这种情况下,您应该将其附加到游戏对象上,并更改统一脚本执行顺序并将脚本带到最早的点
我创建了一个脚本,希望在游戏启动时用作主脚本
当Unity编辑器启动时,必须使用InitializeOnLoad
属性来运行函数,而不是游戏。编译游戏时,不会运行每个编辑器脚本
有时候,Unity一启动就可以在项目中运行一些编辑器脚本代码,而无需用户执行操作,这是非常有用的
相反,创建一个空游戏对象并附加以下脚本:
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";
}
}
脚本将在场景开始时自动调用。@NewCallum仍然相同,无响应:/n您确定调用了该函数吗?您在控制台中有任何错误吗?(检查错误按钮是否在<代码>控制台< /CONT>标签)@ @ HeliUM更新后的PrimeScript,完整脚本在NONIN UNION中调用Stand的方法叫做“代码> Stand())/Cuff>:我觉得你是C或C++的人(几个月前我的一个朋友犯了同样的错误)!嗯,我想我误解了InitializeOnLoad,我不想把脚本附加到任何对象上,而是从游戏启动开始。我怎么能做到呢?但是我的脚本没有被任何游戏对象攻击,我只是想让它在没有任何玩家交互的情况下开始运行。我不认为这会起作用。在执行unity脚本管道之前,您基本上是在尝试读取游戏对象,所以很多事情在这一点上可能不起作用
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;
}
}