【发布时间】:2019-01-31 13:50:48
【问题描述】:
我有圆形游戏对象预制件。我随机实例化它们大约 50-100 次。我给它们添加了刚体,它们四处移动。问题是;我想销毁一组具有相同标签并相互碰撞的预制件。但我无法得到它们的所有对撞机。因为其中一些与第二或第三预制件发生碰撞。我怎样才能在不碰撞它们的情况下得到它们?
我想做什么的图片
我试着用这段代码来做:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Colliders : MonoBehaviour {
public List<GameObject> colliders;
private void Start() {
if (colliders == null)
colliders = new List<GameObject>();
colliders.Add(this.gameObject);
}
private void OnTriggerStay2D(Collider2D col) {
if (col.gameObject.tag != this.gameObject.tag) return; // if colliders haven't the same tag ignore
if (colliders.Contains(col.gameObject)) return; // if colliders already exist in the list ignore
colliders.Add(col.gameObject); // add colliders to the list
if (colliders.Count < 2) return; // if there aren't more than two gameobjects in the list ignore
for (int i = 0; i < colliders.Count; i++) // get all colliders in the list
{
if (colliders[i] == this.gameObject) return; // if it is same as this gameobject ignore
if (colliders[i] == col.gameObject) return; // if it is same as this collider ignore
Colliders colScript = col.gameObject.GetComponent<Colliders>(); // get the collider script attached to the colliders in the list
List<GameObject> colColliders = colScript.colliders; // get the list of the colliders in the list
for (int j = 0; j < colColliders.Count; j++)
{
if (colliders.Contains(colColliders[j])) return; // if colliders already exist in the list ignore
colliders.Add(colColliders[j]); // add colliders to the list
}
}
}
private void OnCollisionExit2D(Collision2D col) {
for (int i = 0; i < colliders.Count; i++) // get all colliders in the list
{
if (colliders[i] == this.gameObject) return; // if it is same as this gameobject ignore
Colliders colScript = col.gameObject.GetComponent<Colliders>(); // get the collider script attached to the colliders in the list
List<GameObject> colColliders = colScript.colliders; // get the list of the colliders in the list
for (int j = 0; j < colColliders.Count; j++)
{
if (!colliders.Contains(colColliders[j])) return; // if colliders not exist in the list ignore
colliders.Remove(colColliders[j]); // remove colliders from the list
}
}
if (col.gameObject.tag != this.gameObject.tag) return; // if colliders haven't the same tag ignore
if (!colliders.Contains(col.gameObject)) return; // if colliders not exist in the list ignore
colliders.Remove(col.gameObject); // remove colliders from the list
}
}
【问题讨论】:
-
为什么现在只检查标签删除
OnTriggerExit中的所有内容? -
我看到并修复了,但我在这个项目上工作了大约 5-7 个小时,我之前写得很好。它没有给出编码错误。但我无法得到所有对撞机。这段代码只是为了给你看。
标签: unity3d collision-detection collision