【发布时间】:2019-09-15 03:11:57
【问题描述】:
所以在我的项目中,我有一个原始对象,每次我按下特定键时,它都会克隆该对象并向克隆添加一个移动脚本。
原始对象移动有点慢,因为它也有移动脚本,但是从第一个克隆开始,速度有非常明显的提高。每次我克隆它都会不断增加,所以它必须每次都在自我繁殖或类似的东西。
我不知道该怎么做,虽然我可以在层次结构中看到,当我第一次克隆时,它会生成一个克隆,这是正常的。当我第二次克隆时,它会生成两个克隆:
游戏对象(克隆), 游戏对象(克隆)(克隆)
它似乎正在制作克隆的克隆。不过,那个分身根本无法动弹,只是坐在那里。为什么会有克隆的克隆,如何使所有克隆的速度保持在原始速度?
我试图查看代码并查看处理实例化对象的特定部分,以及整个移动脚本,但我不确定要查找什么...
这是移动脚本(我已经包含了大部分 WASD 脚本以使该项目可重现):
public class MovementScript : MonoBehaviour {
public static Rigidbody rb;
public float thrust = 900f;
public int Savings;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey(KeyCode.A)) {
//Sets Velocity to zero on Y so it can change direction without delay
rb.velocity = Vector3.zero;
rb.AddForce(Vector3.left * thrust);
}
else
{
rb.velocity = Vector3.zero;
}
if (Input.GetKey(KeyCode.D))
{
//Sets Velocity to zero on Y so it can change direction without delay
rb.velocity = Vector3.zero;
rb.AddForce(Vector3.right * thrust);
}
else
{
rb.velocity = Vector3.zero;
}
if (Input.GetKey(KeyCode.W))
{
//Sets Velocity to zero on Z so it can change direction without delay
rb.velocity = Vector3.zero;
rb.AddForce(Vector3.forward * thrust);
}
else
{
rb.velocity = Vector3.zero;
}
if (Input.GetKey(KeyCode.S))
{
//Sets Velocity to zero on Z so it can change direction without delay
rb.velocity = Vector3.zero;
rb.AddForce(Vector3.back * thrust);
}
else
{
rb.velocity = Vector3.zero;
}
if (Input.GetKeyDown(KeyCode.Space))
{
//Freeze all positions
rb.constraints = (RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ);
}
}
}
这是我的实例化脚本的一部分:
if (Savings >= 5 && Input.GetKeyDown(KeyCode.Alpha1))
{
CheckIf = CheckIf + 1;
Debug.Log(Savings);
//this instantiates or clones ArcadeGame1 and gives it a new position on the area
GameObject clone = Instantiate(ArcadeGame1, new Vector3(-2, 3, 13), Quaternion.identity);
//this gives a movement script to the new clone in order to help it move
clone.AddComponent<MovementScript>();
}
我希望当我按下克隆键时只有一个克隆,即使在第一次之后也是如此。如果我按克隆键 5 次,应该有 5 个克隆加上原来的。
它们也应该以与原始速度相同的速度移动。第 5 个克隆的移动速度应该与原始对象一样快。
感谢您帮助我解决我的问题。
【问题讨论】:
-
This is one of the parts of my instantiating script:那个脚本附在什么上面? -
这似乎与静态刚体有关。尝试删除静态关键字
-
检查对象嵌套的位置。它可能是您从中克隆的对象的子对象,并且将从其位置相对移动。所以它会增加速度。
-
@Draco18s 脚本已附加到原始游戏对象。
-
我会试试@mchts 谢谢