【问题标题】:Why does AddComponent add too much scripts? [closed]为什么 AddComponent 会添加太多脚本? [关闭]
【发布时间】:2022-01-20 06:11:29
【问题描述】:

我对 Unity 很陌生,我设置了这个脚本来在我的游戏中生成单位,但由于某种原因,每当生成单位时,它会继续添加如此多的移动脚本,以至于它严重滞后于 unity,我做了什么错了吗?

代码:

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

public class Spawn : MonoBehaviour
{

    public Rigidbody DemoUnit;
    public Transform SpawnArea;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.O))
            Instantiate (DemoUnit, SpawnArea.position, SpawnArea.rotation);
            DemoUnit.gameObject.AddComponent<Movement>();

    }
}

【问题讨论】:

  • 如果您有很多 Spawn 类的实例,将为每个实例执行代码。在场景检查器中检查 Spawn 实例,以便只有一个实例。
  • 提示:您的DemoUnit.gameObject.AddComponent&lt;Movement&gt;(); 声明不是if 声明的一部分。您的缩进使它看起来像您认为的那样......但是如果您想将两个语句作为if 语句的主体,则需要使用大括号。我强烈建议对 all if 语句的主体使用大括号以避免此类问题。目前,AddComponent 将在 每次 Update 执行时被调用。

标签: c# unity3d


【解决方案1】:

您忘记用花括号括住 if 语句的内容。 这应该可以解决问题:

void Update()
{
    if (Input.GetKeyDown(KeyCode.O))
    {
        Instantiate (DemoUnit, SpawnArea.position, SpawnArea.rotation);
        DemoUnit.gameObject.AddComponent<Movement>();
    }
}

没有花括号,您的代码等效于以下代码,并且每帧都添加了组件:

void Update()
{
    if (Input.GetKeyDown(KeyCode.O))
        Instantiate (DemoUnit, SpawnArea.position, SpawnArea.rotation);

    DemoUnit.gameObject.AddComponent<Movement>();
}

此外,我相信您想将组件添加到新创建的实例而不是预制件中:

void Update()
{
    if (Input.GetKeyDown(KeyCode.O))
    {
        var instance = Instantiate (DemoUnit, SpawnArea.position, SpawnArea.rotation);
        instance.gameObject.AddComponent<Movement>();
    }
}

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 2013-07-08
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多