Hi there, just started using Unity today and I’ve hit a wall that I can’t figure out.
I’m adding multiples of a custom MonoBehaviour (GameLayer) class to another custom MonoBehaviour (GameScene) but, when I add them and modify the values I’m just modifying the first Component over and over:
GameLayer gl = this.gameObject.AddComponent<GameLayer>();
gl.name = layerName;
gl.Width = width;
gl.Height = height;
this.Layers *= gl;*
After doing this several times, this.Layers is full of references to the same object.
I’ve even tried:
gl = this.gameObject.AddComponent();
GameLayer[] gameLayers = this.gameObject.GetComponents();
gameLayers*.name = layerName;*
gameLayers*.Width = width;*
gameLayers*.Height = height;*
this.Layers = gameLayers*;*
In-case AddComponent was only returning the first one.
Like I said, this is my first day with Unity, and this is all in editor. I’ve written an editor script to generate my level meshes (this is part of that). So, perhaps I’m doing something wrong because of it being in editor (like daring to touch an object’s material)?
Any help is appreciated.
It's probably just those first few hours of "What the hell is this component thing" that we all suffer when we start with Unity :p
– whydoidoitSadly, I can't use .Last() because it's adding the same reference over and over. Everything in that collection is the same object (the instantiated most recent GetComponent(). I feel like I have a good enough grasp of components (I could be wrong!). I could most likely do this another way, but I'd like these layers to have their own transform and components themselves.
– UbahsRight so let's get to what you are trying to do: A component doesn't have a transform - it shares the one on the GameObject it is attached to. So presumably you'd want to have it on a separate object in that case.
– whydoidoitYou, sir, are a scholar and a gentleman. Changed GameLayer to not being derived from anything. Added a member GameObject and new that up during instantiation of GameLayer. I wish the documentation went a little more into what Components are actually for, when you should use them, etc. Then I won't say something stupid like "I feel like I have a good enough grasp of components..." [The Component-Script Relationship][1] [1]: http://docs.unity3d.com/Documentation/Manual/TheComponent-ScriptRelationship.html
– UbahsIt's really powerful - but really funky when you aren't used to it. Unity is a very opinionated framework.
– whydoidoit