• Unity3D - Discussion
    5,004 replies, posted
[QUOTE=Over-Run;44676106]I was wondering because I need to make sure my code is as nice as possible for my project demonstration. Is coding in Unity object orientated? I'm just confused as you make scripts and place them on things, so I'm not sure if it is OO. I have 4 magic spells in my game, but each spell has its own script. Is this a good way of doing it? Each spell does something different so I'm just not sure on how to make sure I have the best code possible[/QUOTE] I think you're a bit confused on the meaning of OO. OO just means things are encapsulated in "objects". An "object" is an instance of a class. If you use C# in Unity, everything you do MUST be encapsulated in some kind of object (whether it be an enum, an interface, a struct, a class, etc). Basically, OO just means you aren't using "procedural programming", that is you couldn't have a code file with nothing in it but straight code (like you could in, say, Javascript). Code can only be inside functions, which can only be inside classes and structs. Therefore, yes Unity is object-oriented. [B]HOWEVER![/B] OO is not the end of the story for good code! There are other guidelines out there you can follow to produce good solid code. Here's some of my favorites. 1.) [B]The One Responsibility Principle (ORP)[/B] The One Responsibility Principle states that a class should only be responsible for one task. Does the description of the class include "and" anywhere in it? Then you should split that functionality into another class. There's exceptions to this rule of course, but in general try to follow this when possible. It's especially important when working in a component-based environment like Unity. 2.) [B]The Open Closed Principle (OCP)[/B] The Open Closed Principle states that a class should be open for extension, but closed for modification. If I'm using your code, and I want your class to behave differently, I should be able to extend it and change what I need in the subclass. I should NEVER have to actually go and change any of your code in order to change what I want. 3.) [B]The Linkov Substitution Principle (LSP)[/B] The Linkov Substitution Principle states that if a particular behavior is supported in a parent class, then a child class [B]must[/B] support the same behavior (never get rid of or reduce behavior defined in a parent class). 4.) [B]Dependancy Inversion Principle (DIP)[/B] The Dependancy Inversion Principle states that if code in class A depends on class B, you should abstract that dependency as much as possible. The order of abstraction goes like this (most preferred to least preferred): a.) Interfaces b.) Abstract classes c.) Concrete base classes The nice thing about doing this is it frees you to change things about how class B works without worrying as much about the dependency between the two. I would also encourage you to come up with some code formatting guidelines for yourself. This is purely a matter of personal preference and so I won't list my own here, but just make sure that your code always follows a particular structure and pattern, that way it will be much easier to read. Also, use code folding if you're using C# (#region Something, #endregion). They will make your life happy.
I'd like to note that ORP also applies to functions. If you have one function doing the work of two functions, it should probably be two functions. And go read: [url]http://gameprogrammingpatterns.com/[/url]
[QUOTE=Asgard;44676274]I'd like to note that ORP also applies to functions. If you have one function doing the work of two functions, it should probably be two functions. And go read: [url]http://gameprogrammingpatterns.com/[/url][/QUOTE] Ah yeah, that too. I'd like to mention that in a component-based environment like Unity, ORP really should be followed religiously. Each component in your game should be responsible for exactly one task - for example, don't have a monstrous Player component that handles physics and input and equipment and health. Have a Physics component and an Input component and an Equipment component and a Health component. Need an NPC? Get rid of the Input component and substitute for AI component. Need a barrel that explodes when you damage it, but also contains valuable loot? Equipment and Health might do the job nicely. And so on. EDIT: Plus, if you need interactions between these classes, that's when DIP comes into play. Maybe you have an IPhysics, IInput, IInventory, and IDamageable interfaces. So you could then have CharacterPhysics and RigidbodyPhysics, PlayerInput and BotInput, CharacterDamage versus PropDamage, etc. And these classes really don't have to care about each other at all, just that the others implement the proper interface.
[QUOTE=reevezy67;44673672]Collision creates force? You could probably fix it by adding something like this to FixedUpdate. [code]rigidbody.velocity *= 0.95f;[/code][/QUOTE] That didn't do it... I made a video so you can actually see whats going on: [url]https://www.dropbox.com/s/yyzjo1xwfbia83o/Problem.mp4[/url] (I don't know how to embed dropbox videos)
[QUOTE=KillaMaaki;44676264]I think you're a bit confused on the meaning of OO. OO just means things are encapsulated in "objects". An "object" is an instance of a class. If you use C# in Unity, everything you do MUST be encapsulated in some kind of object (whether it be an enum, an interface, a struct, a class, etc). Basically, OO just means you aren't using "procedural programming", that is you couldn't have a code file with nothing in it but straight code (like you could in, say, Javascript). Code can only be inside functions, which can only be inside classes and structs. Therefore, yes Unity is object-oriented. [B]HOWEVER![/B] OO is not the end of the story for good code! There are other guidelines out there you can follow to produce good solid code. Here's some of my favorites. 1.) [B]The One Responsibility Principle (ORP)[/B] The One Responsibility Principle states that a class should only be responsible for one task. Does the description of the class include "and" anywhere in it? Then you should split that functionality into another class. There's exceptions to this rule of course, but in general try to follow this when possible. It's especially important when working in a component-based environment like Unity. 2.) [B]The Open Closed Principle (OCP)[/B] The Open Closed Principle states that a class should be open for extension, but closed for modification. If I'm using your code, and I want your class to behave differently, I should be able to extend it and change what I need in the subclass. I should NEVER have to actually go and change any of your code in order to change what I want. 3.) [B]The Linkov Substitution Principle (LSP)[/B] The Linkov Substitution Principle states that if a particular behavior is supported in a parent class, then a child class [B]must[/B] support the same behavior (never get rid of or reduce behavior defined in a parent class). 4.) [B]Dependancy Inversion Principle (DIP)[/B] The Dependancy Inversion Principle states that if code in class A depends on class B, you should abstract that dependency as much as possible. The order of abstraction goes like this (most preferred to least preferred): a.) Interfaces b.) Abstract classes c.) Concrete base classes The nice thing about doing this is it frees you to change things about how class B works without worrying as much about the dependency between the two. I would also encourage you to come up with some code formatting guidelines for yourself. This is purely a matter of personal preference and so I won't list my own here, but just make sure that your code always follows a particular structure and pattern, that way it will be much easier to read. Also, use code folding if you're using C# (#region Something, #endregion). They will make your life happy.[/QUOTE] Just being pedantic, but it's generally called SRP (single responsibility principle) not ORP.
[QUOTE=KmartSqrl;44677041]Just being pedantic, but it's generally called SRP (single responsibility principle) not ORP.[/QUOTE] I've heard it both ways ;)
[QUOTE=KillaMaaki;44677080]I've heard it both ways ;)[/QUOTE] Definitely still makes sense both ways. I just see SRP more so figured I'd point that out in case anyone wanted to do more reading :)
Is it normal that OnTriggerEnter2D fires constantly as long as a collider is inside, or should it only fire once when it initially enters and I have to do some debugging? Is it maybe because I change the Radius of my CircleCollider during runtime? [code] void FixedUpdate () { (collider2D as CircleCollider2D).radius += growth; } [/code]
[QUOTE=KillaMaaki;44676304]EDIT: Plus, if you need interactions between these classes, that's when DIP comes into play. Maybe you have an IPhysics, IInput, IInventory, and IDamageable interfaces. So you could then have CharacterPhysics and RigidbodyPhysics, PlayerInput and BotInput, CharacterDamage versus PropDamage, etc. And these classes really don't have to care about each other at all, just that the others implement the proper interface.[/QUOTE] What is an interface? And what's the difference between an abstract class and a concrete base class? Could you maybe provide an example? That's how I learn best. Edit: And for my character controllers, would it be a good idea to separate GUI from Input and such? Or is that something that isn't too big a deal in Unity? Edit2: I have a method StringToVector3() in two different scripts/classes. What would be the best way to separate out that method? A static class? What if I want it to work by call Vector3.StringToVector3()? How would I do something like that, or can I not?
[QUOTE=Pelf;44681214]What is an interface? And what's the difference between an abstract class and a concrete base class? Could you maybe provide an example? That's how I learn best. Edit: And for my character controllers, would it be a good idea to separate GUI from Input and such? Or is that something that isn't too big a deal in Unity?[/QUOTE] Yes, ALWAYS separate GUI from everything else. Nothing is too small to worry about in Unity - it's not magic, so things that would be best practice anywhere else are often best practice in Unity, too, for the same reasons. An interface in C# is this: [code] public interface IMyInterface { void MyMethod(); } [/code] Note that the "I" in front of it is optional, it's common practice though. Basically, when a class [I]implements[/I] this interface, it means the class promises to have a public method called MyMethod that follows the exact signature defined in the interface. [code] public class MyTestClass : MonoBehaviour, IMyInterface { public void MyMethod() { // do whatever } } [/code] The nice thing about interfaces is that unlike standard inheritance you can implement multiple interfaces at once (in addition to inheriting from a class, like above where I inherit from MonoBehaviour and then implement the IMyInterface interface) An abstract class is just like a regular class, but you aren't allowed to actually use it. Like so: [code] public abstract class MyAbstractClass { public abstract void SomeMethod(); } [/code] It works just like a base class (I can inherit from MyAbstractClass and override the SomeMethod method), but it doesn't allow me to do this: [code] MyAbstractClass instance = new MyAbstractClass(); // compiler error! [/code] If you notice, there's also the abstract void there. Those work exactly like virtual methods, except I don't have to provide an implementation (since the class is abstract - the compiler knows this class will not actually be used, so the method doesn't need an actual method body) There's probably better resources to explain stuff like this... but hopefully you understand a bit more :) EDIT: Ah, now that's a tricky one. The simple way is to make a utility class and stick a public static function in there which does it. The cooler way is to make a so-called [I]extension method[/I] which adds a new method to the Vector3 class, maybe FromString: [code] public static class Vector3Extensions { public static Vector3 FromString( this Vector3 vector, string stringValue ) { // do whatever } } [/code]
[QUOTE=freakadella;44678265]Is it normal that OnTriggerEnter2D fires constantly as long as a collider is inside, or should it only fire once when it initially enters and I have to do some debugging? Is it maybe because I change the Radius of my CircleCollider during runtime? [code] void FixedUpdate () { (collider2D as CircleCollider2D).radius += growth; } [/code][/QUOTE] Makes sense changing the trigger/collision box size would call the OnXEnter again.
I just started using unity, and I hit a wall with variables. I've got two files, "FPSDisplayer.cs" and "MenuController.cs", now I've made a Options menu in my game, and there's a CheckBox (GUI.Toggle) assigned to a bool named ShowFPS (All of this is scripted in "MenuController.cs". Now I want to use this bool in my other file ("FPSDisplayer.cs"), but how the hell do I do this? I know that using static variables is one option, but it isn't the smartest way of doing it. I've googled it, but I still haven't got it to work.
In your MenuController class you could have [code]public FPSDisplayer fpsDisplayer;[/code] and assign that in the inspector. Then access it by doing [code]fpsDisplayer.ShowFPS = <whatever value>;[/code] [editline]30th April 2014[/editline] [unity]https://dl.dropboxusercontent.com/u/13781308/Unity/Asteroid Game/Asteroid Game.unity3d[/unity] WASD - Move Space - Jump, hold to fly Ctrl - Down X - Kill velocity I made a thing where you can walk around a 4km diameter asteroid. Exaggerated gravity and movement of course. [editline]30th April 2014[/editline] Let me know if the camera/movement gets wonky at all, particularly near the poles (marked by the giant pole going through the asteroid).
[quote]Speed: 10747 m/s Slope: 10 degrees[/quote] I broke it by falling through terrain and then getting ejected by the gavitational singularity. You can't calculate gravitational force using the point mass formula for such an irregular object, it gives you extremely wrong values resulting on exaggerated slopes on a surface with features not orders of magnitude smaller than the object's total size. You probably need a few "gravity emitters" to approximate it, if you can't calculate it correctly.
I'm new to networking, anyone got some tips for a fps multiplayer? How should I network it, should I use default unity networking library? and is there a wiki or some code of networking that is for fps, I have seen how to network to cubes in one main camera, but i need each person to have own camera and hud etc, how does rust do this?
[QUOTE=AnonTakesOver;44692998]I'm new to networking, anyone got some tips for a fps multiplayer? How should I network it, should I use default unity networking library? and is there a wiki or some code of networking that is for fps, I have seen how to network to cubes in one main camera, but i need each person to have own camera and hud etc, how does rust do this?[/QUOTE] You need UDP, and library that works on top of UDP. You need to determine what packets can be lost and what can't be. (For FPS that is) Read all of those tutorials! [url]http://gafferongames.com/networking-for-game-programmers/[/url] [editline]1st May 2014[/editline] [QUOTE=Pelf;44690776]In your MenuController class you could have [code]public FPSDisplayer fpsDisplayer;[/code] and assign that in the inspector. Then access it by doing [code]fpsDisplayer.ShowFPS = <whatever value>;[/code] [editline]30th April 2014[/editline] [unity]https://dl.dropboxusercontent.com/u/13781308/Unity/Asteroid Game/Asteroid Game.unity3d[/unity] WASD - Move Space - Jump, hold to fly Ctrl - Down X - Kill velocity I made a thing where you can walk around a 4km diameter asteroid. Exaggerated gravity and movement of course. [editline]30th April 2014[/editline] Let me know if the camera/movement gets wonky at all, particularly near the poles (marked by the giant pole going through the asteroid).[/QUOTE] I think camera is cool, just that dark areas are too dark and can't see stuff. Also, [IMG]http://i.imgur.com/j43VSCW.png[/IMG]
This whole networking thing is confusing, how would I make it so that the server loads a scene, and the clients connect to it, and use values from the scene, an example would be, say if there is a timer since the scene is loaded from the server, how would I make it so that a client that joins the server, loads the scene and gets that time.
[QUOTE=AnonTakesOver;44709856]This whole networking thing is confusing, how would I make it so that the server loads a scene, and the clients connect to it, and use values from the scene, an example would be, say if there is a timer since the scene is loaded from the server, how would I make it so that a client that joins the server, loads the scene and gets that time.[/QUOTE] In a nutshell.... Client joins server and waits for initial "handshake" data. Server sends "handshake" (basically just a message that tells the client the connection was accepted) in addition to the current level and the timer. Client receives handshake message, parses current level + timer and loads level / sets values / whatever.
When you assign a mesh to a MeshFilter, does it create a new one? I'm seeing some weird stuff coming back in the profiler [img]http://files.facepunch.com/garry/home/2014/May/03/15-51/u33J.png[/img] See the number of meshes.. we only have about 10 meshes.. should it be that high? Does this mean the mesh data is being replicated for every game object that uses it?
[QUOTE=garry;44712487]When you assign a mesh to a MeshFilter, does it create a new one? I'm seeing some weird stuff coming back in the profiler [img]http://files.facepunch.com/garry/home/2014/May/03/15-51/u33J.png[/img] See the number of meshes.. we only have about 10 meshes.. should it be that high? Does this mean the mesh data is being replicated for every game object that uses it?[/QUOTE] Are you assigning to MeshFilter.mesh, or MeshFilter.sharedMesh?
sharedMesh
[QUOTE=garry;44714283]sharedMesh[/QUOTE] Huh. It shouldn't be creating new meshes then. I've seen Unity have lots of extra meshes in the background in a fresh project with no scripts (had something like 40 extra meshes). Could always check if it directly correlates to objects - delete all the objects and see how many meshes Unity reports afterwards perhaps?
How do i change the camera view if a button is pressed while looking at a object?
Can you be a bit more specific? What do you mean by "change the camera view"?
[QUOTE=garry;44712487]When you assign a mesh to a MeshFilter, does it create a new one? I'm seeing some weird stuff coming back in the profiler [img]http://files.facepunch.com/garry/home/2014/May/03/15-51/u33J.png[/img] See the number of meshes.. we only have about 10 meshes.. should it be that high? Does this mean the mesh data is being replicated for every game object that uses it?[/QUOTE] I think the count is the number of meshes multiplied by the number of times it's being used. If you switch the profiler over to detailed mode and take a snapshot, you should be able to breakdown how Unity is adding it all up to that final number. As Maaki said though, even in a fresh project and blank scene, it still reports anywhere between 20-40 meshes by default.
[t]http://i.imgur.com/Ke7Vt1k.png[/t] I've been making a node based noise editor. It currently uses LibNoise for the noise generators and operators.
[QUOTE=garry;44712487]When you assign a mesh to a MeshFilter, does it create a new one? I'm seeing some weird stuff coming back in the profiler [img]http://files.facepunch.com/garry/home/2014/May/03/15-51/u33J.png[/img] See the number of meshes.. we only have about 10 meshes.. should it be that high? Does this mean the mesh data is being replicated for every game object that uses it?[/QUOTE] I found the issue - even though I was using sharedMesh - I was later accessing the bounds via .mesh !
[QUOTE=garry;44720415]I found the issue - even though I was using sharedMesh - I was later accessing the bounds via .mesh ![/QUOTE] Aaaah, that'll do it. IMHO the getter for mesh shouldn't call Instantiate. It's kind of dumb that it does - I'd think it would only do that in the setter. EDIT: I dunno, maybe there's merits to doing it that way I'm not thinking of at the moment.
[QUOTE=Pelf;44715030]Can you be a bit more specific? What do you mean by "change the camera view"?[/QUOTE]Making that another camera main camera for awhile tils you press e again.
[QUOTE=Icejjfish;44727823]Making that another camera main camera for awhile tils you press e again.[/QUOTE] If you have cameraOne and cameraTwo, store them in variables and then just enable/disable them. [code]public Camera cameraOne; public Camera cameraTwo; ... if ( Input.GetKeyDown( KeyCode.E ) ) { cameraOne.enabled = !cameraOne.enabled cameraTwo.enabled = !cameraTwo.enabled }[/code] or something like that
Sorry, you need to Log In to post a reply to this thread.