- Home /
Object being destroyed without GetKey Down
Hi. I'm making a game where you have to travel through a cave and collect artifacts and crystals to make money and I'm having a problem with the destruction of the crystal when it is collected.
When the user presses "E", the OnTriggerEnter(Collider ActiveObject) is supposed to be destroyed but whenever I run the game in the editor, the object is destroyed as soon as the player comes in contact with the trigger collider.
Thanks in Advance. I'm only three days into learning C#, so my mistake is probably obvious :D.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Collection : MonoBehaviour {
public bool collectible;
private int inv_GCrystal;
public string rmessage;
public GameObject GCrystal;
public Text Resource;
public GameObject ActiveObject;
// Use this for initialization
void Start () {
collectible = false;
inv_GCrystal = 0;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter (Collider ActiveObject) {
if (Input.GetKey (KeyCode.E))
inv_GCrystal += (Random.Range (0, 3));
print (ActiveObject);
Destroy (ActiveObject.gameObject);
if (gameObject.tag == "GCrystal")
Debug.Log ("Right-Click or press 'E' to mine the crystal");
rmessage = "Right-Click or press 'E' to mine the crystal";
Resource.text = rmessage;
collectible = true;
}
void OnTriggerExit () {
collectible = false;
rmessage = "";
Resource.text = rmessage;
}
}
Answer by Reynarz · Jul 25, 2017 at 01:40 AM
The problem is in your "if statement", is just taking in count the first element, and not the others.
Example:
if(This is true)
Execute this just if is true.
I will do my work any way.
I will do my work any way.
But
if(This is true)
{
Execute this, just if is true.
Execute this, just if is true.
and Execute this, just if is true.
/*Otherwise not*/
}
You need use the Curly brackets "{ }" in your if statement.
Your answer
Follow this Question
Related Questions
Key and Door Tutorial Help? 2 Answers
How do I destroy my player on contact? 2 Answers