Fired projectile collision with player issue

Currently I have a bullet projectile coming from a space ship mesh that is surrounded by a sphere(shield) collider that is larger than the ship.

The problem is that my projectiles for the weapons are fired from inside this collider so they immediately make contact and apply damage to the player.

I could use layer based collision management but I intend to use the same weapons and ammo systems for NPC’s so I need them to be able to collide with the player and cause damage as usual. If possible I’d like to avoid creating ‘NPC Only Projectiles’ and ‘Player Only projectiles’.

Is there another method to handle this? This problem will be universal since most of the enemies will have a shield type system. I haven’t worked with the collision system much and can’t think of any quick fixes or work around.

Personally I’d use layers and just set the layer when you instantiate the prefab for you projectile.

Alternatively you could have a script on your projectile that would identify who fired it, then in your OnCollisionEnter() you could get this script from the projectile and see who’s ‘bullet’ it is.

i.e.

void OnCollisionEnter(Collision col)
{
    MyBulletInfo bullet = col.GameObject.GetComponent<MyBullletInfo>();

    if(bullet == null) return;

    // does it match?
    if(bullet.Source == this.Source)
    {    // handle the hit

    }
}

Where Source is some type that would identify the player/npc, i.e.:

public enum ObjectOwner
{
    Player,
    Enemy
}

Naturally this could just be a bool, or alternatively, you could make Source an ID and give players and enemies a unique ID (i.e. a unique int) and then bullets would not hit shields they were aligned with, but could hit other shields, including enemy shields.

But I imagine somewhere you are doing:

GameObject bullet = GameObject.Instantiate(MyActiveBullet) as GameObject;

In which case you surely can add another line:

bullet.layer = wasFiredByPlayer ? LayerConstants.PlayerBullets : LayerConstants.EnemyBullets;

Or similar. This is much more efficient and there is no specialisation of your missile prefabs, you just need to know whether the player or an enemy fired a weapon and I imagine you will know that.

Naturally, you can then adjust the physics settings to determine which bullets can collide which which layers.

Presumably, this is the approach you were considering, perhaps it is made easier seeing how easy it would be to place the ‘bullets’ on the appropriate layer at runtime?

Hope that helps!