- Home /
add class or script to child gameObjects
Hello all,
I am attempting to make a new object of a class, assigning values to class variables then attaching that object to a gameObject via a editor button press. I'm currently calling the following code when a button is pressed in the editor:
class nodeList{
public float distance;
public nodeList(float x){
distance = x;
} }
foreach(Transform child in transform){
nodeList temp = new nodeList(dist);
child.gameObject.AddComponent<temp>(); }
this throws an error: 'temp' could not be found. Are you missing a directive or assembly reference?
I also tried creating a new empty script called "nodeList" using: child.gameObject.AddComponent("nodeList")
which throws klass != SCRIPTING_NULL
I also tried child.gameObject.AddComponent(nodeList) as Component;
which throws Only assignment, call, increment, decrement and new object expressions can be used as a statement.
Can anyone tell me what I am doing wrong?
you cannot loop in transform directly, you need to do as below
for(int i=0; i<transform.childCount;i++)
{
transform.GetChild[i].gameObject.AddComponent<proxy>();
}
I don't think the foreach loop is at fault. I can perform other logic on the children gameObjects perfectly fine. I'll give it a shot though.
Nope. Get the same error, 'scriptname' could not be found. Are you missing a directive or assembly reference?
, also your code should be transform.GetChild(i)
as it is a function call.
Answer by tanoshimi · Nov 17, 2014 at 07:24 AM
You can't attach arbitrary classes such as your nodeList to gameobjects. To assign a component to a gameobject, the class must derive from Monobehaviour.
I see. Why would attacing a new script that drives from $$anonymous$$onoBehaviour throw and error and fail? child.gameObject.AddComponent("nodeList") which throws klass != SCRIPTING_NULL
where nodeList is a new $$anonymous$$onoBehaviour script.