I'm currently designing a Unity game, and I want to ensure I'm implementing proper encapsulation. However, I'm stuck on this problem:
Suppose I have a class Item
with the field: private string itemName
. I also have a class Strawberry
that is a subclass of Item
. I want to write a method in class Strawberry
that returns its itemName.
These scripts are MonoBehaviour, so they cannot contain constructors that would solve the problem above using base
in its constructor.
What strategy should I use to set the Strawberry
class' name?
Thanks!
You need to make your itemName
string protected. That means it can be accessed by child classes.
Item base class:
using UnityEngine;
public class Item : MonoBehaviour
{
protected string itemName = "itemBase";
}
Strawberry 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.