为什么在更改游戏运行时角色的步行速度时,只对其中一个才能生效



在层次结构中,我有两个第三个controller脚本附加到其中每个脚本

然后,我去了第三个人controller脚本,然后更改了速度变量为公开:

[SerializeField] public float m_MoveSpeedMultiplier = 1f;

然后在我的脚本上我做了:

public float walkSpeed = 10f;
private ThirdPersonCharacter[] thirdPersonCharacter;

然后在清醒中

void Awake()
{
        thirdPersonCharacter = new ThirdPersonCharacter[2];
        for(int i = 0; i < thirdPersonCharacter.Length; i++)
        {
            thirdPersonCharacter[i] = GetComponent<ThirdPersonCharacter>();
        }
}

然后在更新中

void Update()
    {
        thirdPersonCharacter[0].m_MoveSpeedMultiplier = walkSpeed;
        thirdPersonCharacter[1].m_MoveSpeedMultiplier = walkSpeed;
    }

但是,当游戏正在运行时,我在脚本中的"检查员"中的第三个controller之一中更改时,步速值从10到1或从10到20到20到20,它仅影响其中一个字符。为什么它不影响他们两个?

由于它不起作用,所以我尝试了:

public ThirdPersonCharacter[] thirdPersonCharacter;

然后在"开始"功能中删除了代码。然后将第三个controller和第三个controller(1)拖到脚本中的检查员到2。

,并且在运行时更改速度值时,它仅影响其中一个仅构成第三个人controller。

我的总体目标是能够在游戏运行时同时实时控制第三个人controller和第三个人controller(1)相同的速度,然后能够以单独控制每个速度。因此,以后我将拥有3个速度值。一个用于两者,每个两个。但是我还不能使它们都更改。

问题与此帖子中的问题相似。

下面的代码行:

thirdPersonCharacter[i] = GetComponent<ThirdPersonCharacter>();

将返回附加到GameObject this脚本的ThirdPersonCharacter的引用。它将返回 same 在for循环中两次参考。

要获取不同的ThirdPersonCharacter,您必须找到每个单独的gameObject,将ThirdPersonCharacter连接到它们,然后在它们上执行GetComponent

GameObject tpc1 = GameObject.Find("TPC1");
thirdPersonCharacter[0] = tpc1.GetComponent<ThirdPersonCharacter>();
GameObject tpc2 = GameObject.Find("TPC2");
thirdPersonCharacter[1] = tpc2.GetComponent<ThirdPersonCharacter>();

替换 tpc1 tpc2 以gameObjects ThirdPersonCharacter的名称附加到。

您可以在此处找到其他方法。

thirdPersonCharacter[i] = GetComponent<ThirdPersonCharacter>();

以上代码每次返回相同的(第一个)组件。改用此;

void Awake()
{
    thirdPersonCharacter = GetComponents<ThirdPersonCharacter>();
}

相关内容

最新更新