Question by
rorybowcott · Sep 19, 2019 at 09:32 AM ·
scripting problemruntimeunexpected
Why does my GameObject destroy itself?
I have a simple seen in which a GameObject ("Child") moves towards another ("Parent"), once it reaches the Parent object, it snaps onto it. Therefore when the Parent object moves so does the Child.
This does work but after a second or so of snapping onto the Parent, the Child GameObject destroys itself and vanishes from the Hierarchy. If I keep the Parent object moving in the scene view the Child will not destroy itself.
Could anyone explain what is going on here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snapper : MonoBehaviour
{
private bool Snapped = false;
private Vector3 offset;
public GameObject snapparent;
public float speed = 1f;
void Update()
{
if (Snapped == true)
{
transform.position = snapparent.transform.position + offset;
}
else if (Snapped == false)
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, snapparent.transform.position, step);
}
}
void OnTriggerEnter(Collider col)
{
if (col.tag == "parentblock")
{
Snapped = true;
snapparent = col.gameObject;
offset = transform.position - snapparent.transform.position;
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612212348im_/https://answers.unity.com/themes/thub/images/avi.jpg)