![](/img/trans.png)
[英]What is the best way to dynamically generate 3D objects on a grid in Unity?
[英]What is the best way to encapsulate inherited fields in Unity 2D?
我目前正在设计一个 Unity 游戏,我想确保我正在实施正确的封装。 但是,我被困在这个问题上:
假设我有一个 class Item
,其字段为: private string itemName
。 我还有一个 class Strawberry
,它是Item
的子类。 我想在 class Strawberry
中编写一个返回其 itemName 的方法。
这些脚本是 MonoBehaviour,因此它们不能包含可以在其构造函数中使用base
来解决上述问题的构造函数。
我应该使用什么策略来设置Strawberry
类的名称?
谢谢!
您需要保护您的itemName
字符串。 这意味着它可以被子类访问。
项目基础 class:
using UnityEngine;
public class Item : MonoBehaviour
{
protected string itemName = "itemBase";
}
草莓 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.