【问题标题】:How to get variables/functions from a child GameObject?如何从子游戏对象中获取变量/函数?
【发布时间】:2020-01-08 15:46:34
【问题描述】:

您好!我正在尝试创建一个房间,该房间将从列表中生成随机布局并从该布局中获取变量。我在这方面遇到了一些麻烦,因为从游戏开始时布局就没有了,而且我已经在这个问题上工作了几天了。目前,“房间”游戏对象在其子项中搜索标记为“布局”的对象,然后在找到那个游戏对象后,代码从布局的布局组件中获取“waves”变量。代码在这里:

foreach (Transform child in transform)
{
   if (child.tag == "Layouts")
   {
      layout = child.gameObject.GetComponent<Layout>();
   }
}
layout.testFunction();
totalKillsNeeded = layout.waves;

当我运行代码时,什么也没有发生。没有错误或任何东西。尽管我的 Visual Studio 显示了两个脚本之间的引用,但 testFunction 没有运行,尽管我检查并看到 layout.waves 等于 1 或 2,但 totalKillsNeeded 返回 0。我尝试了多种获取 Layout 脚本的方法,所有这些方法已返回相同的结果。这可能是我没有考虑过的小事,但我仍然无法弄清楚。谢谢!

【问题讨论】:

  • 嗨,请您提供更多代码来制作minimal reproducible example 并带有一些示例值。上面的代码遍历所有子转换,获取最后一个并运行 testfunction(布局不应该为空),totalkills 将设置为最后一个波中的任何内容,或者 null.. 你收到警告了吗?错误?
  • 最好在设置布局后添加break; 以退出迭代,您的场景中可能有多个包含布局组件的子组件。
  • GetComponentInChildren&lt;&gt;()?如果不止一个,也可以GetComponentsInChildren&lt;&gt;()
  • 由于某种原因我无法编辑,所以我会在这里发表评论。首先@BugFinder:我知道一个事实,每个房间都会有一个,而且只有一个,不多也不少,作为一个孩子,所以波浪只会得到那个价值。正如我在帖子中所说,我也没有收到任何错误或警告。下一个draco18s-no-longer-trusts-se,这是我已经尝试过的方法之一,抱歉没有具体说明。
  • 考虑使用if ( child.CompareTag("Layouts") ) 以获得轻微的效率优势。

标签: c# unity3d children gameobject


【解决方案1】:

你的代码应该可以工作,但以防万一,试试这个。这是ScriptA.cs,把这个放在父级上

using UnityEngine;

public class ScriptA: MonoBehaviour
{
    int totalKillsNeeded = 0;
    ScriptB layout;

    // Start is called before the first frame update
    void Start()
    {
        foreach(Transform child in transform)
        {
            if(child.CompareTag("Layouts"))
            {
                layout = child.gameObject.GetComponent<ScriptB>();
            }
        }

        layout.testFunction();
        totalKillsNeeded = layout.waves;

        Debug.Log($"Total Kills needed: {totalKillsNeeded}, layout waves {layout.waves}");
    }
}

还有ScriptB.cs,把它放在Child游戏对象上,如果需要的话,在inspector中设置wave

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptB: MonoBehaviour
{
    public int waves = 12;

    public void testFunction()
    {
        Debug.Log("Test Function Called, waves: {waves}");
    }
}

控制台输出:

层次结构应如下所示:

如果你的最后一个孩子有 0 波,你的 for 循环将只显示最后一个:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多