【发布时间】: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<Movement>();声明不是if声明的一部分。您的缩进使它看起来像您认为的那样......但是如果您想将两个语句作为if语句的主体,则需要使用大括号。我强烈建议对 allif语句的主体使用大括号以避免此类问题。目前,AddComponent将在 每次Update执行时被调用。