I’ve been googling for an hour, found alot of scripts, but can’t get any of them to work. The problem is, i’m pretty new to programming and I’m trying to learn it.
Now, I have a Player which is tagged as Player and a trap which i tagged Enemy. I have basic movement for my character. I’m using navmesh aswell.
Should i be adding a collider(box,capsule etc) to my Player and to the Trap? Also if someone could tell me how the script would Exactly look like? Thanks in advance. It’s been bugging me for a few hours now xD. Sucks to be a newbie ^^.
This is what i tried.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision otherObj)
{
if (otherObj.gameObject.tag == "Player") {
Destroy (gameObject, .5f);
}
}
}
Next, there’s no need for the Start and Update methods to remain in this class since you do nothing in them.
Also, a OnCollisionEnter implies that the collider is not a trigger… this implies that you can’t walk through the trap. Usually event colliders are setup as a Trigger, in which case you’d use OnTriggerEnter.
Lastly, in your code you ‘Destroy(gameObject)’, this destroys the object that the script is attached to. Then again… you call this script ‘Player’, but check if the ‘otherObj’ is tagged as “Player”… which is which? These names are confusing… one should be the Player, the other the Trap.
I’ll try with OnTriggerEnter. So, "otherObj " should be tagged as " enemy " then? That’s the tag on my trap. Thanks for the help, i let you know how it turns out
Do you have a rigidbody on 1 or both of your objects? (Trap & Player)
Trigger is more likely what you want for a trap, so you’d set the Collider on the Trap to “isTrigger”.
Does that help?
Okay i finally figgured it out. I made a cube and put it into my trap and added a box collider, disabled it’s mesh. Added this to the trap and made the box collider a trigger:
using UnityEngine;
using System.Collections;
public class Trapp : MonoBehaviour {
public GameObject objToDestroy;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
Destroy(objToDestroy);
}
}
Excellent Glad you got it working. (Small performance tip to remember for the future, unless this has been patched since I last saw.)
Using the following is more garbage collector friendly, but still does the same thing you want. *probably doesn’t matter much if it’s used sparingly, either way, but it doesn’t hurt to know.
other.CompareTag("player");
Oh and just a note, you needn’t concern yourself with linking the object to destroy (unless it was some other random object (ie: not the trapp or player).
You can call:Destroy(other.gameObject);
and it will do what you’re doing now.