Contents:

Understanding the Plants’ Attributes

Each plant within PvZ has some form of unique attribute to make it different; it could simply be a damage boost or the plant could decimate the entire board. Before making a plant, it is important to dictate common attributes between plants and use these to make future Scriptable Objects in Unity for ease of access and creation.

I’ll throw a table of all the plants into Assets, because it’s very large.

Notably, there are some attributes we can see that we could probably throw into a couple of Enumerators inside of Unity.

Let’s Create Some Plants

Now we’ve managed to find similarities between plants, we can create a master Plant script, and then use that as a basis for our five different Plant Types.

All plants have Health which work perfectly as a public variable to throw into the master Plant script.

public GameObject plantModel;
[Space(10)]
public float maxHealth;
[HideInInspector] public float currentHealth;

Some of these variables are namely for the User Interface to eventually interact with, but it gives us a nice base to work from for the other plants.

Offensive Plant Base

Let’s look into the Offensive Plant Type first, after all we like to see things happening on the screen and this works as a good first demo.

Offensive Plants need Damage/Shot and Shot Interval parameters as a base for other scripts to look at when instantiating bullets or other important attributes, but it also needs to have the other parameters we used in the plant base - but how do we use that? Easy, we use the Plantbase instead of MonoBehaviour like so: public class Plant_Offensive : Plant.

Now, since the Offensive Plant needs to spawn a bullet every X seconds, we need to make a Bullet. With the same principles as the Plant base, we can make a Bullet base where other bullets (such as a future ice bullet etc.) can derive from.

[Header("Offensive")]
public Bullet plantBullet;
[Space(10)]
public float damagePerShot;
public float shotInterval;

IEnumerator fireBullet()
{
    while (true)
    {
        //Wait for seconds.
        yield return new WaitForSeconds(shotInterval);
        Debug.Log("Spawning Bullet.");

        //Every X seconds, spawn the bullet.
        Bullet bullet = Instantiate(plantBullet, transform, true);
        bullet.SetData(damagePerShot);
        bullet.transform.parent = transform;
    }
}

Bullet Base

The Bullet base will contain all aspects every bullet will need, such as Speed. Using this base, we can also get the damage the bullet will cause from the Plant it is spawned from.