- Home /
How to set the property of my required component?
I want to specify that my CircleCollider2D is a trigger
[RequireComponent(typeof(CircleCollider2D), ????? )]
or in this case I want my BoxCollider2D to be used by Effector
[RequireComponent(typeof(BoxCollider2D), ????? )]
Answer by SoulRider · Oct 14, 2017 at 01:35 PM
[RequireComponent(typeof(CircleCollider2D))]
public class Foo : MonoBehaviour
{
private CircleCollider2D circleCol2D;
private void Awake()
{
circleCol2D = GetComponent<CircleCollider2D>().isTrigger = true;
}
}
No. I want the property to be triggered the moment I add the script not like this. RequireComponent(Type requiredComponent, Property requiredProperty, Property requiredProperty) something like that.
Unfortunately, you can't do it the way you would like, you need to do it the way shown (or indeed the shorter method by unit_nick which I edited in above).
calling circleCol2D.OnTriggerEnter(collidingCollider)
manually, during awake won't work? (assu$$anonymous$$g one knows what collider to collide with)
which could even be simplified to
GetComponent<CircleCollider2D>().isTrigger = true;
Answer by Bunny83 · Oct 14, 2017 at 07:20 PM
RequireComponent is just a neat editor tool to automatically add a component to a gameobject when this script is attached through the editor. Note that this won't actually work when you add your script though code. It's a pure editor feature. It's not possible to specify initialization values in an attribute like this.
However what you want to use instead is implement the "Reset" method. Reset is only called once when the component is attached to the object or when you right click the component and select "Reset". It's ment exactly for that kind of initialization of your component at edit time.
void Reset()
{
GetComponent<CircleCollider2D>().isTrigger = true;
}
Though it would even be recommended to do the component check directly inside Reset. RequireComponent is not really reliable.
void Reset()
{
var col = GetComponent<CircleCollider2D>();
if (col == null)
col = gameObject.AddComponent<CircleCollider2D>();
col.isTrigger = true;
}
This way you don't need the RequireComponent at all.