Breaking Object by Destroying it and Instantiating Broken Parts problem, help!
Alright so I have this setup. I have a canon object which has a script on it that instantiates a canonball rigidbody and adds force to it which sends it flying forward. The canonball has a sphere collider and it is not a trigger. That part works great, I wanted to make another script which I would use to attach to an object I want to destroy when it gets hit by the canonball, but before it gets destroyed, it instantiates another object that represents broken parts of the object that gets destroyed. Here is the script I'm using:
using UnityEngine;
using System.Collections;
public class DestroyDoor : MonoBehaviour
{
public Transform brokenPos;
public GameObject brokenDoor;
// Use this for initialization
void OnCollisionEnter(Collider other)
{
if (gameObject.tag == "Canonball")
Instantiate(brokenDoor, brokenPos.position, brokenPos.rotation);
Destroy(gameObject);
}
}
It absolutely does not work lol doesn't instantiate anything nor it does destroy anything, it did destroy the object but I saved the script or did something and now it doesn't even do that. So could somebody please help me out because I'm not sure how to go about a rigidbody hitting something and using that as a OnTriggerEnter or OnCollisionEnter, whatever. Could somebody please write a working script and explain please? Thanks!
Answer by Leuthil · May 11, 2016 at 01:22 PM
Your code seems mostly correct. One glaring error I see is that you have
gameObject.tag == "Canonball"
which is incorrect since gameObject refers to this gameObject. Instead it should be:
other.gameObject.tag == "Canonball"
Other than that, as long as your brokenDoor is a prefab of a broken door and brokenPos is a correctly assigned transform position, it should work as intended.
However I'm not sure why you have the spawning broken door being positioned in a variable spot. Seems to me like you could just do:
Instantiate(brokenDoor, transform.position, transform.rotation);
which would guarantee that it spawns exactly in the same position and orientation of the original door game object.
Yeah that seemed to fix it thanks man! Have my rep lol. I'm using the transform variable as the spot because the pivot and local point of the door is a bit weird because I made more than one object without using layers and such in blender so it took the pivot point of a different object and it is messed up and not centered or somewhere near the door, so if I used its own transform it would spawn somewhere under the scene. Thanks for the help tho.
Answer by Prasenjit_LinuxGuy · May 11, 2016 at 03:01 PM
Use this one from line 10
void OnCollisionEnter(Collider other)
{
if (other.gameObject.tag == "Canonball") // Or you can use if (other.game.name == ("Heirarical name of canonball"))
Instantiate(brokenDoor, brokenPos.position, brokenPos.rotation);
Destroy(other.gameObject);
} }