Search Unity

Role of the constuctor

Discussion in 'Scripting' started by Talzor, May 30, 2006.

  1. Talzor

    Talzor

    Joined:
    May 30, 2006
    Posts:
    197
    Hi, can somebody tell me why the following happens:

    I have a class A
    Code (csharp):
    1. public class ClassA : MonoBehaviour {
    2.     protected int i = 1;
    3. }
    and three classes B, C and D which derives from A.
    Code (csharp):
    1. public class ClassB : ClassA {
    2.     public void Print(){
    3.         Debug.Log("B: " + i);
    4.     }
    5.  
    6.     public void Start(){
    7.         Print();
    8.     }
    9. }
    Code (csharp):
    1. public class ClassC : ClassA {
    2.     public ClassC(int j){
    3.     }
    4.    
    5.     public void Print(){
    6.         Debug.Log("C: " + i);
    7.     }
    8.    
    9.     public void Start(){
    10.         Print();
    11.     }
    12. }
    Code (csharp):
    1. public class ClassD : ClassA {
    2.     public ClassD(){}
    3.     public ClassD(int j){
    4.     }
    5.    
    6.     public void Print(){
    7.         Debug.Log("D: " + i);
    8.     }
    9.  
    10.     public void Start(){
    11.         Print();
    12.     }
    13. }

    The output for running this (one game object with B and one with C) is:

    C: 0
    D: 1
    B: 1

    Why hasn't i been initialised in C?
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    You probably need to have a non-zero argument constructor ClassC too.
     
  3. Talzor

    Talzor

    Joined:
    May 30, 2006
    Posts:
    197
    Yes, I know that. My question is why?
     
  4. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    Well, with what value would Unity call a non-zero argument constructor?
     
  5. Talzor

    Talzor

    Joined:
    May 30, 2006
    Posts:
    197
    Ahh, I think I understand now. The unity "side" of the object exists, and it can call Print(), but since I have declared a constructor I no longer get the default one and mono can't figure out how to create the object as there are no zero argument constructor, and hence the null value of i.
     
  6. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203