Prototype pattern

Tulenber 10 July, 2020 ⸱ Beginner ⸱ 2 min ⸱ 2019.4.2f1 ⸱

We continue the cycle about patterns and talk about the Prototype, not the most popular one in Unity.

Theory

The purpose of the Prototype template is to create new objects by cloning an existing one. Usually, it happens by providing the interface to the cloned object itself. The main problem of this process is that cloning from the outside of the object is difficult due to the non-obvious mechanism of copying dependent objects or the lack of access to internal fields. But if you focus on the name “Prototype," it becomes evident that the use of prefabs to create new objects is nothing more than the use of this template, since Unity provides us with the ability to clone internal fields. =)

More theory can be found in this article or this chapter of Robert Nystrom’s book.

Implementation

The basis of this template in .Net is the ICloneable interface, which consists of a description of one method object Clone ();.

As an example, let’s look at the simplified implementation of a Skeleton inherited from Monster class, which, in turn, is inherited from MonoBehaviour. Now, having one skeleton, we can assemble our army of undead. =)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using UnityEngine;

public class Skeleton : Monster, ICloneable
{
    //...

    // Start is called before the first frame update
    void Start()
    {
        //...
    }

    // Update is called once per frame
    void Update()
    {
        //...
    }

    public object Clone()
    {
        // Here could be more complex logic to copy the skeleton
        return Instantiate(this);
    }
}

Conclusion

It is a tiny article to draw your attention to the relationship between the pattern and one of the main approaches to work with Unity. See you next time! =)



Privacy policyCookie policyTerms of service
Tulenber 2020