Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Fattie · May 23, 2012 at 03:53 PM · javascriptprogrammingclasses

Modifying a prototype in UnityScript

Previously titled "Adding functions, variables to Runtime Classes"

It is an everyday basic of OO programming that you can stick more functions in an existing class. Just to be clear, here is how you do it in Objective-C for instance, it's just a category...

http://it.toolbox.com/blogs/macsploitation/extending-classes-in-objectivec-with-categories-27447

I'm afraid I don't know how to do this with UnityScript / Javascript.

Example. Consider say Color ...

file:///Applications/Unity/Unity.app/Contents/Documentation/Documentation/ScriptReference/Color.html

How would you add a new Class variable, or a new Class Function?

Thanks!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by whydoidoit · May 24, 2012 at 11:16 AM

You are not going to be able to add anything to an existing class in UnityScript - which is not Javascript, and most obviously not Javascript when considering things like .prototype etc. UnityScript is a .NET language most like JScript.NET.

Just adding properties and methods to object isn't the .NET way and for a reason, it gets very complicated very quickly. It's also much harder to do that in a precompiled language rather than a runtime one (Javascript/Ruby both are interpreted and support lots of dynamic playing around - Ruby does this elegantly)

As Fattie mentions above, the .NET way of adding methods to an existing class is to use Extension Methods which are a c# technique - you might be able to call them from Javascript afterwards but they'd have to be put in a Plugins folder to be visible to Javascript which is compiled after c#. Extension methods allow you to write a function that appears to be a member of the class but is in fact implemented elsewhere - it is syntactic sugar only, but it looks good and keeps the code clean. There are no such things as Extension Properties by the way.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · May 24, 2012 at 03:15 PM 0
Share

Yes that is totally wrong - that is real Javascript not Unity's flavour.

avatar image whydoidoit · May 24, 2012 at 03:22 PM 0
Share

Edit: See my second answer to this post for the best way of doing this...

If what you are wanting to do is associate extra data with an object which you didn't write, you are best off using a Dictionary and use that as a lookup when you have an instance to find your extra data.

Actually Dictionaries are a pain for this because they make you check the key and create a new item: you could try this code:

 public class Index<T$$anonymous$$, TR> : Dictionary<T$$anonymous$$,TR>  where TR : class, new()
 {
     public new TR this[T$$anonymous$$ index]
     {
         get
         {
             TR val;
             if(!(TryGetValue(index, out val)))
             {
                 base[index] = val = new TR();
             }
             return val;
         }
         set
         {
             base[index] = value;
         }
     }
 }

Which makes a derivation of Dictionary called Index that doesn't have that problem.

Then

 public class $$anonymous$$yExtraInfo
 {
     public int someProperty;
     public string someOtherProperty;
 }

 public static Index<object, $$anonymous$$yExtraInfo> Extra = new Index<object, $$anonymous$$yExtraInfo>();

In your code you can now refer to these other properties

 XXXX.Extra[instanceOfClassYouDidntWrite].someOtherProperty = "cool huh";

Where XXXX is the class you used to define the static

avatar image whydoidoit · May 24, 2012 at 03:25 PM 0
Share

Ugh sorry, that was c# - if you are interested I could knock out a JS version

avatar image whydoidoit · May 25, 2012 at 02:51 PM 0
Share

Yes - I'll post my version that makes sure that it doesn't keep strong references. You are right though, cannot be written in JS but can be used by it.

avatar image
1

Answer by whydoidoit · May 25, 2012 at 04:27 PM

Ok, per @fattie in the comments to my first answer I'm posting a second answer that covers a method of having extended properties on any object that you can't just add them to, probably because they came from somewhere else and you don't have the code.

This technique will work from Javascript and C#, but the code has to be in C# hence I've built it as a plugin unity package you can download from here.

You use it like this (clearly this is an example, I could just modify test!):

 //Javascript
 
 //You can have any number of these type of classes
 class MyExtendedProperties
 {
     //Any number of members
     public var aProperty : String;
 }
 
 //This is a test class for this example
 //try to believe that it's an object that we've
 //got that we can't change the source of
 class test
 {
     //This is just so that there is something there
     public var test: String = "Hello";
 }
 
 function Start () {
     //Create a new instance of test
     var o = new test();
     //Give it an extra property in a new instance of MyExtendedProperties
     Extension.Get.<MyExtendedProperties>(o).aProperty = "World";
     //Read it back
     Debug.Log(Extension.Get.<MyExtendedProperties>(o).aProperty);
     
     //Next time the garbage collector runs our extended properties will be cleaned up
     //as nothing has a reference to o
 }

The C# is probably pretty obvious from that Javascript apart from the fact that the .Get method is an extension method callable in C# like this

   anythingAtAll.Get<MyExtendedProperties>().aProperty = "cool huh";
 



For reference - if we had .NET 4 then there is a built in class to do this.

So the basic idea it to have a dictionary, keyed off the object that contains another class that you can put extra information in. The problem of just doing this straight off is that the fact that the object is the key will keep the object alive forever - read massive memory leaks if this gets used too widely. The answer to that is to use weak references and get a notification when the garbage collector runs to enable you to clean up the extra instances associated with objects that have been killed.

I use Jeff Richter's method of knowing that the Garbage Collector has run (that man is bloody smart) and then clean up the extra classes that have been created.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Where to use Structs and classes? 5 Answers

Question on UnityScript and C# 1 Answer

Does UnityScript (Javascript) support classes/structs? 1 Answer

why doesent my javascript unity code work 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges