Search Unity

Overwrite properties in derived classes?

Discussion in 'Scripting' started by Adrian, Apr 5, 2008.

  1. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    I'm trying to override a property in a derived class.

    It looks something like this:
    Code (csharp):
    1. class Base {
    2.     public var foo :String = "bar";
    3. }
    4.  
    5. class Derived extends Base {
    6.     public var foo :String = "barbar";
    7. }
    8.  
    9. --
    10.  
    11. var test = new Derived();
    12. Debug.Log(test.foo);
    This produces an "Ambiguous reference 'foo'" error.

    Is there any way to override properties in derived classes? I tried the same in Boo and got the feeling that it's not possible and one should override getters/setters instead. I would do that but getters/setters are not accessible in the editor.

    Any hints?
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    I was able to get it to work in C# but Boo still refuses any attempt.

    This works in C#:
    Code (csharp):
    1. public class Test {
    2.     public virtual string foo = "bar";
    3.  
    4. }
    5.  
    6. public class Test2 : Test {
    7.     public override string foo = "barbar";
    8.  
    9.     string Test () {
    10.         return foo;
    11.     }
    12. }
    13.  
    14. Test2 t = new Test2();
    15. Debug.Log(t.Test()); <-- prints "barbar"
    The same code in Boo produces no syntax error but the "Ambiguous reference" error mentioned above:

    Code (csharp):
    1. class Test ():
    2.     public virtual foo as string = "bar"
    3.  
    4. class Test2 (Test):
    5.     public override foo as string = "barbar"
    6.  
    7.     def Test() as string:
    8.         return foo
    9.  
    10. t as Test2 = Test2()
    11. Debug.Log(t.Test())
    Any help would be appreciated!
     
  3. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    Oh, but the editor doesn't like the C# example:

    Code (csharp):
    1. public class Test : MonoBehaviour {
    2.    
    3.     public virtual string foo = "bar";
    4. }
    5.  
    6. public class Test2 : Test {
    7.    
    8.     public override string foo = "barbar";
    9. }
    When I try to add the Test2 script to any GameObject, following error gets printed repeatedly to the console:
    "Same name multiple times included:::Base(MonoBehaviour) foo"

    Also, the editor doesn't show a field "foo" with the value "barbar", as it should. It shows two fields "foo", both with the value "bar".

    I also tried shadowing the property with the new keyword but it behaves the same as with virtual/override.

    Argh! It seems like I should scrap this and look for some workaround. I could assign values in the derived classes' Start function but that seems so unelegant to me. Also I could no longer change the class properties in the Unity editor since they would get overwritten.