Skip to content

Instantly share code, notes, and snippets.

@soraphis
Last active August 16, 2016 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soraphis/1901fea0e40884af60b21a2b5a741c4e to your computer and use it in GitHub Desktop.
Save soraphis/1901fea0e40884af60b21a2b5a741c4e to your computer and use it in GitHub Desktop.
Reduces code clutter when using sphere casts or raycasts when the actual object should be ignored

Reduces the code:

var colliderGameObject = GetComponentInChildren<Collider>().gameObject;
var originalLayer = colliderGameObject.layer;
colliderGameObject.layer = 2; // IgnoreRaycast Layer (note: Physics.IgnoreRaycastLayer is actually 1 << 2 (the layermask instead of the layer itself))

// do the actual physics stuff:
var colliders = Physics.OverlapSphere(transform.position, 1, SomeLayerMask);
// ... do smth with colliders

colliderGameObject.layer = originalLayer;

to this:

using (new PhysicsDisposable(this.gameObject)) {
    colliders = Physics.OverlapSphere(transform.position, 1, SomeLayerMask);
    // ... do smth with colliders
}
/// <summary>
/// This class uses the decorator pattern and the Idisposable interface to allow a cleaner usage of raycast/spherecasts
/// or other physic quarrys, which should not hit the gameobject
/// </summary>
class PhysicsDisposable : IDisposable {
private static Stack<PhysicsDisposable> Pool = new Stack<PhysicsDisposable>(4);
private List<Collider> colliders = new List<Collider>(2);
private List<int> originalLayer;
private PhysicsDisposable(params Collider[] c) {
colliders.AddRange(c);
originalLayer = new List<int>(colliders.Count);
originalLayer = new List<int>(colliders.Capacity);
for (int i = 0; i < this.colliders.Count; ++i) {
originalLayer.Add(colliders[i].gameObject.layer);
colliders[i].gameObject.layer = GameLayer.IgnoreRaycast; // 2
}
}
public static PhysicsDisposable Create(params Collider[] c) {
if (Pool.Count > 0) {
var p = Pool.Pop();
p.colliders.AddRange(c);
for (int i = 0; i < p.colliders.Count; ++i) {
p.originalLayer.Add(p.colliders[i].gameObject.layer);
p.colliders[i].gameObject.layer = GameLayer.IgnoreRaycast; // 2
}
return p;
} else {
return new PhysicsDisposable(c);
}
}
public static PhysicsDisposable Create(GameObject go) { return Create(go.GetComponentInChildren<Collider>()); }
public void Dispose() {
for (int i = 0; i < this.colliders.Count; ++i) {
colliders[i].gameObject.layer = originalLayer[i];
}
colliders.Clear();
originalLayer.Clear();
Pool.Push(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment