- Home /
Convert 3D object into 2D object via script
Hello,
I am trying to create a capsule at run time in my script that will shoot off of my player. However all of my players are 2D sprites, and the capsule is a 3D object. When I remove the 3D components in the script it works fine, but adding the 2D components wont work. I tried googling the issue but I could not find what was wrong with my script. I have tried adding 2D components onto a 3D object via the inspector in unity and that works. I am not sure what the issue is.
Thanks for any help in advanced!
GameObject capsule = GameObject.CreatePrimitive(PrimitiveType.Capsule);
capsule.transform.localScale = new Vector3 (.1f, .1f, .1f); // need to make or bullet not gigantic
if(tag % 2 == 0)
{
Blue = GameObject.FindWithTag (tag.ToString ());
capsule.transform.position = Blue.transform.position;
}
else
{
Red = GameObject.FindWithTag (tag.ToString ());
capsule.transform.position = Red.transform.position;
}
Vector2 movement = new Vector2 (-1, 0);
//need to convert capsule into a 2d object so that it will interact with the rest of the game
//we need to convert the capsule to a 2d object so that it will interact with the rest of our game
//UnityEngine.Object.Destroy(capsule.GetComponent<Rigidbody>());
//UnityEngine.Object.Destroy(capsule.GetComponent<CapsuleCollider>());
//capsule.AddComponent<Rigidbody2D>();
//capsule.AddComponent<BoxCollider2D>();
//capsule.rigidbody2D.velocity = movement * speed;
}
Answer by robertbu · May 07, 2014 at 06:55 AM
This looks like a Unity bug to me. The capsule you create using CreatePrimitive() does not have a CapsuleCollider nor a Rigidbody. Yet when I try to add a BoxCollider2D, I get the error:
Can't add component 'BoxCollider2D' to Capsule because it conflicts with the existing 'CapsuleCollider' derived component! UnityEngine.GameObject:AddComponent() Bug25b:Start() (at Assets/_Project/Scripts/Bug25b.cs:27)
When posting questions, the OP (original poster) often asserts that he believes his problems are due to bugs in Unity. Of all the 1000's of questions I've worked on, this is the first time I believe it to be true (and you missed your chance to correctly assert that it's all Unity's fault ;).
A workaround is to crate a prefab. Start with a Capsule game object, delete the collider, Add your Rigidbody2D and BoxCollider2D, make it a prefab, then use Instantiate() to create it at runtime.
I thought it was a bug but did not want to say so because i'm still new to unity. Thanks for the help!