- Home /
Creating new instances of classes
I have a script on a prefab object, the script contains the following lines:
//This is potentially creating 4 new allocations in memory everytime a new worker is created
public Harvester harvester = new Harvester();
public Builder builder = new Builder();
public Attacker attacker = new Attacker();
public Player player = new Player();
Am I right in saying that everytime a new prefab is Instantiated, it will create 4 new instances of the classes?
Answer by coolraiman · Jan 27, 2016 at 03:10 PM
Yes it will
polymorphism may be a solution in your case
By exemple, all these 4 classes derive from the Test class Then your script instead of having one of each classes, only have one list or array
in your start function you can then allocate what you need
List<Test> tests = new List<Test>();
tests.add(new Builder());;
tests.add(new Player());;
and etc...
or if you have some values to define and know from the start the number of element used, you can use an array instead
Test[] tests = new Test[numberOfThingsInIt];
and there is a lot of advantage to use polymorphism like cleaner code, avoid a lot of duplicated code and etc...
Answer by FortisVenaliter · Jan 27, 2016 at 02:53 PM
Yes, that's how C# works. Those initializers happen after the memory for the containing class is blocked out, but before the constructor is called. See this answer on Stack Overflow for a bit more info.
Your answer
Follow this Question
Related Questions
Is there a quick way to replace an object with a prefab instance? 1 Answer
Build Queue Logic In Turn-based Strategy 1 Answer
Not serializable anymore when also a prefab 0 Answers
How can I modify a variable on an instance of a prefab after I created it? 2 Answers
Prefab instances not renaming when prefab is renamed? 1 Answer