- Home /
killzone not detecting player
I want an invisible cube that kills the player if the player touches it. the player runs on a player controller, using a script called walk.cs, has 3f health and the process used to lower said health is ddamage
I set the cube so it has no renderer, and added the trigger tag to the cube collider, but its not even printing "pão" like I asked it to, which means it isnt even detecting the collision
also, I have tried using OnControllerColliderHit, but it didnt work either
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class killzone : MonoBehaviour
{
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == ("Player"))
{
print("pão");
walk target = col.transform.GetComponent<walk>();
target.ddamage(3f);
}
}
}
Answer by tyruji · Jun 30, 2021 at 06:01 PM
OnCollision, as well as OnTrigger messages, are called by game objects with a rigidbody attached, respectively OnControllerColliderHit is called for game objects with a character controller. Make sure you have either and you'll be good.
I tried using OnControllerColliderHit, since my player is based on a Character Controller, but no matter how many alterations I make, it doesnt seem to make a difference, and the player still isnt being detected.
public class killzone : MonoBehaviour
{
void OnControllerColliderHit(ControllerColliderHit col)
{
if (col.gameObject.CompareTag("Player"))
{
print("pão");
walk target = col.transform.GetComponent<walk>();
target.ddamage(3f);
}
}
}
Aight, I'll repeat myself - OnControllerColliderHit will be called for game objects with a character controller attached. I assume your player has a character controller attached, your script will work if your killzone has a character controller on it as well. If your killzone is a cube or multiple cubes then you could use Physics.OverlapBox to get all colliders overlapping with your cubes. Something like that: private BoxCollider[] _boxColliders = null;
private void Start()
{
_boxColliders = GetComponents<BoxCollider>();
}
private void Update()
{
Player player = null;
foreach( var box in _boxColliders )
{
foreach( var col in Physics.OverlapBox(transform.position +
box.center, box.size/2, transform.rotation) )
{
if( !col.gameObject.CompareTag("Player") ) return;
player = col.gameObject.GetComponent< Player >();
}
if( player != null ) break;
}
if( player == null ) return;
player.Damage( 420 ); // do whatever you want
}
Hope I helped somehow, good luck.