Good Afternoon, I am trying to change the transform to a rect transform on bool true and then back to a transform on false. I can convert a transform to rect transform but not back to a transform on false stating that a transform already exists and will not let me destroy it.
Warning:
Can't add component 'Transform' to
Sample because such a component is already added to the game object!
Script:
using UnityEngine;
using System.Collections;
public class Sample : MonoBehaviour {
public bool testing;
void Update(){
if(testing == true && GetComponent<RectTransform>() == null){
gameObject.AddComponent<RectTransform>();
}
else {
gameObject.AddComponent<Transform>();
}
}
}
However, you can convert a Transform to a RectTransform because it’s basically upgrading the class but revert it it’s seem more complicated. If you really need to do that I think the only way is to destroy your object and reinstantiate it.
What you’re accidentally trying to do is add a new transform to your game object. You’re basically telling it to be in two places at once. This is happening because these new transforms are never removed.
To fix this, simply remove your rect transform component and it will return to normal!
Try the following
using UnityEngine;
using System.Collections;
public class Sample : MonoBehaviour {
public bool testing;
void Update()
{
if(testing == true && GetComponent<RectTransform>() == null)
{
gameObject.AddComponent<RectTransform>();
}
else
{
Destroy ( GetComponent<RectTransform>());
}
}
}