gameObject.AddComponent(presetComponent) ?? I would like to add a component thats already created.
Lets say we have a Component called "Traits" that has some perimeters.
public class Traits : Monobehaviour {
public string traitName = "someone";
public float height = 6.2;
public float weight = 236;
public Color hairColor = Color.black;
}
Now what I would like to do is create a few of these and then add them to a game object later. To create them lets say I do something like this.
public List<Traits> traitsList = new List<Traits>();
for(int i = 0; i < 10; i ++){
Traits newTrait = new Traits();
newTrait.traitName = "Bob";
newTrait.hairColor = Color.blue;
newTrait.weight = 400;
newTrait.height = 5.2;
}
Now I would like to add them to a game object but I am doing it wrong somewhere.
someNewGameobject.AddComponent<Traits>(savedTrait[i]);
Not a thing, and neither is
someNewGameObject.getComponent<Traits>() = savedTraits[i];
Em I just approaching this wrong? I would like not to do something like.
Traits newTrait = gameObject.AddComponent<Traits>();
// And then have to assign all the elements on its own, that would suck if the properties are a long list.
newTrait.traitName = savedTraits[i].traitName;
newTrait.weight = savedTraits[i].weight;
newTrait.height = savedTraits[i].height;
// and so on.
I may just have to rethink this hole spiel but it seams like there should be a way.
Thanks for checking it out.
Anxo.
I see that you construct a 'Traits' in your for loop but you seem to not bother adding it to your List. I assume this will cause problems.
Also, you called your List traitsList but reference savedTraits. What go on?
Also since Traits is derived from $$anonymous$$onoBehaviour you shouldn't create instances with "new". You should actually get warnings about that in your console. $$anonymous$$onoBehaviours or Components in general can only be created with AddComponent. If you create them with new they become fake null objects since they can't live without a gameobject they are attached to.
Thanx you 2 but this is actually not my code. I wrote this as an example to ask the question, I should have been more thorough. $$anonymous$$y Classes are a lot longer and convoluted so I did not want to turn anyone off by posting that code here.
Answer by sankalp22 · Dec 02, 2015 at 09:14 AM
You can follow solution in this thread. here
Thanks, it turns out to be way too messy, Ins$$anonymous$$d, in my case, I can get away with storing my data in a
List<Dictionary<string,object>> Traits;
ins$$anonymous$$d. Won't work for all but allows me to avoid that reflection mess.