c# - Unity - 如何让两个相同的游戏对象发生碰撞、相互破坏并在目标位置生成一个新的游戏对象?

标签 c# unity3d unityscript

所以我想让两个球发生碰撞, self 毁灭,然后在它们的位置产生另一个球(最好以特定的速度)。但是,当我尝试将脚本附加到球上时,球的两个实例在接触时都被破坏,然后立即产生两个球的预制件,因为它们都有代码。这会导致两个球一遍又一遍地产生并相互摧毁。我将这个脚本附加到球上:

private Vector3 ballPosition;

void OnTriggerEnter2D (Collider2D other) {

    if (other.gameObject.tag == "Ball") {

        ballPosition = new Vector3 ((transform.position.x + other.transform.position.x) / 2, (transform.position.y + other.transform.position.y) / 2, 0.0f);
        StartCoroutine ("RespawnBall");
    }
}

IEnumerator RespawnBall () {

    Instantiate (gameObject, ballPosition, Quaternion.identity);
    Destroy (gameObject);
    yield return null;
}

如何让这段代码销毁两个球,然后只生成预制件的一个实例?

最佳答案

您还可以在脚本中使用一个 bool 值,设置为只有第一个球具有 OnTriggerEnter2D()方法调用将生成一个新球:

private Vector3 ballPosition;
public bool spawnNewBall;

void Start() {
    spawnNewBall = true;
}

void OnTriggerEnter2D (Collider2D other) {

    if (other.gameObject.tag == "Ball") {

        if (spawnNewBall) {
            other.GetComponent</*YourScriptName*/>().spawnNewBall = false;
        }

        ballPosition = new Vector3 ((transform.position.x + other.transform.position.x) / 2, (transform.position.y + other.transform.position.y) / 2, 0.0f);
        StartCoroutine ("RespawnBall");
    }
}

IEnumerator RespawnBall () {
    if (spawnNewBall) {
        Instantiate (gameObject, ballPosition, Quaternion.identity);
    }
    Destroy (gameObject);
    yield return null;
}

更简单地说,就是这样做:

public class TwoToOne : MonoBehaviour {

    public bool doNothing;

    void OnCollisionEnter (Collision col)
        {
        if (doNothing) return;

        col.gameObject.GetComponent<TwoToOne>().doNothing = true;
        Destroy(col.gameObject);

        GameObject newCube = Instantiate(gameObject);

        Destroy(gameObject);
        }

    }

这是 Unity 中完全常见的脚本或模式。

因此,从概念上讲,您只是“摧毁另一个”;由于其中一个脚本必须首先运行,因此效果很好。在与 Unity 不同的系统中,您可以执行以下操作之一:

  • A,以某种方式“摧毁”另一个游戏对象。那将是 DestroyImmediate(col.gameObject)在 Unity 中。

  • B,以某种方式“破坏”或禁用其他脚本。那将是 col.gameObject.GetComponent<TwoToOne>().enabled = false在 Unity 中

  • C,以某种方式在另一个游戏对象上“标记”(设置一个 bool 值)- 如此处所示。

碰巧,在 Unity 中你不能做 A 或 B,所以你只能做 C。B 是最优雅的解决方案,但它在 Unity5 中不起作用,所以现在做 C!

关于c# - Unity - 如何让两个相同的游戏对象发生碰撞、相互破坏并在目标位置生成一个新的游戏对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880543/

相关文章:

c# - C# 4.0 中用于文件加载的多线程

c# - iTextSharp - 将元素从一个 PDF 复制到另一个

unity3d - 当光源在侧面时,为什么我的统一对象的底部比顶部暗?

android - 处理器计数可靠性

unity3d - unity3d 中的屏幕记录

vector - 在 Unity 4.3 中将 2d 对象移向并穿过某个位置

c# - 使用 Unity 进行开发的最佳语言?

c# - ASP.NET Core MVC 异步加载 session

c# - 循环迭代父节点,直到找到特定标签

c# - 根据顶点和点获取抛物线/圆弧