- Home /
Cleanly destroying transforms
For my game I have written some code to allow players to 'weld' two objects together at certain points on an object. These weld points are just empty game objects that are transforms, children of the object that they are attached to. Since I do not want players to be able to weld multiple objects to the same weld point, I am destroying the weld points that were used after a weld is completed, and then moving all of the other weld points to a new object, created by the weld code.
This is where I get an error, since Unity is still trying to use the transform that I destroyed with Destroy().
Any help would be appreciated, and if you need any code other than what I put here please just let me know.
//Get the positions of the best magPoints to use Vector3 oneWeldPos; Vector3 twoWeldPos;
Transform[] oneWeldPoints = one.GetComponent().SnapPoints;
Transform[] twoWeldPoints = one.GetComponent().SnapPoints;
float snapRange = 0.4f;
float[] closestPair = ClosestPair(oneWeldPoints, twoWeldPoints);
//If the magpoints are close enough together, move the objects together and deal with their rotations
if(closestPair[2] < snapRange){
Debug.Log("SNAPPING");
Transform oneSnap = oneWeldPoints[(int)closestPair[0]];
Transform twoSnap = twoWeldPoints[(int)closestPair[1]];
Vector3 oneDif = one.transform.forward - oneSnap.transform.forward;
one.transform.eulerAngles = -(twoSnap.transform.forward + two.transform.forward) + oneDif;
one.transform.position -= (twoSnap.position - oneSnap.position);
Destroy(oneWeldPoints[(int)closestPair[0]].gameObject);
Destroy(twoWeldPoints[(int)closestPair[1]].gameObject);
}
//Skipped a bit of code I don't think is relavent
foreach(Transform child in one.transform){
if(child != null){
child.parent = weld.transform;
}
}
foreach(Transform child in two.transform){
if(child != null){
child.parent = weld.transform;
}
}