How do I check to see if two gameObjects are of the same prefab?

I am trying to make a game where the player can hold one weapon in each hand and if the 2 weapons are the same weapon or spell, it would do…something. Right now I just want the program to actually recognize when the 2 weapons are of the same type, which is not happening. I think it’s because the way I wrote it makes it so it’s checking to see if the 2 weapons are literally the exact same gameObject.

public Spell Rweapon;
public Spell Lweapon;

public void setweaponr(Spell weapon)
    {
        if (Rweapon != null)
        {
            Destroy(Rweapon.gameObject);

        }

        if (weapon == Lweapon)                ***this is the part that is not registering correctly***
        {

            Debug.Log("2hand");
        }
        else
        {
            Rweapon = Instantiate(weapon, gun1.position, gun1.rotation, gun1);
            Rmcost = Rweapon.manacost();

   
        }      
    }

As it is, it should be showing a message in the console that says 2HAND, but it’s not showing up. Everything else works just fine but not that part.

You are right! It is checking if the two game objects are exactly the same.


How to fix this?

Method 1: The simplest solution would just to have a variable, like a string, and compare if they are the same.

Method 2: Similarly, you can also check the tags of the two game objects (weapons) and check if they have the same tag.


If you choose method 1, here some template code:

/*within each weapon script*/

private string weaponType = "typeOfWeapon";//assign the string

/*Checks If The Parameter String Is Equivalent To 'weaponType'*/
public bool isEqualType(string type){
     return weaponType.Equals(type);
}

/*Gets Weapon Type String*/
public string GetWeaponType(){
     return weaponType;
}


/*-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=*/
/*within the script you provided above in your post*/

//replace 'InterfaceScript' with the appropriate script name
if(weapon.GetComponent<InterfaceScript>().isEqualType(Lweapon.GetComponent<InterfaceScript>().GetWeaponType())){//if they are the same type
     //then, whatever you want to do here
}

If you choose method 2:

if(weapon.tag.Equals(Lweapon.tag)){//if they have the same tag
      //then, whatever you want to do here
}
/* *
 * [IMPORTANT]: You must add tags to the game objects/weapons (done within the inspector)
 * */

Tutorial On Tags


If you need additional help, feel free to let me know. :slight_smile:
@alexandersueme