- Home /
transform.DetachChildren() is deactivating my children's scripts after detaching from the parent
I'm using transform.DetachChildren() in the OnDestroy() method to have my children be unaffected by the destruction of the parent game object. The problem I have is: transform.DetachChildren() is deactivating my children's scripts after detaching from the parent. is there a way to have my children that are detached to remain active after detaching them from their parent.
private void OnDestroy()
{
foreach (Transform childT in transform)
{
childT.parent = FindObjectOfType<GameManager>().enemyContainer.transform;
//childT.GetComponent<Health>().currentHealth = 0;
//childT.parent = null;
}
//transform.DetachChildren(); deactivates the scripts
}
Answer by azerty0220pl · Apr 10, 2020 at 08:18 AM
Hello @Treven ! You can enable scripts this way:
childT.GetComponent<ScriptName>().enabled = true;
However it would be better if you investigate a little bit about it. Just by creating two new gameObject and writing the simplest scripts possible. Then make it more complex, more similar to what you have right now, step by step. Test it as many times as you can, so you can see what is causing the problem.
I actually found a solution last night at midnight that seems to work. What seemed to happen was, Ondestroy: the objects being detached were being reset and thus all the scripts deactivated. Getting the children before not after the GameObjects destruction in update allowed me to detach the children with no problems but can't put them in the enemy container I have though (B^{. I also tried the script below with my for each loop but my script could not read the entire code before the game objects destruction thus leaving only one or two children behind. Thanks for the help and reply.
if(GetComponent<Health>().currentHealth <= 0)
{
transform.DetachChildren(); //puts them outside the container
}
Your answer
Follow this Question
Related Questions
Detach children on button press 1 Answer
Add force to child 1 Answer
Children detach not working 1 Answer
How to have child object remain after parent is destroyed? 1 Answer
Instantiate a copy without its children 0 Answers