Question by
Shnayzr · Feb 14, 2016 at 03:53 PM ·
gameobjecttransformassign
How can i assign a GameObject to another but only have some of its components?
lets say i have GameObject A with these components: Transform, SpriteRenderer and Animator.
and in script i want to create GameObject B wich equals to A but with only the Transform component.
how can i do that in c#?
Comment
Answer by dan5071 · Feb 14, 2016 at 04:24 PM
Simple enough!
void Start ()
{
// Find our first GameObject A. Use whatever method you want to reference A.
GameObject a = GameObject.Find( "A" );
// Instantiate GameObject B from A. Change position and rotation to whatever you want.
GameObject b = Instantiate( a, Vector3.zero, Quaternion.identity ) as GameObject;
// Optional. Change B's name to 'B' in the editor instead of A(Clone).
b.name = "B";
// Destroy the SpriteRenderer and Animator components.
Destroy( b.GetComponent<SpriteRenderer>() );
Destroy( b.GetComponent<Animator>() );
}
is there a way to destroy every component except Transform?
Sure. Same concept, just a more generalized approach. Please upvote if I helped you out!
void Start ()
{
// Find our first GameObject A. Use whatever method you want to reference A.
GameObject a = GameObject.Find( "A" );
// Instantiate GameObject B from A. Change position & rotation however you want.
GameObject b = Instantiate( a, Vector3.zero, Quaternion.identity ) as GameObject;
// Optional. Change B's name to 'B' in the editor ins$$anonymous$$d of A(Clone).
b.name = "B";
// Store all the components attached to "B" in an array of components.
Component[] components = b.GetComponents( typeof(Component) );
// Iterate through each component in our component array.
foreach( Component c in components )
{
if( c.GetType() != typeof(Transform) )
Destroy( c );
}
}
Your answer
Follow this Question
Related Questions
Auto level an object 0 Answers
Instantiated objects can't convert to GameObjects 0 Answers
Best way to set game object transforms 2 Answers