My weapon switching script is not working?

So, I added the tag “Item” to both of the items and then tried to pick them up, no error but nothing happens. Please tell me what is wrong, I can’t find it.

using UnityEngine;
using System.Collections;

public class weaponManager : MonoBehaviour {

	public GameObject Apple;
	public GameObject Bread;
	public Camera Camera;
	int weaponOut = 1; // 1==apple 2 == bread

	void Update() {

		if (Input.GetKeyDown (KeyCode.E)) {

			RaycastHit hitInfo;
			Ray ray = Camera.ScreenPointToRay(new Vector2 (Screen.width / 2, Screen.height / 2));

			if (Physics.Raycast(ray, out hitInfo)) {

				if (hitInfo.transform.tag == "Item") {

					if (hitInfo.transform.gameObject.name.Contains("Apple")) {

						changeWeapon (1);

						if (weaponOut == 1) {
							Destroy (hitInfo.collider.gameObject);
							Instantiate (Apple, transform.root.transform.position + new Vector3 (0, 2, 0), Quaternion.identity);
						}	else if (weaponOut == 2) {
							changeWeapon (2);
							Destroy (hitInfo.collider.gameObject);
							Instantiate (Bread, transform.root.transform.position + new Vector3 (0, 2, 0), Quaternion.identity);
						}

					}	else if (hitInfo.transform.gameObject.name.Contains ("Bread")) {

						changeWeapon (2);

						if (weaponOut == 1) {
							Destroy (hitInfo.transform.gameObject);
							Instantiate (Apple, transform.root.transform.position + new Vector3 (0, 2, 0), Quaternion.identity);
						}	else if (weaponOut == 2) {
							Destroy (hitInfo.transform.gameObject);
							Instantiate (Bread, transform.root.transform.position + new Vector3 (0, 2, 0), Quaternion.identity);
						}

					}

				}

			}

		}

	}

	void changeWeapon(int weapon) {
		if (weapon == 1) {
			weaponOut = 1;
			transform.FindChild("Apple").gameObject.SetActive(true);
			transform.FindChild("Bread").gameObject.SetActive(false);
			Debug.Log ("Changed Weapon!");
		} else if (weapon == 2) {
			weaponOut = 2;
			transform.FindChild("Apple").gameObject.SetActive(false);
			transform.FindChild("Bread").gameObject.SetActive(true);
			Debug.Log ("Changed Weapon!");
		}
	}

}

Hello, Are you sure the raycast is hiting the item?

  • Did you debug what object it is hitting
  • I would recommend you use a Simple collider instead of raycast to see if you hit the item
  • Try debugging your if statement to find the error