Unity3d中的多态

k

我需要一些帮助。我不知道这是否可能:

我有2个脚本,interactBase和interactRock脚本。

interactRock脚本扩展了interactBase脚本。

interactRock覆盖函数“ interact()”

因此,我尝试获取对象的引用并调用子级的函数。

但是它似乎起作用。也许你可以帮我吗?

码:

interactBase:

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class interactBase : MonoBehaviour {

    public interactBase(){

    }

    // Use this for initialization
    void Start () {

    }

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

    }

    public void interact(){

    }
}

rockInteract:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class rockInteract : interactBase {
    public bool triggered;

    public rockInteract(){
    }

    // Use this for initialization
    void Start () {
        triggered = false;
    }

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

    }

    public new void interact(){
        triggered = true;
        print ("working");
    }
}

调用脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class triggerScript : MonoBehaviour {
    Animator anim;
    SpriteRenderer sprite;
    public bool triggered;
    public GameObject toTrigger;
    interactBase baseFunc;

    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator> ();
        sprite = GetComponent<SpriteRenderer> ();
        triggered = false;

        baseFunc = toTrigger.GetComponent<interactBase>(); 
        print (baseFunc);
    }

    // Update is called once per frame
    void Update () {
        transform.position += Vector3.zero;
        if (triggered == true) {
            //print (baseFunc.interact ());
            baseFunc.interact ();
            triggered = false;
        }
    }
}

谢谢

乔·泰文

问题是您需要将基本交互定义为

virtual void interact()

和孩子一样

override void interact

通过基类指针调用子交互。使用new并不能做到这一点。

new的真正含义是“ child具有自己的方法,恰好具有相同的名称,这与基类中的完全不同的方法相同。当使用child指针时,应调用此new方法,而在使用base指针时,不应调用此new方法。 ,因为base拥有使用该名称的自己的方法”。虚拟和覆盖表示“子级具有相同方法的不同版本,无论您使用何种类型的此类指针,都将调用该子级”。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章