Different parameter on Spawn()

Hello there!
Trying complete the challenge I did a different code of Rick and it worked just fine, but I started to wonder if what I did is not, let’s say, “good practice” on coding.
Is there any reason why I should avoid doing with a Int instead of a Attacker?
Here is my code:

public class AttackerSpawner : MonoBehaviour {

    [SerializeField] bool spawn = true;
    [SerializeField] int minRandomTime = 3;
    [SerializeField] int maxRandomTime = 7;
    [SerializeField] Attacker[] enemyArray;
        
	IEnumerator Start ()
    {
        do
        {
            yield return StartCoroutine(SpawnAttacker());
        }
        while (spawn);
	}
	
	private IEnumerator SpawnAttacker()
    {
        yield return new WaitForSeconds(Random.Range(minRandomTime, maxRandomTime));        
        int enemyIndex = Random.Range(0, enemyArray.Length);
        Spawn(enemyIndex);
    }

    private void Spawn(int index)
    {
        Attacker newAttacker = Instantiate(enemyArray[index], new Vector2(transform.position.x, transform.position.y), Quaternion.identity) as Attacker;
        newAttacker.transform.parent = transform;
    }
}

Thanks for your time!

Hi Lucas,

Given your solution works, it’s definitely not wrong to pass on an integer instead of an Attacker.

However, your method is named SpawnAttacker, not GetEnemyIndex. For me, it would make more sense if you did this:

    private IEnumerator SpawnAttacker()
    {
        yield return new WaitForSeconds(Random.Range(minRandomTime, maxRandomTime));        
        int enemyIndex = Random.Range(0, enemyArray.Length);
        Spawn(enemyArray[index]);
    }

    private void Spawn(Attacker attacker)
    {
        Attacker newAttacker = Instantiate(attacker, new Vector2(transform.position.x, transform.position.y), Quaternion.identity) as Attacker;
        newAttacker.transform.parent = transform;
    }

We try to follow the single responsibility principle meaning that each class, each method and each code snippet is supposed to have a specific task. Furthermore, we do not want to create too many dependencies.

In your example, both methods do something with the enemyArray. What if the enemyArray does not contain any Attacker object references? In my example, you could still call the Spawn method and spawn an Attacker if you pass on an Attacker. The Spawn method does not depend on the enemyArray.

Hi Nina

I’m new to coding, but now I get it.
Thanks for your answer and explanation.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms