The component that is most directly concerned with parent/child relationships in Unity is the Transform component.
You could add a component to an gameObjects parent by doing something like
transform.parent.gameObject.AddComponent<typeOfComponent>();
To break down this somewhat awkward line:
transform refers to the Transform of the current GameObject
.parent refers to the Transform of the current GameObject’s parent
.gameObject refers to the GameObject that the parent Transform is attached to
Depending on what you are doing, it may not be the best practice to code it exactly like this. One of the guidelines for more understandable object-oriented programming style I might paraphrase as “Objects should take car of their own s**t”, so having a child object mucking about with attaching components to its parent could be confusing if you need to revise or debug this part of your project later.
Pretending, hypothetically, that the parent object is a Giant Orange Head, and assuming it has other code that needs to be attached, it might be better to have a script called GiantOrangeHeadManager, or something like that, and have your child script send a message to the GiantOrangeHeadManager that it is time to attach whatever component is needed. You could get a reference to the parent script using something like:
GiantOrangeHeadManager GOHmgr = gameObject.GetComponentInParent<GiantOrangeHeadManager >();
(you might want to test for nulls in case it doesn’t find what it is looking for)
Then, you would call GOHmgr.AddSomeComponentMethod();
to actually add the component.
Or, if the parent object doesn’t need its own script for any other reason, and if you need to dynamically add components in several parts of your project, you could have a generic ComponentAdder or ComponentManager script that you could add to the parent.
Either way, it is usually safer and cleaner to have any important changes to an object handled by the object itself. When this principle is set aside, I suspect it is far more common to have parent objects doing stuff to child objects than the other way around. Every project is different so your requirements may be different enough that having the child add components directly to its parent makes sense.