Reputation: 13
Trying to detect if an object is overlapping with another object by using a Raycast Sphere with little or no distance. My relevant code is as follows:
//Check at location using Stationary Spherecast, apply damage effect if its a unit
if (Physics.SphereCast (transform.position, 3, Vector3.up, out hit, 1)) {
Debug.Log ("In Spherecast");
if (hit.transform.CompareTag ("Enemy unit") || hit.transform.CompareTag ("Player Unit")) {
Debug.Log ("In Spherecast's If");
int Dmg = MM.MoveStat (Ours, SM.selected.GetComponent<EidolonClass> (), hit.transform.gameObject.GetComponent<EidolonClass> ());
hit.transform.gameObject.GetComponent<EidolonClass> ().TakeDamage (Dmg);
}
}
At present, however, neither of those Debug.Log statements ever get output to the console. Is there something I'm misunderstanding about the spherecast, or about its constructors?
Upvotes: 0
Views: 3446
Reputation: 125245
Trying to detect if an object is overlapping with another object
Use one of the Physics.OverlapXXX
functions. There are many of them but if Sphere is what you are looking for then Physics.OverlapSphere
should be used.
For the sake of performance, use the ones that ends with NonAlloc
.
Physics.OverlapSphereNonAlloc
should be fine for this. Just check if what it returns is > 0
.
Collider[] colliders = new Collider[5];
void Update()
{
if (Physics.OverlapSphereNonAlloc(transform.position, 3, colliders) > 0)
{
//Overlaps!
}
}
Note:
Make sure that a collier is attached to both GameObjects you want to check of they overlap with one another.
EDIT:
If you need to access the Colliders
too:
Collider[] colliders = new Collider[5];
void Update()
{
int hitCount = Physics.OverlapSphereNonAlloc(transform.position, 3, colliders);
if (hitCount > 0)
{
Debug.Log("Touching!");
for (int i = 0; i < hitCount; i++)
{
Collider C = colliders[i];
Debug.Log("In Foreach for: " + C.name.ToString());
if (C.transform.CompareTag("Enemy Unit"))
{
Debug.Log(C.name.ToString() + " Is an enemy");
//...
}
}
}
else
{
Debug.Log("Not Touching!");
}
}
Upvotes: 3
Reputation: 13
Ended up finding a solution that worked, taking ideas from the solutions Programmer and rutter suggested, as welll as looking around both on this site and on the official Unity Forums to find a solution that did what I needed. Heres the finished segment of code:
Collider[] collisions = Physics.OverlapSphere(transform.position,.75f);
foreach (Collider C in collisions) {
Debug.Log("In Foreach for: " + C.name.ToString());
if (C.transform.CompareTag ("Enemy Unit")) {
Debug.Log (C.name.ToString () + " Is an enemy");
int Dmg = MM.MoveStat (Ours, SM.selected.GetComponent<EidolonClass> (), C.transform.gameObject.GetComponent<EidolonClass> ());
C.transform.gameObject.GetComponent<EidolonClass> ().TakeDamage (Dmg);
}
}
Upvotes: 0