Reputation: 13
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.
Upvotes: 1
Views: 7775
Reputation: 924
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);
}
}
Upvotes: 1
Reputation: 406
What should I do to make this work?
I personally would use different approach then overlap. One of the easiest solutions is to use colliders and object tags.
To answer why is your code not working. It is mainly because variable "dead" is not bool and 'UnityEngine.Collider[]' cant be value "true".
This is example of Unity prefab 1st person controller which have assigned following script. After that all object which have any collider and tag set ro "red" will so to speak react to scrip.In this case it will write "I have collided with trigger"+something.
using UnityEngine;
public class collisionTest : MonoBehaviour {
void OnTriggerEnter(Collider trigg)
{
if (trigg.gameObject.tag == "Red")
{
Debug.Log("I have collided with trigger" + trigg.gameObject.name);
//do your stuff
}
}
}
Upvotes: 0