2017-12-25 18 views
0

私はいくつかの助けが必要です。私はこれが可能かどうかを知りません:Unity3dの多型

私は2つのスクリプト、interactBaseとinteractRockスクリプトがあります。

interactRockスクリプトはinteractBaseスクリプトを拡張します。

interactRockは、関数が上書きされます「(対話)」

だから私は、オブジェクトの参照を取得し、子の機能を呼び出すためにしてみてください。

しかし、それはうまくいくようです。多分あなたは私を助けることができますか?

コード:

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; 
     } 
    } 
} 

ありがとう

答えて

2

問題は、基本クラスのポインタを通じて呼び出される子相互作用のための

override void interact 

として

virtual void interact() 

と子として相互作用ベースを定義する必要があるということです。新しいものを使ってもそれを達成できません。

newは、基本クラスの全く異なるメソッドと同じ名前の子メソッドを持っています。この新しいメソッドは、子ポインタを使用するときに呼び出す必要がありますが、ベースにはその名前を持つ独自のメソッドがあるので、ベースポインタを使用してください "。バーチャルとオーバーライドは、「子は同じメソッドの異なるバージョンを持ち、それはこのクラスに使用するポインタのタイプに関係なく呼び出すもの」を意味します。

+0

労働者(Y)ありがとう – Maik