2017-12-25 25 views
0

도움이 필요합니다. 나는이 스크립트는 interactBase과 interactRock 스크립트를Unity3d의 다형성

이 가능하면 저는 잘 모릅니다.

interactRock 스크립트는 interactBase 스크립트를 확장합니다.

interactRock 함수 덮어 쓰기 "상호 작용()"를

그래서 내가 개체의 참조를 얻고 아이의 함수를 호출하려고합니다.

하지만 dosent가 작동하는 것 같다. 아마 내가 도와 줄 수 있니?

코드 :

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

당신에게

감사 6,

답변

2

문제는 당신이 기본 클래스 포인터를 통해 호출 할

override void interact 

아이의 상호 작용에 대한

virtual void interact() 

와 아이

으로 기본 상호 작용을 정의 할 필요가 있다는 것입니다. 새 것을 사용하는 것은 그렇게하지 못합니다.

new는 "기본 클래스의 완전히 다른 메소드와 동일한 이름을 가진 자체 메소드가 있습니다.이 새 메소드는 하위 포인터를 사용할 때 호출해야하지만 base는 그 이름을 가진 자체 메소드를 가지고 있기 때문에 기본 포인터를 사용하십시오 ". 가상 및 재정의는 "자식이 같은 메서드의 다른 버전을 가지고 있으며이 클래스에 사용하는 포인터의 유형에 관계없이 호출 할 수 있습니다."를 의미합니다.

+0

근무한 (Y) 감사합니다. – Maik