I'm working on my first Unity game and I'm having a problem with this script.
void FixedUpdate ()
{
Debug.Log ("dead is " + dead);
dead = Physics.OverlapSphere (frontCheck.position, radius, whatIsWall);
if (dead == true)
{
Debug.Log ("Player died!");
Invoke ("Reset", 1);
}
}
void Reset()
{
SceneManager.LoadScene ("Game");
}
I'm trying to make the bool dead
true when the player runs into a wall, using a transform in front of the player. I was using Physics2D.OverLapPoint and it worked fine, but I had to change player's physics to 3D. I'm trying to use OverLapSphere now, but Im getting an error message "Cannot implicitly convert type UnityEngine.Collider[]
to bool
. What should I do to make this work? Im very much a beginner to Unity and coding in general, so it's probably a simple fix. Maybe I just need to try something else? thanks.
Better Approach
I believe a better approach to detect collisions is using OnColissionEnter. https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
That way you can have a simple check such as:
void OnCollisionEnter(Collision col) {
if (col.gameObject.tag == "Wall"){
dead = true;
}
}
Here is a short tutorial on that: https://unity3d.com/learn/tutorials/topics/physics/detecting-collisions-oncollisionenter
Using OverlapSphere
If for some reason you prefer OverlapSphere, then you need to know that it doesn't return a bool as you are expecting. Instead, it returns all colliders that overlap with the sphere.
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
I believe what you are looking for is:
void FixedUpdate ()
{
Debug.Log ("dead is " + dead);
Collider[] hitColliders = = Physics.OverlapSphere (frontCheck.position, radius, whatIsWall);
if (hitColliders.length != 0) {
Debug.Log ("Player died!");
Invoke ("Reset", 1);
}
}