
In Level 2, we built the storage vaults (Arrays) and defined the DNA blueprints (Structs). But a factory without motion is just a museum. Today, we install the "Start Button."
In Solidity, we call these Functions. This is the logic that will actually breathe life into our undead army.
🏗️ Step 1: Defining the Spawn Function
In any strategy game, when you click "Train Unit," a command is executed. In our contract, that command is _createZombie.
To create a Zombie, the function needs two inputs: a Name and a DNA code.
function _createZombie(string memory _name, uint _dna) {
// The magic happens here...
}
👁️ Player Vision: Imagine a massive control console in the heart of your fortress. When you input a name and a DNA sequence, the gears start turning.
🧬 Step 2: Recruitment (Pushing Data to the Army)
Creating the data isn't enough; we must store it in our barracks (the zombies array). We use the .push() method to add a new unit to the end of our list.
zombies.push(Zombie(_name, _dna));
This line instantiates a new Zombie from our blueprint and sends him straight to the underground barracks.
🔒 Step 3: Security Clearance (Public vs. Private)
By default, functions in Solidity are public. This is a security risk. If we leave it public, anyone on the Ethereum network could trigger our factory and spawn Zombies into our army.
To keep our factory secure, we set the visibility to private.
Pro-Tip: In Solidity, it is a standard convention to start private function names with an underscore (_).
function _createZombie(string memory _name, uint _dna) private {
zombies.push(Zombie(_name, _dna));
}
👁️ Player Vision: The "Start Button" is now locked inside a secure vault. Only the internal systems of our Citadel can trigger a spawn. No unauthorized entry allowed.
🛠️ The Full Code (Updated)
Our ZombieFactory.sol is now a functional piece of machinery:
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.6.0;
contract ZombieFactory {
uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;
struct Zombie {
string name;
uint dna;
}
Zombie[] public zombies;
function _createZombie(string memory _name, uint _dna) private {
zombies.push(Zombie(_name, _dna));
}
}
🏆 Level 3 Cleared
The factory is now operational. We’ve mastered:
Function Declaration
State Manipulation (Pushing to arrays)
Access Control (Public vs. Private visibility)
The Problem: We shouldn't have to provide DNA manually. In the next level, we will build a Random DNA Generator that turns any string into a 16-digit hexadecimal DNA sequence.
See you at Level 4, Commander. The grid is waiting. ⚔️🔥
Top comments (0)