- Home /
Add two components of the same type using RequireComponent attribute
Hi, I've been wondering whether is it possible to add two components of the same type in my game object when I add my script to it. I would like to add two edge colliders 2D to my gameObject when I assign my script to this same gameObject. Something like this:
[RequireComponent(typeof(EdgeCollider2D))]
[RequireComponent(typeof(EdgeCollider2D))]
public class Foo
{
...
}
I know there is a way of adding these two components via script by using AddComponent, but how about adding at the moment I assign my script?
Could you explain why you want to have twice the same component? It makes more sense to have two child game objects and each gets the component.
Yes, this way would perfectly work as well. It is actually just a matter of not having two additional child gameObjects in the scene just to hold a single component each, and for curiosity's sake also, nothing else =)
Answer by Xarbrough · Aug 22, 2017 at 08:46 PM
You could use the Reset() method from MonoBehaviour. It gets called the first time the script is added to a GameObject and whenever the user selects the 'Reset' option from the context menu.
void Reset()
{
int numColliders = GetComponents<EdgeCollider2D>().Length;
for (int i = 0; i < 2 - numColliders; i++)
gameObject.AddComponent<EdgeCollider2D>();
}
Awesome! I did not know this could be possible. Thanks for the help @Xarbrough !!
Your answer
Follow this Question
Related Questions
Only one component of type on a Gameobject at a time 2 Answers
RequireComponent at variable level? 1 Answer
Editor: Is it possible to move a component of a Prefab Gameobject Child to it's parent?? 1 Answer
How can i remove two scripts from a GameObject that depend on eachother? 0 Answers
Execute Code When Component Added 6 Answers