GameObject null after SetParent()
So basically I have a Collision. In one of the colliding objects, I save a reference to the other and at the same time, I set its parent to the same collider.
void OnTriggerEnter2D(Collider2D collision){
saveObject = collision.transform.gameObject;
saveObject.SetParent(transform);
}
The second time I enter OnTrigger Enter2D with another object, saveObject is null. If I remove, SetParent(), the object is still the collision-object as expected.
Basically, I want to remove the previous object, before adding the new one.
Can anybody explain why this happens, and how to circumvent it?
Answer by EthanRushbrook2 · Jul 05, 2018 at 10:01 PM
Why do you want to set a parent? Doing this makes sense that it would return you a null gameObject. Either try to use a different method or reassign the gameObjcet in your code.
Well, the basic idea is, that i can move the object around. Once I place it inside another object, I want to move them around together. Imagine a character placed into a vehicle.
What exactly do you mean by, 'use a different method'? Which one? And what do you mean by, reassign the gameObject? If I call SetParent() and then save a reference of the object, it is still null the next collider hits.
thx
By method I mean try a different way of doing it.
Yeah, most of the time, we anyhow end up doing it differently :)
In this case, it was also a better idea for me, to just destroy the original object, and respawn a different, much leaner version of it into the vehicle.
But I am still a bit confused, as to why the reference to a gameObject is lost, if the parent is reset. I would guess it has something to do, with keeping the memory from littering.
Anyhow, thanks for the help!