How to avoid collisions using InstanceID
I am trying to make a multiplayer game. The main problem is the bullets. The bullets spawn at the gun barrel on the drone(the player) which is inside its box collider. There is also another large collider that's a sphere to act as a targeting threshold for players. I need the bullet to avoid collisions with those 2 colliders. Right now this is how I'm doing it:
if (Input.GetKeyDown(KeyCode.Space))
{
var bullet = bulletPrefab;
bullet.GetComponent<Bullet>().spawnEntity = gameObject.transform.GetInstanceID();
bullet.GetComponent<Bullet>().spawnEntityTracker = tracker.transform.GetInstanceID();
Instantiate(bullet, transform.position, transform.rotation);
}
When the player fires the bullet, the bullet has the instance IDs of the objects it's not supposed to hit assigned. The bullet is then instantiated.
void OnTriggerEnter(Collider other)
{
if ( other.gameObject.transform.GetInstanceID() != spawnEntity && other.gameObject.transform.GetInstanceID() != spawnEntityTracker && other.gameObject.tag != "Bullet")
{
Debug.Log(other.gameObject);
Instantiate(spark, transform.position, transform.rotation);
Destroy(gameObject);
}
}
When the bullet hits something it checks if the entity's transform's instance ID is different than the ones it's supposed to ignore.
This doesn't seem to work. I paused the editor and checked if the bullets recorded the instance IDs properly. They did. Even so, they explode when hitting the player that spawned them.
Could you perhaps use layers (friendly bullets don't hit friendly colliders)?
Thats definitely the most performant and proper way to filter collisions if you can.
Your answer
Follow this Question
Related Questions
RPC sending Failed 0 Answers
Instantiate object during collision only once 1 Answer
Sensing an objects collisions by another object 0 Answers
Bullets not moving on client screen. 0 Answers