Search Unity

Cannot Add Script Derived From UnityEngine.Component To A GameObject

Discussion in 'Scripting' started by Manato, Jan 29, 2018.

  1. Manato

    Manato

    Joined:
    Jun 11, 2015
    Posts:
    28
    Hi,
    I tried to attach a script that derives from UnityEngine.Component to a GameObject, but it's not working. The editor says, that I can only attache scripts that derives from UnityEngine.Monobehaviour. Thought, the official document says it should work.

    https://docs.unity3d.com/ScriptReference/Component.html

    Is it a bug or is the documentation wrong?

    Using Version 2017.3
     
  2. whileBreak

    whileBreak

    Joined:
    Aug 28, 2014
    Posts:
    289
    I think MonoBehaviour already inherits from Component, so MonoBehaviour is what you want.
     
  3. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,536
    Well look at the documentation for Component.
    Now look at the documentation for MonoBehaviour.
    AddComponent<>() accepts anything derived from T:<MonoBehaviour> and T:<Component> is clearly derived from T:<Object>. So basically - do what the message says and give it something derived from MonoBehavior.
     
  4. Manato

    Manato

    Joined:
    Jun 11, 2015
    Posts:
    28
    UnityEngine.Component: "Base class for everything attached to GameObjects."
    The only possible way, that I can think of, is to use AddComponent to attach a script to a GameObject.

    I know, I can derive from Monobehaviour, but why is it written like that I can derive from Component and add the script to my Gameobject?
     
  5. whileBreak

    whileBreak

    Joined:
    Aug 28, 2014
    Posts:
    289
    And Behaviour inherits from Component :p


     
  6. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,536
    It literally says right after that

    Derive from MonoBehaviour if you want to attach it to a GameObject. Docs.
     
    whileBreak likes this.