Classes or scripts as classes

Ok, so as I delve deeper I have a few more questions.
(this is all coming from a traditional c++ programmer)

I see how a script file when added as a compnenet can basically be treated as a class object instantiated into the gameobject.

Im assuming this is the correct way to go about scripting, ie not to actually define classes in a JS way in your scripts??

So if this is the case, you can esentially instance a new object of a class through GameObject.AddComponent .
I can see how you can keep local pointer to these objects with var myobj= GameObject.AddComponent …
But how do you set a script/class/instance as a member within another script/class?

Or do you add them all to a gameobject and use that as the parent? Which is fine, but if i add 2 instances of the same script (via GameObject.AddComponent) how can i distinguish between them when using Component.GetComponent?

thanks in advance

Okay, most GameObjects are elements that can exist in the scene. GameObjects can also be contained within each other, through a parent/child relationship.

However, Components are actually a subclass of GameObject. Components themselves, are not intended to be self-contained objects within the scene heirarchy. Instead, they are meant to be handled inside of a particular GameObject.

MonoBehaviors (scripts attached to GameObjects) are components, and as such, may be embedded in GameObjects just like components.

However, an object may be derived from the GameObject supertype, and will work just fine within the Heriarchy.

When you get down to it, Javascript doesn’t handle dynamic typing like this, but Unity doesn’t HAVE Javascript. Instead, they added to the functionality of “Javascript”, and have called it Unityscript.

It doesn’t matter HOW you design your objects, actually. It really depends on how you want them to work.

For BEHAVIOR, you want to embed a monobehavior script. For a functional type, though, you want to define your own class…

The differences are pretty obvious, and the benefits as well.

Please be more specific here. There are numerous ways to do this, one of which involves a custom class, but it really depends upon how you want to include the member, and what you need to locate.

In most cases, why would you need to?

In this case, I’d suggest you try something like:

GameObject.BroadCastMessage()/SendMessage().

This will allow you to create an event message to the root object of the current heirarchy, which should bubble upward. As long as the function only exists in one Monobehavior, it will be the only one called.

Like I told you last time, you’ll do better with C#, believe me.

Thanks Ter,

I think i have it a little more clearly. Im just used to function based programming rather than behaviour style. So essentially I should treat gameobjects as the superclass template and derive my own from those (since unity is set up to exchange and link between gameobjects much better than individual script objects.

I just find it wierd that gameobjects already have transform etc built in to their archetype…

"However, an object may be derived from the GameObject supertype, and will work just fine within the Heriarchy. "

How would I go about doing this (im assuming it wouldnt have the transform component then either?)

I think i will need to stick fairly close to my function based roots as the project im working on is fairly heavily driven by procedural generation (ie very little in terms of predefined scene objects).

I’ve gtot one more question (again showing my oldskool roots). How can i simulate pointers?
Assuming i developa gameobject that handles/manupulates large data arrays but i want to do it directly on memory held in other gamepbjects. I deally id take a pointer as argumnet to the functions. How would I do the smae in unityscript?

Oh and c#, im not using it atm since ive been hacking apart allthe turorials/examples and they mainly seem to be in JS. BUt it probably would be more compaftable for me in the long run.

thanks again t.

Yes, it’s a hard bridge to gap, but I’ve had extensive experience in Lua, and Ruby, and frankly, hooks and metatable objects made me start thinking in a more dynamic way, so maybe it’s a bit more simple for me.

Set up better? In some ways. In other ways, Unity is better set up to handle scripted behaviors. It’s really an argument of convenience than functionality, though.

Really though, try to avoid doing something because it’s just easier… In some cases, you will be much better served with scripted behavior, and in some situations, you’ll be much better served by derivative heirarchy…

For instance, I recommend making a monster, item, etc. class, and for level-design type scripts, such as scenes, one-use triggers, etc. I recommend using behaviors.

It makes perfect sense when you think about it. System.Object doesn’t have transform built into their archetype, simply because System.Object isn’t meant to be put in the scene.

GameObject is the lowest-category of class that can go into a scene, and thus, is the first object that needs to be defined as a “spacial” object. As such, GameObjects by default, need to be able to locate themselves within a spacial environment, and therefore, need to have a transform member.

In UNITYSCRIPT, (Javascript doesn’t do this by default!), you can subclass from an object using the extends keyword.

class Derp extends GameObject 
{
  var stuff : int
  function DerpDerp()
  {
  }
}

vs. the standard C# variant:

public class Derp : GameObject
{
  public int stuff;

  public void DerpDerp()
  {
  }
}

I think you are looking at this quite backwards. In the case of procedural generation, you are going to actually WANT to use an Object Oriented heirarchy.

At the risk of sounding too rude, it doesn’t sound like you’ve really worked in C++ before. It sounds like you’ve been taught C via a C++ IDE. Frankly, it’s a common thing. Most programming instructors, and the authors of many programming books have made the transformation from FORTRAN, COBOL, Basic, C, etc. and seem to be unable to make the gap to the Object Oriented generation.

Most of my professors in college were like this, they thought they understood object oriented design, but they did not. Frankly, most self-taught programmers these days are far better off than those that the colleges pump out these days, because the old generation of programmers just can’t grasp the new concepts.

http://www.thetruetribe.com/2010/01/understanding-pointers-in-javascript/

An interesting note, is that you can pass functions as pointers, and invoke them easily. It’s a little more elegant than the tried-and-true C/C++/C# /* method… Though this can be quite invonvenient, because like Java, it’s hard to define exactly which variables become pointers, and which variables become unique values…

Indeed. Conversion between unityscript and C# is REALLY simple.

There are only a few places where things get all flubbed up:

@ - Any code following this will become enclosed by [ ] brackets. Any types within the brackets need to be declared as typeof(type)

function stuff() : type - needs to be changed to public/private/protected type stuff().

class sub extends par - needs to be changed to public/private/protected class sub : par

var derp : type - needs to be changed to: type derp

Also, remember that unityscript supports polymorphism, while C# does not support polymorphism, so you need to typecast ((ntype)variable) manually.

Unity makes C# development lightning fast compared to developing an engine from scratch, in my opinion. It takes all the drudge work out, and lets you jump straight to the fun stuff.

Oh, and a quick point… I gave you some bad information (I’ve only been using Unity for about two weeks now, so I’m still learning too!) but there is a way to locate a second script in the same object, if you add multiples. Since you are actually deriving from the MonoBehavior Class by default in UnityScript, you can use the Filename (in this case, the class name), you can use the name of the class to locate the component:

GameObject.GetComponent(ScriptType)

I hope this helps. I still, however, want to point out, that if you have two scripts that are actually keeping hard references to each other, you might want to reconsider your design, because in most cases, an event-oriented framework will serve you better… However, there are cases where this can be very useful. Also, avoid doing GetComponent calls every frame. You want to grab and store the reference in a member during Start() if possible, or inform the script to grab a reference when it’s been added to the GameObject.

Hi Ter…

Thanks for all your feedback, Its been pretty useful in helping me get my head around stuff.

I actually learnt C++ myself (art school graduate!), following on from learning BASIC on ZXSpectrums etc.
So my understanding and use of it is probably not very ‘standardised’.

After your suggestions I looked into using csharp and found it much more comfortable, Ive already ported all the stuff ive done so far into it. I get that behaviour based programming is great for gameobjects like enemy bots, projectiles etc. It makes them so easy to introduce.

The main procedural stuff Im working on is a detailed 2d heightmap/noise library. With csharp Ive managed to get most of this across into a script that i can then add as a component to anything that needs it (2d textures for heightmaps, actual textures, level layout etc). Im much happier with the strict typing and the public/private declarations i can do ( I like to keep track of everything myself!).

Getcomponent is essentially just building a pointer to the component right? But as you suggest its probably better to setup common ‘gets’ as a member variable. (Glad they put in generics so i dont have to get types all the time)

As always the more i work in it the more i see how to make things make sense. I also worked out that you can ‘name’ components after adding them and so return to them individually too.

I did get annoyed with unity meshcollider though. Ive built a large 2d terrain mesh (very quick) but when i send it to the collider to setup the bsp(or whatever its doing) it hangs. Im convinced the colider is doing a proper 3d colision set, but since its a grid terrain all the polys are in strict x,z layout so it would actually be much faster to check only polys in the same grid cell as the player/object.

p.s. is there any ide other than built in unity for csharp (that intergrates?), I really miss my class/function browser.

Thanks again

Tom

I believe that Unity integrates well with Visual Studio.

you can offer the solution of the project
but thats it, you can’t use it for more than the “text editor”

Notepad++ isn’t too bad, I hear. I think there’s some info on the wiki in on external editors, take a look at that. I think there’s an intellisense mod as well out there.

I spent most of my years programming in notepad and writing build scripts, seeing as I was working with no IDE in Java most of the time, if not, working with a GNU C++ compiler. Let’s face it, Unity’s method is nicer only because you don’t have to compile manually. The intellisense might as well not exist, and the syntax highlighting is so sparse it might was well not be there either.

For people that are used to that… Well, have fun. For guys like me, it’s more of a nuissance that the nice features are there at all, since they aren’t worth a damn.

“I actually learnt C++ myself”

Sorry, I wasn’t trying to point out that your understanding was borked, I was pointing out that as you put it, your understanding of C++ was actually decent if you wanted to ignore the “++” bit of the statement. I noted a few points of misunderstanding of Object Oriented frameworks that actually draw the line between C and C++. C++ was needlessly overcomplicated, though, and C# sort of brought it back down to basics. If you were comfortable with C(++), you’ll feel absolutely cushy in C#.

I did want to point something out that you are likely to run into as a massiev C# pitfall, though. When you are overriding a method, learn about the new/override/abstract keywords. You didn’t have to explicitly warn C++ back in the day that you were planning on redefining methods in subclasses, but now you have to.

This is a strange concept, really, because it seems to me that it should be pretty obvious to the compiler what you are trying to do, but for some reason… Yeah… You:“Go through the door.” Compiler:“Are you going to open the door?” You:“No, I’m going to plow through the thing face first.”.

If you are overriding a superclass method, you need to use the new keyword before the function. Don’t ask me why, but C# expects this. Override methods are sort of like abstract methods, but this all seems quite silly to me, so I’m not going to bother explaining those.

As for the mesh colliders, Unity itself contains a terrainCollider. I can only assume that the Unity developers knew exactly what they were doing, and sensibly wrote a collider that would behave as it made sense, just testing heights instead of running the whole gambit of trying to generate a convex hull and yada yada.

You might have to write your own terrain collider, but honestly, this is pretty easy.

As for the component question, I generally don’t bother writing accessors and mutators and defending objects against external intrusion. It might be poor programming practice, but I find it to be an irritating habit of paranoid developers. If your work is going to be modified or used by someone else, I would suggest it, but honestly, if your work is internal, I’d rather avoid the split-millisecond overhead of aliasing a command to setting something to true/false. I only do things like this where it saves me typing in the long run (splitting linear array data into multidimensional coordinates, etc).

And yes, it just grabs a pointer to the component.