我正在通过脚本实例化按钮,然后需要在父对象中调用几个级别的脚本
这是在预置脚本中,当其中一个按钮被点击时会被调用。性能一点也不相关,所以我只是告诉它从下到上一直到带有mllhildTestController.cs脚本的控制器游戏对象。
public void ClickMe()
{
string parentNode = ReturnLabel();
string path = this.GetComponentInParent<mllhildTestController>().path;
this.GetComponentInParent<mllhildTestController>().Clear();
this.GetComponentInParent<mllhildTestController>().Load(path, parentNode);
}但它只会导致一个错误
NullReferenceException:未设置为对象实例的对象引用
this.something工作正常,所以在我的GetComponentInParent<mllhildTestController>()部分的逻辑中,它必须是一个错误。
有人能帮帮我吗?
编辑:这个函数看起来很好,但是因为它是被问到的
public string ReturnLabel()
{
return buttonText.text;
}控制器脚本
public class mllhildTestController : MonoBehaviour
{
public mllhildTestLinq linq;
public mllhildTestDisplay display;
public mllhildTestButtons buttons;
public List<GameObject> listToStuff;
public string test = "smName";
public string smName = "mllhild";
public string displayText = "display.textWindow.font";
public string path = @"C:\SlaveMaker4\Slaves\";
// Start is called before the first frame update
void Start()
{
ClearText();
// linq.LinqTest(@"C:\SlaveMaker4\Rhia.xml");
// string filename = @"C:\SlaveMaker4\Rhia.xml";
// linq.QueryXML(filename, parentNode);
// Debug.Log(this.GetType().GetField("test").GetValue(this));
// Debug.Log(this.GetType().GetField(test).GetValue(this));
// Debug.Log(display.textWindow.font);
// Debug.Log(this.GetType().GetField("display").GetType().GetField("textWindow").GetType().GetField("font").GetValue(this));
// Debug.Log(typeof(TextMeshProUGUI).GetProperty(displayText).GetValue(this));
// Debug.Log(this.GetType().GetField(displayText).GetValue(this));
}
// Update is called once per frame
void Update()
{
}
public void SetText(string text)
{
display.textWindow.text = text;
}
public void AddText(string text)
{
display.textWindow.text += text;
}
public void ClearText()
{
display.textWindow.text = null;
}
public GameObject bfield;
public GameObject AddNewButtonList(string label)
{
GameObject b = Instantiate(bfield) as GameObject;
b.SetActive(true);
b.GetComponent<PrefabListButtoms>().title.text = label;
b.transform.SetParent(bfield.transform.parent, false);
return b;
}
public void Clear()
{
foreach(GameObject b in listToStuff)
{
Destroy(b);
}
listToStuff.Clear();
}
public void LoadButton() { Load(path, "Language" ); }
public void Load(string path, string parentNode)
{
string[] fileArray = Directory.GetFiles(path, "*.xml");
foreach (string xmlfile in fileArray)
{
GameObject blist = AddNewButtonList(xmlfile + "\n" + parentNode);
listToStuff.Add(blist);
//AddText("\n\n" + xmlfile + "\n");
//AddText("Parent-Node:" + parentNode + "\n");
//AddText("Child-Nodes:" + "\n");
linq.QueryXML(xmlfile, parentNode, blist);
}
}
}发布于 2020-05-14 12:37:12
你不能直接访问,因为你必须找到父母,然后你找到想要的孩子
因此,您的第一个挑战是找到组件的父级:
第一个命令是:GameObject.Find("NameofObj")或GameObject.FindWithTag("NameOfTag")
因此,在您从这个GameObject..and中找到所需的子组件之后,您最终可以访问链接到子脚本的方法
https://stackoverflow.com/questions/61796533
复制相似问题