0
\$\begingroup\$

I want to have a custom component which will have a drop down. I want this to be applied to ever GameObject in the project, which means every GameObject in the hierarchy and every GameObject prefab. Something like a transform component. It should not be removable, and it should be added by default when creating new GameObjects.

In the drop down, I will select a few options, and I want to store those values in an array on that custom forced component for that GameObject.

So if I have 2 new GameObjects in scene named XYZ and ABC, and the component is PQR, I should be able to do this-

ABC.GetComponent<PQR>().someArrayVar = whatever;
XYZ.GetComponent<PQR>().someArrayVar = anotherWhatever;

Anyone know how to do this? Any help appreciated. Thanks in advance :)

\$\endgroup\$
  • 1
    \$\begingroup\$ I don't think you can. You can make components be required for scripts (i.e. the script requires a RigidBody, for example) but I don't think you can make every gameobject automatically come with a custom component. \$\endgroup\$ – Draco18s Sep 29 '16 at 19:44
  • \$\begingroup\$ I think you'd have to create prefabs for each base GO type, then just use those to ensure they have the component. \$\endgroup\$ – Jesse Williams Sep 29 '16 at 20:20
1
\$\begingroup\$

This is not possible because you are not allowed to derive from the GameObject class. The closest thing that I can think of would be to write an extension method for gameObject that both attaches your custom component to the gameObject, as well as updating your array.

public static class Helper {

    public static void ModScriptArray(this GameObject gameObject, Data arrData)
    {
        PQR script = gameObject.GetComponent<PQR>();
        if (script == null)
            script = gameObject.AddComponent<PQR>();

        script.someArrayVar = arrData;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.