- Home /
Question by
ahstein · Oct 29, 2020 at 07:11 PM ·
prefabrequirecomponent
Equivalent to RequireComponent attribute for prefab reference?
Is there any way to add a component requirement to a prefab reference that is set in the inspector? Essentially, I want to use the RequireComponent attribute on a GameObject reference rather than on a class.
Something like this:
public class Gun : MonoBehavior
{
[SerializeField][RequireComponent(typeof(Bullet)] GameObject bulletPrefab;
}
Comment
Best Answer
Answer by $$anonymous$$ · Nov 11, 2020 at 03:26 PM
Well, as far as I know, no. But you can validate the prefab and see if you want to add a component onto it, like this:
GameObject prefab = null;
private void OnValidate()
{
if(prefab.GetComponent<RandomClass>() == null)
prefab.AddComponent<RandomClass>();
}
Awesome, this is exactly the kind of alternative I wanted. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613014831im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate issues 1 Answer
how to make prefab clone as a child of prefab clone? 0 Answers
Prefab subtypes - Any methods considered good practice? 1 Answer
How do you instantiate just one prefab? 1 Answer
Audio, play when laser hits object 1 Answer