- Home /
Network.Destroy and collision; destroying correct object.
Got a small problem regarding Network.Destroy and OnCollisionEnter. In my multiplayer game, I have a Network.Instantiated prefab (a target) that needs to be destroyed upon contact with another Network.Instantiated prefab (a bullet). However, there needs to be multiple of each prefab in the scene at once, which is where I'm having the issue.
Originally, I wrote a standard OnCollisionEnter function in two scripts (one on each prefab object) handling their destruction on contact with one another. The collision function didn't work at all, let alone the destruction, so I'm now using the tag method shown below:
Function for the target prefab:
function OnCollisionEnter(collision : Collision)
{
if (networkView.isMine && collision.collider.gameObject.tag == "bullet")
{
Debug.Log("Destroyed.");
Network.Destroy(gameObject);
}
}
Function for the bullet prefab:
function OnCollisionEnter(collision : Collision)
{
if (networkView.isMine && collision.collider.gameObject.tag == "asteroid")
{
Debug.Log("Destroyed bullet.");
Network.Destroy(gameObject);
}
}
This worked for the collision and destruction, but because every prefab clone has the same tag, it seems random individual bullets and targets in the scene are destroyed as opposed to the ones making contact. Any easy way to make sure the correct bullet and target are destroyed on contact? Thanks for any help.
Answer by trs9556 · May 05, 2013 at 11:55 PM
I don't think this would work exactly right, because theoretically one will destroy one before the other gets a change to destroy the other, but maybe you can try destroying each others GameObjects.
So the bullet destroys the player and the player destroys the bullet?
Change Network.Destroy(gameObject); to Network.Destroy(collision.gameObject).
Another way to go about this (although it would change the physics on your game) is to get rid of the target prefab's script and have the bullet do everything. And in the bullet's script you can have it auto die after x amount of seconds. This would simulate collateral damage as well.
I don't think it would make a difference, but also try Network.Destroy(this.gameObject);
Let me know the results.