How to get an object when pressing the E key

Posted by Ragthor - Thursday April 22, 2021

In this video we will learn how to obtain an object, specifically a leaf, by pressing the E key and saving the result. From now on I tell you that you can use this method for any object in your game, or even sounds.

 
                     
                     
                     using System.Collections;
                        using System.Collections.Generic;
                        using UnityEngine;

                        public class hoja : MonoBehaviour
                        {

                            bool ingreso = false;
                            public int totalHojas;

                            void Start()
                            {
                                totalHojas = PlayerPrefs.GetInt("hojas");
                            }

                            void Update()
                            {
                                if(ingreso && Input.GetKey(KeyCode.E))
                                {
                                    totalHojas += 1;
                                    PlayerPrefs.SetInt("hojas", totalHojas);
                                    Destroy(gameObject);
                                }

                            }

                            private void OnTriggerEnter(Collider other)
                            {
                                if(other.gameObject.tag == "Player")
                                {
                                    ingreso = true;
                                }
                            }

                            private void OnTriggerExit(Collider other)
                            {
                                if (other.gameObject.tag == "Player")
                                {
                                    ingreso = false;
                                }
                            }
                        }