简体   繁体   English

在 Unity 2D 中封装继承字段的最佳方法是什么?

[英]What is the best way to encapsulate inherited fields in Unity 2D?

I'm currently designing a Unity game, and I want to ensure I'm implementing proper encapsulation.我目前正在设计一个 Unity 游戏,我想确保我正在实施正确的封装。 However, I'm stuck on this problem:但是,我被困在这个问题上:

Suppose I have a class Item with the field: private string itemName .假设我有一个 class Item ,其字段为: private string itemName I also have a class Strawberry that is a subclass of Item .我还有一个 class Strawberry ,它是Item的子类。 I want to write a method in class Strawberry that returns its itemName.我想在 class Strawberry中编写一个返回其 itemName 的方法。

These scripts are MonoBehaviour, so they cannot contain constructors that would solve the problem above using base in its constructor.这些脚本是 MonoBehaviour,因此它们不能包含可以在其构造函数中使用base来解决上述问题的构造函数。

What strategy should I use to set the Strawberry class' name?我应该使用什么策略来设置Strawberry类的名称?

Thanks!谢谢!

You need to make your itemName string protected.您需要保护您的itemName字符串。 That means it can be accessed by child classes.这意味着它可以被子类访问。

Item base class:项目基础 class:

using UnityEngine;

public class Item : MonoBehaviour
{
    protected string itemName = "itemBase";
}

Strawberry class:草莓 class:

using UnityEngine;

public class Strawberry : Item
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log($"my mane is: {GetItemName()}"); 
    }

    string GetItemName() => this.itemName;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM