benArcen

Unity Questions Thread

Recommended Posts

One thing I remember from when I was first learning a language/ecosystem/framework in Python was that it was super useful to find a few big projects, and then read their entire sources, top to bottom, to see everything—from how they're laid out from a birds-eye view, architecture-wise, to nitty-gritty details and tricks and idioms that good Python programmers used to get. stuff. done.

 

I'm pretty far into Unity stuff, but I know there are things I could be doing better (UnityEvents? LINQ? memory-friendliness? making things more tweakable from the editor? animation curves?). Can you guys think of good examples of complete Unity projects that both aren't trivial, and are good examples of clean code and sound engineering, blah blah etc blah?

Share this post


Link to post
Share on other sites

I'm not aware of any projects that have released their source, though you can get into any .NET assembly using .NET Reflector. When I first started learning C# I poured over the source of Bastion, which was quite helpful.

Share this post


Link to post
Share on other sites

Good idea. Was there debugging information? I did that with FEZ awhile back, but all the variable names were stripped out. But I was looking for undiscovered secrets and codes, anyways :)

Share this post


Link to post
Share on other sites

It's still readable, but requires a bit of assumption. They replace variable names with things like num1, num2, etc so you can get a sense of what is going on. If your willing to spring for the paid version of reflector I think you can see the original variable names if I remember correctly.

Share this post


Link to post
Share on other sites

There's also an open-source version of Reflector called ILSpy.

 

It preserves most names -- I think it only generates names for variables declared inside a function, so a lot of codebases are still decently readable.

Share this post


Link to post
Share on other sites

The game I most recently worked on was made in Unity, and my boss mentioned he wanted to release the source of it. I'm not sure if he still plans to, since we'll need to remove all the PS4 related code since most of that is privileged. If he ends up deciding to release it, I'll make sure to drop a note about it here.

Share this post


Link to post
Share on other sites

Update! I ended up implementing object pooling today, and decided to just use this script from UnityPatterns rather than writing it myself since it didn't seem like it'd be very interesting work. Pretty happy with that script, the only issue is you need to put all the prefabs you want pooled into an public array on a singleton component, and I have a LOT of prefabs I need pooled so that list is pretty huge and unwieldy now. Haven't done a huge amount of testing (or even tried it on a phone yet) but in editor it seems like about a 20-30 fps increase.

Share this post


Link to post
Share on other sites

This isn't a question, I'm just excited about having a break-through. I've long understood that having a lot of gameObjects slows things down, but it wasn't until re-reading Chapter 1 of The Nature Of Code today that I understood how to avoid that. The idea is to have one gameObject that has an array of a class, each instance of which is rendered (or makes a sound or whatever) when an update occurs. I don't think I explained it well, but I finaly get it.

Share this post


Link to post
Share on other sites

For 2D games in Unity, I really think it's worth it to code your own collision checking, as opposed to using the built in collider/rigidbody setup normally used (assuming you're not doing any physics simulation). Checking whether 2 rectangles intersect is really easy, and the performance increase can be well worth your time as you can simply do away with many of your unnecessary rigidbodies and colliders.

Best used with object pooling, I suppose.

Share this post


Link to post
Share on other sites

For 2D games in Unity, I really think it's worth it to code your own collision checking, as opposed to using the built in collider/rigidbody setup normally used (assuming you're not doing any physics simulation). Checking whether 2 rectangles intersect is really easy, and the performance increase can be well worth your time as you can simply do away with many of your unnecessary rigidbodies and colliders.

Best used with object pooling, I suppose.

 

Hmm.. I've never tried coding my own box collision before, but you made me curious. (coded in Processing)

 

      boolean x_is_colliding = false;
      boolean y_is_colliding = false;
      
      // Check by x axis
      if (my_x_position > other_x_position) {
        if (((my_x_position - my_width/2) - (other_x_position + other_width/2)) < 0)
          x_is_colliding = true;
      } else if (my_x_position < other_x_position) {
        if (((other_x_position - other_width/2) - (my_x_position + my_width/2)) < 0)
          x_is_colliding = true;
      }
      
      // Check by y axis (only bother if x is colliding already)
      if (x_is_colliding) {
        if (my_y_position > other_y_position) {
          if (((my_y_position - my_height/2) - (other_y_position + other_height/2)) < 0)
            y_is_colliding = true;
          else i--;
        } else if (my_y_position < other_y_position) {
          if (((other_y_position - other_height/2) - (my_y_position + my_height/2)) < 0)
            y_is_colliding = true;
          else i--;
        }
      }
      
      if (x_is_colliding && y_is_colliding)
        return true;
      else
        return false;

 

This seems to work, but is there a better way of doing it that I missed?

 

edit: I realized it would be a bit more efficient if it didn't bother checking for y-axis collision unless x-axis collision had already been detected.

Share this post


Link to post
Share on other sites

That's pretty good, though it could be simplified a bit by making the rectangle class a bit more robust.  Basically you need to check that the bottom of one rectangle with the top of the other, the left of one rectangle with the right of the other and vice versa.

 

public bool Intersects(Rect rectA, Rect rectB)
{
        return rectA.Right >= rectB.Left || rectA.Left <= rectB.Right &&
               rectA.Top >= rectB.Bottom || rectA.Bottom <= rectB.Top;
}

 

You should keep in mind however this only works for Axis Aligned (i.e. not rotated) rectangles.  For a more robust system, you'll then have to consider collisions between each shape type (circle vs. circle, circle vs rectangle, rectangle vs polygon, etc).  For a solution in C# you should check out the FlatRedBall engine.  It uses XNA, though I believe all the collision code is engine agnostic and should work in Unity.  Also it's worth considering scene size and object count, as any collision system must.  If you want to implement your own checks and be efficient about it, you'll likely also want to implement Broad and Narrow Phase collision, A quad tree, collision layers, collision events that you'll want, and other considerations.

Share this post


Link to post
Share on other sites

Ah ok, so it seems like it actually is out of my current skill & knowledge range. Thanks for the FlatRedBall recommendation, though!

Share this post


Link to post
Share on other sites

I wouldn't necessarily say that, after all the only way to bring those things into your comfort zone is to experiment with them.  Collision and physics are pretty robust concepts, particularly in how they work in games.  Like many things in programming it's one of those problems that seems simple at first but gets considerably more complicated when you try to do it practically.  If I were you I'd go ahead and try implementing a basic collision system, say just rectangle-rectangle, then add in different elements and see how the code has to be adjusted as a result.  The good news is there are a number of resources out there with code examples as well as those that go over the theory of how things work so it's actually a good learning project since you won't have to go it all alone.

 

Also a personal note here, when you try to learn something new don't immediately try to think about a game that could use it.  Just try to solve whatever problem you are trying to solve, and then, as hard as it may be, throw it all away.  Programming and game development in general isn't a test of skill or knowledge, it's a test of endurance and problem solving.

Share this post


Link to post
Share on other sites

You're absolutely right, but for the moment it's probably easier for me to rely on bulky things like Unity's collider compenent while I figure out other, more basic and essential programming techniques. Someday I will want to figure out how to program more robust collision though, I'm sure!

Share this post


Link to post
Share on other sites

OK, I feel like an idiot for asking this, but I'm actually dipping my toes back into programming again and I'm stumbling in the exact same place that I always do. I am missing a basic understanding of classes since the majority of my programming experience was from way back before Object Oriented Programming was really a thing.

 

I am making a ship combat/trading/equipment module right now. I have one class attached to the player object that has the total size of the ship and what equipment is on it. I have another class that has the ship's cargo stored in it. The available cargo bay size is equal to total size of the ship minus the space the equipment takes up. I have created a function on the equipment class that calculates this and outputs it. I'd like to be able to call this function from the cargo class. How do I make the two classes in completely different script files talk to each other?

 

Edit: C# by the way.

Share this post


Link to post
Share on other sites

So the entity component pattern that unity uses basically means that every game object in the scene has a list of components (monobehavior classes). You can achieve what you want a few ways, but one short answer is to say this.gameObject.GetComponent<CargoBay>() which would return the CargoBay component on the same game object as your other component.

Share this post


Link to post
Share on other sites

OK, I feel like an idiot for asking this, but I'm actually dipping my toes back into programming again and I'm stumbling in the exact same place that I always do. I am missing a basic understanding of classes since the majority of my programming experience was from way back before Object Oriented Programming was really a thing.

 

I am making a ship combat/trading/equipment module right now. I have one class attached to the player object that has the total size of the ship and what equipment is on it. I have another class that has the ship's cargo stored in it. The available cargo bay size is equal to total size of the ship minus the space the equipment takes up. I have created a function on the equipment class that calculates this and outputs it. I'd like to be able to call this function from the cargo class. How do I make the two classes in completely different script files talk to each other?

 

Edit: C# by the way.

 

I think I was at a similar understanding in recent memory, so I can identify with not quite putting object-orientated programing together.

 

This series somehow managed to explain to me what classes are and how to allow them to get and set properties of each other. I came across it after months of watching Unity's official tutorials. For some reason, this series is what really helped it click with me.

 

-----------------

 

Note: I stop writing when I get overwhelmed with the problem. 

 

Refering to the problem at hand, let me give it a go:

 

So when one script needs to know a property value from another script, what's actually happening is that a specific instance of the script needs a property value from another specific instance of a different script. 

 

I'm going to get away from how you have organized your scripts to give you an example that makes more sense to me. Sorry, I hope it is still helpful.

Think about it like this:

 

We want many ships that can carry many pieces of cargo.

There are certain properties that every ship will need to have. For example, its speed, the size of its cargo bay, its location in space.That list of properties can be the Ship class. The class is where we are storing everything that a ship contains and everything a ship can do (properties and functions).

 

There are certain properties that every piece of cargo needs to have. For example, we want it to have a size, destination, text description, and legal status. That list is going to be our Cargo class. 

 

So let's suppose that our ship needs to know if it can fit a robotic whale into its cargo bay. 

This is where I personally get a bit confused on how to organize things, but I'm going to just go ahead and make an executive decision. I would make a thrid class that we will call the ShipManager class.

 

So the ShipManager class will mostly be a list of all the things that we want to do to the ships. 

In this case, we want to put a robotic whale on the player's ship.

-First the Ship Manager needs to know which ship is the player's ship.

-Then it needs to know which piece of cargo is the robotic whale.

-Then it needs to see if the robotic whale will fit on the player's ship.

 

A simple way for the ShipManager to find the player's ship will be to have all of the instances of the Ship class in a single array. 

*Let me make sure that I explain what an instance is. An instance is a particular object that currently exists in the game which is has the script in question as one of its components. So for instance, if I have 200 ships flying around, that is 200 instances which are all using 1 script.

So we need the ShipManager class to have a Ship array called "ships"

 

Ship[200] ships;
 

 

Assuming that the player's ship is the first instance of the Ship class in the array,  the ShipManager can refer to the player's ship with 

 

ships[0]
 

 

So now the ShipManager needs to know what it's trying to put on that ship.

Let's suppose that the robotic whale is coming from the cargo bay of another ship. 

 

....................

gosh this is getting complex.

 

I'll try to skip ahead....

 

The idea is to have each class have a function that allows other scripts to get each property it needs from this script and a function for each property that another script can set. 

 

So the Ship class would probably need something like:

 

 

Cargo[100] _cargo;
int cargoCount;
int cargoMax;

public Cargo[] GetCargoArray()
{
    return _cargo;
}
 

 

 

that would be called from another script like this:

 

 

givingShip=ships[75];
tempCargoArray= givingShip.GetCargoArray();

 

 

which would return the array of the ship's cargo.

 

I think it would also be a good idea for each ship to have an array for it's current cargo and the ability for that array to be changed by the ShipManager or maybe other ships.

 

 

Cargo[100] _cargo;
int cargoCount;
int cargoMax;

public void SetCargo(Cargo _item)
{
   if(cargoCount<cargoMax)
   {
       _cargo[cargoCount]=_item;
   }
}
 

 

 

which would be called from another ship like this:

 

 

recievingShip=ships[39];
recievingShip.SetCargo(_cargo[18]);
 

 

 

 

This is taking more effort than I thought it would. 

I'll leave this up in case it's useful in its incomplete state.

 

If you have more questions, please ask. Sorry that I got lazy.

Share this post


Link to post
Share on other sites

For what it's worth, I follow object oriented programming but Unity seems to have an extra layer of weird obfuscation that makes it harder.

Share this post


Link to post
Share on other sites

I have a feeling that I'm breaking this into too many small chunks and that's making it more difficult than necessary. Also, the difference between having a class definition and a class instance. Thank you all for the tips. I think I've figured out a couple of places where my mind is missing a step, which will make it a lot easier to fill those gaps using tutorial videos. The frustrating thing is that they have a video specifically on splitting up classes to make them easier to read, but then all the sample projects use one big class anyway.

Share this post


Link to post
Share on other sites

In order to get two classes to talk to one another, the easiest solution is usually to just put a variable of the class whose methods you want to call in the other.  For example:

 


public class Cargo
{
    public int Capacity = 10;
}

public class Ship
{
    public int Size = 100;
    public Cargo CargoComponent = null;

    public int GetAvailableSpace()
    {
        return Size - CargoComponent.Capacity;
    }
}

 

I think what you're getting tripped up on is the difference between classes, components and objects.  I've walked a few people through Unity related stuff and this seems to be a pretty common thing, and assuming that is the issue, here is a quick breakdown.

 

Classes are blueprints for objects:  They tell you what data and functionality an object will have

Components are a type of class: Object in this case means a script object, or rather a bunch of data wrapped up into a single container.

Objects are instantiated versions of classes:  This seems to be where I think you are having some confusion.  Gameobjects (what typically is called a Unity Object) are instantiated versions of the gameobject class.  However, each of the components on the gameobject are also objects (they are C# objects).  A gameobject is simply a special type of object that can hold references to an arbitrary number of components.

 

I included an image in case this doesn't make sense, or I can clarify if all I've managed to do is make this all seem weirder.

 

So a component is a class definition, and when you attach that component to a gameobject an class instance is created.

 

Essentially when you write a class you are creating a class definition.  When you attach a class to a gameobject you are creating a class instance, which is what is actually active in the game.  There are exceptions to that such as static members and functions that don't require a class instance to function, but those are really an entire topic in themselves.

 

 

post-28069-0-02076300-1433887916_thumb.png

Share this post


Link to post
Share on other sites

Hi guys,

 

I'm moving over some of my experiments in Processing over to Unity, and I'm wondering whether there is anything like Processings map() function in unity?

 

The map function is useful for taking a number with a range, and figuring out what its contemporary would be in another range. For example, your value is 0.5, in a range between 0 and 1. The range you want to translate it to is 0 and 2, making the returned result 1. Any ideas?

Share this post


Link to post
Share on other sites

Has anyone had experience with drawing textures onto terrain with code? Any tutorials you can recommend? 

 

Making a randomly generated map is haaarrrd.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now