簡體   English   中英

在孩子 class 中調用父母的行為?

[英]Inovking an action from a parent in a child class?

我正在嘗試創建一種可交互系統,您可以在其中擁有可收集元素和可交互元素,一旦進入對撞機,可收集元素就會簡單地添加到您的庫存中,而可交互元素需要有一些反饋(用戶輸入)才能被添加

這是 BaseInteractable class:

using System;
using UnityEngine;

[RequireComponent(typeof(SphereCollider))]
public abstract class BaseInteractable : MonoBehaviour, IInteractable
{
    public enum Collectiblestate
    {
        Collected,
        NotCollected
    }

    protected Collectiblestate _collectibleState = Collectiblestate.NotCollected;
    public static event Action<IInteractable> OnInteractedItem;

    private void OnTriggerEnter(Collider other) => OnItemInteracted();

    // This this function comes from the interface
    public virtual void OnItemInteracted() => OnInteractedItem?.Invoke(this);
}

這是 StandardCollectible class:

using UnityEngine;

public class StandardCollectible : BaseInteractable
{
    [SerializeField] private GameObject _collectibleImage = default;

    public override void OnItemInteracted()
    {
        base.OnItemInteracted();
        _collectibleState = Collectiblestate.Collected;
        _collectibleImage.SetActive(false);
    }
}

這里是 StandardInteractable class:

using System;
using UnityEngine;

public class StandardInteractable : BaseInteractable
{
    public static event Action OnInteractThresholdReached;

    [SerializeField] private KeyCode _interactKey = KeyCode.L;
    [SerializeField] private GameObject _collectibleImage = default;
    public override void OnItemInteracted()
    {
        //this is a notice for the canvas, to display a UI showing the interaction key
        OnInteractThresholdReached?.Invoke();

        if(Input.GetKeyDown(_interactKey))
        {
            // Here I am trying to call the interact item action
            base.OnInteractedItem?.Invoke(this);

            _collectibleState = Collectiblestate.Collected;
            _collectibleImage.SetActive(false);
        }
    }
}

問題出在 StandardInteractable class 上的這一行:

base.OnInteractedItem?.Invoke(this);

我似乎無法從父 class 調用 Action,而且我並沒有真正找到任何有用的信息,因為我不想為該事件訂閱 StandardInteractable,我想在按下按鈕時調用它.

這真的可能嗎?

在此先感謝您的幫助!

在派生的 class 中調用 class 事件不可能像在 C# 中那樣。有一個常見的解決方法是引發基本 class 事件。

只需在BaseInteractable中創建一個方法並在那里調用事件。 然后你可以從派生的class調用這個方法。

這是官方的 MS 解釋: https://learn.microsoft.com/en-us/do.net/csharp/programming-guide/events/how-to-raise-base-class-events-in-derived -課程

更新(添加代碼示例):BaseInteractable.cs

protected void RaiseOnInteractedItem(StandardInteractable standardInteractable)
{
    OnInteractedItem?.Invoke(this);
}

StandardInteractable.cs

if(Input.GetKeyDown(_interactKey))
{
    // Here I am trying to call the interact item action
    RaiseOnInteractedItem(this);

    _collectibleState = Collectiblestate.Collected;
    _collectibleImage.SetActive(false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM