how can I optimize my code

so it’s my code and it’s working fine,when the player get’s damage ,his gun should drop to the ground .

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

public class test : MonoBehaviour {
public int whatGun;

public void Drop(){
		dropgun1 ();
	else if(whatGun==1){
		dropgun2 ();
	else if(whatGun==2){
		dropgun3 ();
	else if(whatGun==3){
		dropgun4 ();


public void dropgun1(){
	gameObject.AddComponent<DropGun1> ();

public void dropgun2(){
	gameObject.AddComponent<DropGun2> ();

public void dropgun3(){
	gameObject.AddComponent<DropGun3> ();

public void dropgun4(){
	gameObject.AddComponent<DropGun4> ();



how can I optimize public void Drop() ??

cause if I want to add for example more than 50 guns ,it should checks 50 ifs !!! I want to use an array

something like this

 public void Drop(){
     dropgun[whatGun] ();


but I have no idea who to do this with functions ,I hope you guys get what I want :slight_smile:

Take a look at Dictionaries. With them you can map for example a string (like the gun name) to the GameObject itself and use something like this:


If you want an integer index, an ArrayList is sufficient. The advantage over normal arrays is, that it’s dynamic in size, so you can add and remove elements without reinitializing a new array.