It’s a difficult question to word clearly so let me explain:
I have a game object that has a Star
component. Star
has a couple of fields in it that are private and should only be readable, not writeable, after initialization. One of these is a StarType
component, which the Star
object can mutate but I want it to be private so nothing else can change it (after initialization). The other is a StarStockpile
; I want this field to be set on initialization and then to be totally immutable.
First, I tried adding a method to Star
called Init(StarStockpile, StarType)
that sets those two fields, which resulted in the following code to create a new star:
StarType generatedType = generator.GenerateStarType();
GameObject newStarObject = new GameObject(generatedType.name);
Star newStar = newStarObject.AddComponent<Star>();
newStar.Init(stockpile, generatedType);
However, this is pretty much the same problem: Star.Init
has to be public and so it can still be messed with after initialization because anything can call it.
So now I’m trying to assign a Star
component to the game object after its been created through a constructor, like so:
StarType generatedType = generator.GenerateStarType();
Star initStar = new Star(stockpile, generatedType);
GameObject newStarObject = new GameObject(generatedType.name);
Star newStar = newStarObject.AddComponent<Star>();
newStar = initStar;
But I don’t think this is working either. For one thing, my compiler is trying to tell me that I’m doing an ‘unnecessary assignment’, which means I’m not assigning the way I think I am.
In summary:
I want to be able to instantiate a GameObject with a Star
component, where that Star
component’s constructor is called to assign private/readonly fields on initialization (or with any other way that initializes immutable fields).