【问题标题】:Unity3d, can't call Script from another script using GetComponent via stringUnity3d,无法通过字符串使用GetComponent从另一个脚本调用脚本
【发布时间】:2020-07-29 23:11:23
【问题描述】:

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

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

unity 在我可以运行之前给了我以下错误

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?)

【问题讨论】:

  • 您需要将GetComponent的结果转换为脚本的类型。
  • 对不起,你能详细解释一下吗?
  • GetComponent 返回一个 GameObject 类型的对象。 GameObject 没有名为 myfunction 的方法。您需要将GetComponent 的结果转换为myscript 类型。
  • 如果不清楚,请查看 typecasting。
  • @3Dave 如果我错了,请原谅我,我有点生疏了,难道没有通用形式的 GetComponent 吗?像 .GetComponent("my script")?

标签: c# unity3d


【解决方案1】:

试试:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2013-11-22
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多