Question by
newwwbieee · Mar 19, 2017 at 06:55 PM ·
unity 5gameobjectinstantiateendless runnermissingreferenceexception
How to destroy only the collided instance of prefab and not the original one?
I have a cube prefab which i use to instantiate more and more such cubes then later i want to destroy the original cube. Here's the script:
public void drawBlock()
{
tempRand = (int)Random.Range(0, 2);
Debug.Log("Random Value=" + tempRand);
if (tempRand == 1)
{
nextBlockPosition = Vector3.forward;
}
else
{
nextBlockPosition = Vector3.right;
}
GameObject blk = (GameObject)Instantiate(nextBlock, rb.position + nextBlockPosition, Quaternion.identity);
rb = blk.GetComponent<Rigidbody>();
rb.useGravity = false;
rb.AddRelativeForce(-roadSpeed, 0, -roadSpeed, ForceMode.Impulse);
}
All the cubes have tag of Road. This is what the Collider does(the one which is reponsible for destroying the cubes)
void OnTriggerEnter(Collider col)
{
if (col.CompareTag("Road"))
{
Debug.Log("Destroyer Collided with:" + col.name);
Destroy(col.gameObject);
Debug.Log(col.name + "was destroyed!");
}
}
The problem is that after one of the block gets destroyed, unity starts to give the error that im trying to ref the destroyed object wchich shudn't be the case because i just clone the original cube some of them are still in the scene when the first one gets destroyed. What am I doing wrong here?
Comment