- Home /
Destroy child Error c#
Hi guys, I'm currently working on a character select screen and have come across a rather annoying error.
Can't destroy Transform component. If you want to destroy the game object please call 'Destroy' on the game object instead. Destroying the transform component is not allowed.
This is the code I have so far:
using UnityEngine; using System.Collections;
public class ChangingRoom : MonoBehaviour {
private int _charModelIndex = 0;
private CharacterAsset ca; private string _charModelName = "P1";
// Use this for initialization void Start () { ca = GameObject.Find("Character Asset Manager").GetComponent(); InstatiateCharacterModel(); }
// Update is called once per frame void Update () {
}
void OnGUI(){ ChangeCharacterMesh(); }
private void ChangeCharacterMesh(){ if(GUI.Button(new Rect(Screen.width/2 - 60, Screen.height -35,120,30),_charModelName)) { _charModelIndex++; InstatiateCharacterModel(); } }
private void InstatiateCharacterModel(){ switch(_charModelIndex){ case 1: _charModelName = "P2"; break; default: _charModelIndex = 0; _charModelName = "P1"; break; }
if(transform.childCount > 0) for(int cnt = 0; cnt < transform.childCount; cnt++) Destroy(transform.GetChild(cnt));
GameObject model = Instantiate(ca.characterMesh[_charModelIndex], transform.position, Quaternion.identity) as GameObject;
model.transform.parent = transform; model.transform.rotation = transform.rotation; } }
Answer by Alter · Aug 02, 2012 at 07:21 AM
never mind I used "Destroy(transform.GetChild(cnt).gameObject);" instead and it now works :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613075047im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Destroying childs and Instantiate [C#] 0 Answers
GetChild(0) returns nonexistent object 1 Answer
Multiple Cars not working 1 Answer
collision on child only returns parent object ? 1 Answer
Delete children of Instantiated object 2 Answers