首页 > 解决方案 > Unity3d,无法通过字符串使用GetComponent从另一个脚本调用脚本

问题描述

我尝试从一个游戏对象脚本,另一个游戏对象脚本调用一个函数,但我需要它使用字符串但是当我尝试这样做时

GameObject.Find("Player").GetComponent("myscript").myfunction= false;

在我可以运行之前,统一给了我以下错误

Assets\GenericActor.cs(94,40): error CS1061: 'Component' does not contain a definition for 'myfunction' and no accessible extension method 'myfunction' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)

标签: c#unity3d

解决方案


尝试:

MyScript playerScript = GameObject.Find("Player").GetComponent<MyScript>().myfunction = false;

也可以使用标签来完成:

MyScript playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MyScript>().myfunction = false;

另外,如果你调用像 void MyFunction(bool myBool) 这样的函数,你会使用

MyScript playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<MyScript>().MyFunction(false);

推荐阅读