Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Can you force MonoBehavior scripts automatically include other components if they don't already exist?

I've seen a few places where Unity has the ability to "link" or otherwise require component dependencies that are added (at edit-time) and cannot be removed until the dependent component itself is removed.

Is there a way to use this behavior from custom scripts?

I know that you can create components at runtime using ObjectFactory, but it's expensive and doesn't solve the problem of being able to tweak parameters on the dependency components manually.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Yes - the [RequireComponent(typeof(SomeDependencyComponent))] attribute does exactly this.

For example:

[RequireComponent(typeof(AudioSync))]
public class BehaviorPlayer : MonoBehaviour
{
    private AudioSync audioSync;

    public void Start() {
        audioSync = GetComponent<AudioSync>();
    }
}

This automatically creates an AudioSync component (in this case, a custom script in my project) that is guaranteed to be present at runtime, barring any programmatic removals.

It also shows up as an editor component on the game object that can be manually tweaked:

GameObject editor showing the BehaviorPlayer script automatically adding an AudioSync component

Further, if I try to remove the required AudioSync component, Unity spits out an error:

Unity error message stating "Can't remove AudioSync (Script) because BehaviorPlayer (Script) depends on it"

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda