« 包含标签 override 的文章

example of virtual function in unity3d with C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using UnityEngine;
using System.Collections;
using System;
 
public class car : MonoBehaviour {
    private A a;
    private A b;
    private A c;
    private A d;
    private D e;
    private C f;
 
    void Start () {
        a = new A(); 
        b = new B(); 
        c = new C(); 
        d = new D();
        e = new D();
        f = new C();
 
        a.Func(); // print A
        b.Func(); // print B:A
        c.Func(); // print B:A  
        d.Func(); // print A
        e.Func(); // print D:A
        f.Func(); // print B:A
    }
 
 
    public class A {
    	public virtual void Func() 
        {
            Debug.Log("A");
        }
    }
 
    public class B : A  
    { 
        public override void Func()
        { 
            Debug.Log("B : A");
        }
    }
 
    public class C : B 
    {
 
    }
 
    public class D : A 
    {
        public new void Func()
        {
            Debug.Log("D : A");
        }
    }
 
}