# Question
Title: How shader program still works even after detaching shader object?
In the following process of shader creation, shader object is detached after linking program (glLinkProgram), how does the shader program still works after detaching and deleting shader objects?

glCreateShader -\> glShaderSource -\> glCompileShader -\> glCreateProgram -\> glAttachShader -\> glLinkProgram -\> glDetachShader -\> glDeleteShader -\> Use shader.

# Answer
> 2 votes
Documentation.

glAttachShader: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glAttachShader.xhtml

> Shaders that are to be linked together in a program object must first be attached to that program object. glAttachShader attaches the shader object specified by shader to the program object specified by program. This indicates that shader will be included in link operations that will be performed on program.

glLinkProgram: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLinkProgram.xhtml

> After the link operation, applications are free to modify attached shader objects, compile attached shader objects, detach shader objects, delete shader objects, and attach additional shader objects. None of these operations affects the information log or the program that is part of the program object.

From this we can infer that **the sole purpose of attaching a shader is for linking, and once linking is completed whether or not a shader is attached has no relevance**.

So you attach one or more shaders, you link the program, the GLSL compiler takes the attached shaders and copies them off to the final linked program object, following which the shaders need no longer exist.

It may help to understand that OpenGL is quite a high-level abstraction and that many of it's constructs don't (or no longer) reflect how the underlying hardware actually works. This is particularly true of the GLSL interfaces, where it can be argued that they were never a good match for hardware in the first place. No other API has the concept of a linked program object that holds it's own state.

---
Tags: opengl, shaders, glsl, graphics-programming
---


title: Image-Button coordinates are busted

text:
# Question
Title: Image-Button coordinates are busted
I have an image-button and I set its position in `create` in this way:

```
imageButton.setPosition(orthographicCamera.position.x+150,150);

```

The problem is that the position always changes, despite I set it in `create`. Also if I change device, I notice that the coordinates are busted, wrong, instead other views are right.

If I write `setPosition`in `render`, the image-button is faster than the camera, it gets away from the screen, but for other views, this doesn't happen because they follow the camera. Why?

# Answer
There are several possible solutions to this.

---

Try using stage coordinates instead like so: `button.setPosition(150, 150)`. Stage always start at `(0, 0)` bottom left corner.

---

Use 2 separate cameras for your UI and your game.

```
OrthographicCamera gameCam = ...;
OrthographicCamera stageCam = ...;
Viewport viewport = new FitViewport(1280, 720, stageCam); //Constant viewport size
Stage stage = new Stage(viewport);

```

Then use `gameCam` for all of your game related stuff and use `stageCam` for your UI. I use a `FitViewport` here for our stage's viewport since it preserves aspect ratio. Makse sure to read up on Viewports to more clearly understand what viewport fits your need.
> 2 votes

---
Tags: libgdx
---


# Question
Title: Outline shader in SFML/GLSL does not work
I have a problem with SFML. This code does not work:

```
uniform sampler2D texture;

varying vec2 v_texCoords;

float offset = 1.0/32;

void main()
{
v_texCoords = gl_TexCoord[0].xy
  vec4 col = texture2D(texture, v_texCoords);

  if (col.a == 1)
    gl_FragColor = col;
  else {
    float au = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y -offset )).a;
    float ad = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y + offset)).a;
    float al = texture2D(texture, vec2(v_texCoords.x -offset, v_texCoords.y)).a;
    float ar = texture2D(texture, vec2(v_texCoords.x + offset, v_texCoords.y)).a;

    if (au.a != 1 || ad.a != 1 || al.a != 1 || ar.a != 1)
      gl_FragColor = vec4(0.0, 0.0, 0.0, 1);
    else
      gl_FragColor = col;
  }
}

```

How can I make my outline shader work in SFML?

# Answer
> 1 votes
I've tried to make the shader you asked about work; here is a version that I managed to make work:

```
#version 120
uniform sampler2D texture;

float offset = 1.0/32;

void main()
{
  vec2 v_texCoords = gl_TexCoord[0].xy;
  vec4 col = texture2D(texture, v_texCoords);

  if (col.a == 1)
    gl_FragColor = col;
  else {
    float au = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y - offset)).a;
    float ad = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y + offset)).a;
    float al = texture2D(texture, vec2(v_texCoords.x - offset, v_texCoords.y)).a;
    float ar = texture2D(texture, vec2(v_texCoords.x + offset, v_texCoords.y)).a;

    if (au == 1.0 || ad == 1.0 || al == 1.0 || ar == 1.0)
      gl_FragColor = vec4(0.0, 0.0, 0.0, 1);
    else
      gl_FragColor = col;
  }
}

```

---

Now, I don't think that's exclusively the issue at hand, so I'll try to help you with some other aspects of debugging, or at least, how I came up with this code.

# How to find assets.

There are several ways to make sure you find the assets of your project.

* The most simple way is to *hardcode* the path to your assets folder and use it as a base path. That's not clean, but it gets the job done when developing.
* You can move the assets folder in your Debug/Release folder. That's not clean, but it gets the job done when developing.
* In the project properties, you can change the *Debugging \> Working directory* to a folder that you know your files will be in.
* In the project properties, you can change the *Linker \> General \> Output File* to specify a location in your assets folder.
* You can pass the path of assets folder as a command-line argument and use `argc`/`argv` in the `int main()` method, with setting the project property *Debugging \> Command Arguments* to the appropriate path.

*Being able to access your assets is the first step, and really, you should not try to debug your shader or add new features before this has been taken out of the way.*

# How to debug your shader code.

We'll start off by assuming that you have a program that can load your graphics and both of your shaders (the vertex and the fragment) <sup>(there is a complete example at the end of this answer)</sup>. And since you did not provide a vertex shader, let's assume that you used the one provided as a minimal vertex shader on SFML's website.

```
void main()
{
    // transform the vertex position
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

    // transform the texture coordinates
    gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;

    // forward the vertex color
    gl_FrontColor = gl_Color;
}

```

Looking at the console when executing the program, we get these errors:

```
Failed to compile fragment shader:
WARNING: 0:2: '' :  #version directive missing
WARNING: 0:5: 'assign' : implicit type conversion allowed from GLSL 1.20
ERROR: 0:10: 'assign' : l-value required "v_texCoords" (cannot modify a varying)
ERROR: 0:11: 'vec4' : syntax error syntax error

Error: Could not load shaders

```

To fix the warnings, we'll add `#version 120` at the top of the shader files. To fix the second warning, we'll remove the `varying vec2 v_texCoords;` that is in the fragment shader and use the 'built-in' `gl_TexCoord` in the code instead: `vec2 v_texCoords = gl_TexCoord[0].xy;`.

Trying to run the program will give us some new errors:

```
Failed to compile fragment shader:
ERROR: 0:22: 'a' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:22: 'a' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:22: 'a' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:22: 'a' : field selection requires structure, vector, or matrix on left hand side

```

Here it's because we're using a `float` like it were a `vec4`. Notepad++ is not as nice as Visual Studio to edit code :P (no intelli-sense). Changing `if (au.a != 1 || ad.a != 1 || al.a != 1 || ar.a != 1)` to `if (au != 1 || ad != 1 || al != 1 || ar != 1)`, we get more errors, but not as messages. Now the alpha part is all black. What's wrong with the code?

The condition that we have means that any neighbour texel that is transparent will have 'this' texel coloured black. That's not right; let's change `if (au != 1 || ad != 1 || al != 1 || ar != 1)` to `if (au == 1.0 || ad == 1.0 || al == 1.0 || ar == 1.0)`. Build, run, and we get what we expect!

The last small step is to make our shader work with any size of texture by allowing a broader variety of texture size: instead of hardcoding the size of the sprite in the shader, let's use an external parameter: replace `float offset = 1.0/32;` with `uniform float textureOffset;`, and all the variables in the code.

---

The end result to have a border around the sprite (a stroke, an outline), can look like this:

The **main.cpp**:

```
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>

int
main( int argc, char** argv )
{

  std::string assetsFolderPath = "C:\\Users\\alex\\Desktop\\test140614\\assets\\";
  std::string backgroundPath = assetsFolderPath + "maxresdefault.jpg";
  std::string gameSpritePath = assetsFolderPath + "latest.png";
  std::string shaderVert = assetsFolderPath + "main.vert";
  std::string shaderFrag = assetsFolderPath + "main.frag";

  sf::RenderWindow window( sf::VideoMode( 1024, 622 ), "Game", sf::Style::Default );

  sf::Texture background;
  sf::Sprite backgroundImage;

  if ( !background.loadFromFile( backgroundPath ) )
    std::cout << "Error: Could not load background image" << std::endl;

  backgroundImage.setTexture( background );

  sf::Texture gameSprite;
  sf::Sprite gameSpriteImage;
  if ( !gameSprite.loadFromFile( gameSpritePath ) )
    std::cout << "Can't find the image" << std::endl;
  gameSpriteImage.setTexture( gameSprite );
  gameSpriteImage.setPosition( 50.0f, 500.0f );

  sf::Shader shader;
  if ( !shader.loadFromFile( shaderVert, shaderFrag ) )
    std::cout << "Error: Could not load shaders" << std::endl;

  shader.setUniform( "textureOffset", 1.0f / static_cast<float>( gameSprite.getSize().x ) );
  shader.setUniform( "texture", sf::Shader::CurrentTexture );

  int xOffset = 0;
  bool isXoffsetGoingUp = true;
  while ( window.isOpen() )
  {

    sf::Event Event;
    while ( window.pollEvent( Event ) )
    {
      switch ( Event.type )
      {
      case sf::Event::Closed:
        window.close();
        break;
      }
    }

    if ( isXoffsetGoingUp )
    {
      xOffset++;
      if ( xOffset > 500 )
        isXoffsetGoingUp = false;
    }
    else
    {
      xOffset--;
      if ( xOffset <= 0 )
        isXoffsetGoingUp = true;
    }

    gameSpriteImage.setPosition( xOffset, 500.0f );

    window.clear();
    window.draw( backgroundImage );
    window.draw( gameSpriteImage, &shader );
    window.display();
    sf::sleep( sf::microseconds(1000000/60) );
  }

  return 0;
}

```

**main.vert**: this is the exact same as the one posted above.

**main.frag**:

```
#version 120
uniform sampler2D texture;

uniform float textureOffset;

void main()
{
  vec2 v_texCoords = gl_TexCoord[0].xy;
  vec4 col = texture2D(texture, v_texCoords);

  if (col.a == 1)
    gl_FragColor = col;
  else {
    float au = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y - textureOffset)).a;
    float ad = texture2D(texture, vec2(v_texCoords.x , v_texCoords.y + textureOffset)).a;
    float al = texture2D(texture, vec2(v_texCoords.x - textureOffset, v_texCoords.y)).a;
    float ar = texture2D(texture, vec2(v_texCoords.x + textureOffset, v_texCoords.y)).a;

    if (au == 1.0 || ad == 1.0 || al == 1.0 || ar == 1.0)
      gl_FragColor = vec4(0.0, 0.0, 0.0, 1);
    else
      gl_FragColor = col;
  }
}

```

---
Tags: 2d, shaders, glsl, sfml, outline
---


# Question
Title: How can I change the parents rotation so the childs rotation is looking at a specific direction
I have a child object which is always having different positions and rotations (thats my VR Headsets Eye-Gameobject) I cannot modify the position and rotation of that.

I want to set my view to a certain "startposition" and "startrotation" so the player always has the same view at the start of the game.

The childs local position is always set to some values. So I cannot unparent it. If I unparent it, I change his position.

now..

It works with the position.

```
Parent.transform.position =  2 * ParentStartPostion - Eye.localPosition;

```

^ This line of code here sets my parent object so that my Gameobject: "eye-camera" is where i want it to be.

For the rotation part, i would do following:

```
Eye.parent = null; //unparent the eye to the world
Parent.transform.position = Eye.position; //set my Parent to the same position as Eye
Eye.parent = transform; //parent it back. Local Eye should be 0.0.0 now.
Parent.transform.rotation = Quaternion.LookRotation(StartForward, StartUp); // i can rotate the at the direction I want it.

```

But after I unparent my Eye the position of the local(which is also global) is set to a different value. And after I parent it back, its set to the old value again.

```
Eye.parent = null; //unparent my eye to the world - Eye moves anyway because its movend by SteamVR
Parent.transform.position = Eye.position; //set my Parent to the same position as Eye (works)
Eye.parent = transform; //parent it back. Local Eye moves back where it was and there is a distance between parent and eye again.
Parent.transform.rotation = Quaternion.LookRotation(StartForward, StartUp); // the rotation changing my eyes position because its parented. Also the rotation is wrong.

```

And now i dont know anymore how to solve this problem.

so... i painted my problem in paint for better understanding:

# Answer
```
// Populate the net rotation that you want the child to have.
Quaternion desiredRotation = Quaternion.LookRotation(StartForward, StartUp);

// Create a rotation that undoes the child's rotation, then applies the desired rotation.
Quaternion rotationCorrection = desiredRotation * Quaternion.Inverse(Eye.localRotation);

// The parent will apply this correction to its child transforms.
Parent.transform.rotation = rotationCorrection;

// After this rotation has been applied,
// find offset from the child to the position we want it to start, in worldspace.
Vector3 positionCorrection = desiredPosition - Eye.position;

// Apply this offset to the parent's worldspace position to shift it into place.
Parent.transform.position = Parent.transform.position + positionCorrection;

```

Just be careful when creating mismatches between the true position/movement of the player's head and the perspective in-game. Be up-front with the player about what pose they should have when starting the game.

You may want to consider stripping out some of the components you calibrate for at startup:

* Ignore the pitch and roll of the head (so that if I start the game with my head slightly tilted, this doesn't tilt the whole world sideways for the rest of the game)
* Ignore the vertical offset in the position correction (so that if I start the game sitting, then stand up, I'm not levitating for the rest of the game)

I can show you how to apply these changes if they're useful for your case.
> 1 votes

---
Tags: unity, rotation, transformation
---


# Question
Title: Is there a way of limiting the sprites you can select in unity
So, if you had something like:

```
public sprite;

```

in a monobehavior, and that was dragged onto a gameobject, in the editor you will have the option to click the variable and select a sprite to use.

For me, I have many many pictures that I can choose from, and it takes me a while to select the correct image that I need to use.

Is there any way to categorize pictures, and only show pictures from that category? For instance, can I add some kind of tag or something to the picture assets something like "UI", so then when the developers that use my scripts go to select an image, they are not bombarded with every possible image in the game, but instead something contextual that makes sense?

I am wondering if this functionality exists already or any other way to achieve similar results.

Thanks for your time!

# Answer
> 1 votes
We, as a team, have a working system. We use good names (not really great since you can see UI-btn and UI-Button as names) and we filter out all the other sprites this way. When I want anything that is related to UI, I type in UI- and voila! If I want UI buttons, I type in UI-btn- and voila! It's pretty good on it's own, you just need to use it.

Also, as a file & folder structure, I suggest you keep everything that are of one kind in one folder, and separate it further inside that folder. If I'm not sure which folder a material should go, it usually keeps sitting in the Assets folder until I can decide (which doesn't take that long). See examples below:

---
Tags: unity
---


# Question
Title: Need to count a number of programmatically created objects in separate script
I have a game that creates and places a random number of "pickups" on a plane at random places.

I then have a script on the "Player" game object that uses `OnTriggerEnter` to tell when an item has been "picked up" and compares a count (the score) to the number of objects that are created:

```
void OnTriggerEnter(Collider other)
{

    // Get all game objects with the Tag "Pickup"

    if (other.gameObject.CompareTag ("Pickup")) {

        // Deactivate objects that are touched/collected
        other.gameObject.SetActive (false);

        // add to count
        count++;

        scoreText.text = "Score: " + count;

        //TODO: fix this statement; pickupCount is always 0 here, why?

        if(count >= pickupCount){
            winText.text = "You Win!";
        }

    }

}

```

The problem I am facing is that during building this worked fine, I built the project and it outputted "You Win!" after picking up 1 "pickup", I found out this is because for some reason the value of `pickupCount` is now always 0.

`pickupCount = GameObject.FindGameObjectsWithTag("Pickup").Length;`

My guess is that because the Playerscript checks at `Start()` and the SpawnScript creates at `Start()` that the reason the number is always 0 is because at the time of checking there are in fact no "pickups" created. My question is then, how do I check for the total number of these pickups without doing it in an update function?

**SIDE NOTE**

I know I could just change the `OnTriggerEnter()` function to be something like this:

```
void OnTriggerEnter(Collider other)
{

    // Get all game objects with the Tag "Pickup"

    if (other.gameObject.CompareTag ("Pickup")) {

        // Deactivate objects that are touched/collected
        other.gameObject.SetActive (false);

        // check number of pickups left
        pickupCount =  GameObject.FindGameObjectsWithTag("Pickup").Length;

        // add to count to show the score
        count++;

        scoreText.text = "Score: " + count;

        if(pickupCount <= 0){
            winText.text = "You Win!";
        }

    }
}

```

But it is more a case of curiosity now more than anything. Is what I am asking even possible?

# Answer
I'd be inclined to do this with a static variable on a script attached to your pickups:

```
public class CountedPickup : MonoBehaviour {

    static int _pickupsRemaining;
    public static int PickupsRemaining { get { return _pickupsRemaining; } }

    void OnEnable() {
        _pickupsRemaining++;
    }

    void OnDisable() {
        _pickupsRemaining--;
    }
}

```

Now your player script (or any other) can check `CountedPickup.PickupsRemaining == 0` to check how many are left to collect.

This will work even if this component doesn't know anything about what *kind* of pickup it is (it just represents the idea that this pickup should be included in the count, even if you mix & match different types of pickups in one level), and whether you `Instantiate()` & `Destroy()` pickups, or just toggle them on and off with `gameObject.SetActive()`
> 2 votes

# Answer
This isn't necessarily the most elegant approach to this problem, but to respond to this part of your problem:

> My guess is that because the Playerscript checks at Start() and the SpawnScript creates at Start() that the reason the number is always 0 is because at the time of checking there are in fact no "pickups" created.

Note that it's pretty easy to make some code execute once at a later time. There are multiple approaches, but the simplest is Invoke.
> 0 votes

---
Tags: unity
---


# Question
Title: How to instantiate an array of Prefabs in C# Script
Sorry if this sounds quite primitive, I am new to Unity. I am trying to instantiate an array of prefabs, but it doesn't seem to appear when I run the game. Firstly I created my block prefabs, then I created an empty game object and added the following script to the empty object.

```
public class BlocksTestScript : MonoBehaviour {

    public GameObject[] blockPrefabs;
    // Use this for initialization
    void Start () {

        blockPrefabs = new GameObject[7];
        blockPrefabs = Resources.LoadAll ("/Prefab/BlockPrefabs") as GameObject[];

                for (int i = 0; i < blockPrefabs.Length; i++) {
        GameObject myPrefabs = Instantiate(blockPrefabs[i], blockPrefabs[i].transform.position, Quaternion.identity) as GameObject;
    }

    }

    void Update () {

    }
}

```

I get the following error:

> Assets/Resources/Scripts/BlockTestScript.cs(14,28): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

How can I resolve this issue?

**UPDATE**

After looping through to instantiate the prefabs I now get the following error:

```
NullReferenceException: Object reference not set to an instance of an object
BlocksTestScript.Start () (at Assets/Resources/Scripts/BlocksTestScript.cs:15)

```

# Answer
In the first place look at your instantiation code: it makes no sense. You're assigning a `GameObject myPrefabs` (why the name `myPrefab`? It's not a prefab after you instantiate it; and why the `s`? every one your instances is ONE instance) but as soon as you go out of the `for` loop's scope, you've already lost that reference. You need to set up an empty array like this in your class:

`GameObject blocks[] = new GameObject[7];`

and then do

```
for (int i = 0; i < blockPrefabs.Length; i++)
    blocks[i] = Instantiate(blockPrefabs[i]) as GameObject;

```

...now you will maintain the references to each `block` in that array, and can work with these later.

Secondly I'm not sure why you'd want to complicate things by using `Resources.Load` on your prefabs. Just drag your individual prefabs from the Project or Hierarchy views into the inspector listing for `public GameObject[] blockPrefabs` on your `BlocksTestScript` (after setting that array's size to 7 or whatever there in the inspector). Then you can remove the first 2 lines in your `Start()`.

```
public class BlocksTestScript : MonoBehaviour
{
    public GameObject[] blockPrefabs; //size gets set in inspector! drag prefabs in there!
    public GameObject[] blocks;

    void Start ()
    {
        blocks = new GameObject[blockPrefabs.Length]; //makes sure they match length
        for (int i = 0; i < blockPrefabs.Length; i++)
        {
             blocks[i] = Instantiate(blockPrefabs[i]) as GameObject;
        }
    }
}

```
> 2 votes

---
Tags: unity, c#, gameobject
---


# Question
Title: Reset 3ds Max 2017 keyboard shortcuts to default
I somehow messed up my keyboard shortcuts for 3ds Max 2017. How can I restore them to the default? Is there a default shortcut file I can restore them with?

I'm aware there's a *Reset* button inside the Keyboard options, but my 3ds Max crashes when I hit that button.

# Answer
Don’t worry. I’ve found out how to fix this. I just searched for .kbdx files in 3ds Max Program Files folder and used the one that was called DefaultUI and was in En-US folder. Thanks for trying.
> 1 votes

---
Tags: 3dsmax
---


# Question
Title: libGDX upload z-axis of sprite to graphics card
Background: I want to obtain each fragments position via vertex interpolation to then calculate the light vector for phong shading (L = \[Fragment pos\] - \[light source pos\]).

Problem:

At the moment I am using libGDX's *com.badlogic.gdx.graphics.g2d.Sprites* to upload my 2d sprites via the batch to the graphics card. However they only transport the x and y information for each vertex ( I think in the shader z is 0). I also want to upload the z axis of the sprite for use with normal map based pixel shading (calculate the vector of the incoming light).

Should I use a *com.badlogic.gdx.graphics.Mesh* for that or can I extend the Sprite class and somehow put the z axis in the vertices float\[\] array? If I should do that, how do I do this?

# Answer
> 0 votes
To solve this the libGDX SpriteBatch can me modified to add another component to the coordinate in the vertex array.

1. Copy the source code of SpriteBatch to a new class.
2. Copy the source code of Sprite to a new class.
3. In the sprite class increase the field VERTEX\_SIZE by 1.
4. Add the z component to methods like `translate` and `getVertices()`
5. In the SpriteBatch class add Z1-Z4 to the list of constants obtained in Batch.

Should look like this:

```
static public final int X1 = 0;
static public final int Y1 = 1;
static public final int Z1 = 2;
static public final int C1 = 3;
static public final int U1 = 4;
...

```

In the constructor change the vertex attributes to 3

```
new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),

```

and in the line above the `size * 10` to a `size * 10`, because of the four added vertex values.

Now use world coordinates for your sprites and pass the projection view matrix to the batch, so it gets uploaded to the graphic card. Now world and screen space coordinates are available in the fragment shader.

Beware that the depth buffer is disabled when using the spriteBatch. You can enable it by removing the

```
Gdx.gl.glDepthMask(false);

```

Source code can be found here. Maybe I forgot to mention something.

# Answer
> 0 votes
You're mixing terms and techniques here, a 2D-Texture **has no z-dimension**. What you actually want for your normal-mapping is to fetch the texel `t` from the image *using the usual 2D texture-coordinates* and use these color-values `t.rgb` as a normal-vector.

---
Tags: libgdx, shaders, sprites
---


# Question
Title: Can you compare a parameter to another parameter using ChoiceFormat?
I'm currently using the `I18NBundle` (wiki | docs) package from LibGDX to do some internationalization for my game. the `I18NBundle` internally uses the java `MessageFormat` (docs) to format strings such as this:

```
// The string to format.
shields = Shields: {0, number, integer}

// Do the formatting
bundle.format("shields", 5);
>> Shields: 5

```

It can also do conditionals like so:

```
// # = if exact
// < = if greater than
shields = Shields: {0, choice, 0# No Shields! | 1# One Shield! | 1< {0, number, integer} Shields!}

bundle.format("shields", 0);
>> Shields: No Shield!

bundle.format("shields", 1);
>> Shields: One Shield!

bundle.format("shields", 5);
>> Shields: 5 Shields!

```

Now I'm trying to compare two input parameters to each other. I tried this:

```
// If parameter 1 is greater than parameter 0...
score = Score: {0, choice, {1}< {0} New high score! | {0}}

bundle.format("score", newScore, highScore);

// Expected Output if new score is lesser than high score
bundle.format("score", 1, 5);
>> Score: 1

// Expected output if new score is greater than high score
bundle.format("score", 7, 5);
>> Score: 7 New high score!

```

But this throws an exception since it is invalid formatting. So my question is: **Is it possible to compare two input parameters to each other when using `ChoiceFormat`?**

# Answer
You can use this workaround of using a `number` (0 for false and 1 for true) instead of a `boolean`, since a `boolean` is not permitted.

```
condition=Score: {0,choice,0#Cool Score, but {1, number} is less than {2, number}!|1#New Highscore of {1, number}!}

```

This code :

```
int highScore = 15;
int newScore = 20;

boolean isHighScore = newScore > highScore;

//I use a ternary if in order to translate the boolean into a number since booleans
//are not accepted by ChoiceFormat
String res = i18NBundle.format("condition", isHighScore ? 1 : 0, newScore, highScore);
System.out.println(res);

//I test again with a new score that is not the highscore
if(isHighScore)
    highScore = newScore;

newScore = 13;
isHighScore = newScore > highScore;
String res2 =i18NBundle.format("condition", isHighScore ? 1 : 0, newScore, highScore);
System.out.println(res2);

```

Outputs :

```
Score: New Highscore of 20!
Score: Cool Score, but 13 is less than 20!

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: How do I find all game objects with particular name?
I'm trying to mimic `FindGameObjectsWithTag` with `FindGameObjectsWithName`. I know using tags is faster, but I'm trying create a way to search for objects I spawn with a child object I name on instantiation through the inspector.

My goal is create multiple enemy spawners. My current spawner has a drag and drop variable for enemy prefabs. It looks for enemies tagged "ReSpawn", then checks if that length is below a value, to start spawning more. I would like to upgrade my current single spawner to still check for enemies named "ReSpawn", but then check if those respawns have a child object a name specified in the editor. This way, I can set the enemy spawners anywhere (e.g. near water, tall grass, forests, etc), and when I defeat one, the specific spawner will instantiate one of its opponents for that area.

---

Here is my code, so far:

```
var ThisSpot:String;
var Oppos : GameObject[];
var OppoCount : GameObject[];

var HowMany = 3;
var spawnSizeArea = 25;

function Start() {
    StartCoroutine ("Spawn");
}

function Update () {
    OppoCount = GameObject.FindGameObjectsWithTag("Respawn");
    // OppoCount = GameObject.FindWithName(ThisSpot);  This is what I am trying to achieve

    if(OppoCount.length < HowMany) {
        StartCoroutine ("Spawn");
    }
}

function Spawn() {
    var length = Oppos.length-1;
    var index = Mathf.Round(length*UnityEngine.Random.value);
    curSpawn = Oppos[index];

    var xz = Random.insideUnitCircle * spawnSizeArea;
    var newPosition = Vector3(xz.x,0,xz.x)+transform.position;

    yield WaitForSeconds(Random.Range(70,120));

    Instantiate(curSpawn, newPosition, transform.rotation);

    // Then I could use these 2 lines of code below to use multiple spawners
    //var newOp : GameObject = Instantiate(curSpawn, newPosition, transform.rotation);
    //newOp.transform.Find("fighter").gameObject.name=ThisSpot;

    StopCoroutine("Spawn");
}

```

# Answer
Unity best practices are to *never* use `Find` in any of its incarnations at run time. It's slow and unnecessarily ties the name of the object with its functionality.

Any time you call `Instantiate` you can save off the return value and store it somewhere (i.e. a `List` in some component your write). Then you can just iterate over the elements of that list to get what you want.

So for your spawner example, your spawner could have a list of game objects that it has spawned. In `Update` you can iterate over that list and count the number of non-null gameobjects (to check for destroyed objects). Alternatively the enemy can have a reference to its spawner and remove itself from that list in `OnDestroy`. Then if that number is less than a certain value spawn a new one.
> 3 votes

# Answer
From Unity Reference :

```
// This will return the game object named Hand in the scene.
hand = GameObject.Find("Hand");

```

You must remember that when trying to access objects via script, any inactive GameObjects are not included in the search. And that this will only return one object.

If you want to create the same behaviour as 'FindGameObjectsWithTag', you'll have to implement the function yourself.

In one of my games, for each level I used a GameObject to parent all the other objects, this way it was easier to access the objects. You could do something like :

```
int count = 0;
GameObject[] children = GetComponentsInChildren<GameObject>();
foreach (GameObjectchild in children )
{
    if(children.name == "WantedName")
        ++count;
}

```

**Edit:**

If you're using the UI to add instances to the spawner, that means that the spawner, and the objects it is supposed to spawn, are already instanced at startup. I don't think this is the best way to go about it. I would personally add a script to the spawner with an Enum for each monster type. This scripts behaviour would be to check if it holds an instance to an object, if not create one of the Enum type and keep the reference.

If you haven't tried overloading UI yet, it can be quite easy and help enormously in creating a more suitable editor for your game.
> 3 votes

# Answer
The original asker edited their question with the solution they used. However, as questions should not be edited to include the answers, I have removed the code to post as a community wiki.

---

The original asker reports that they used this code to meet their requirements:

```
function Update (){
    for (var i =0; i < OppoCount.length ; i ++){
        if(OppoCount.length > 0) {
            if (OppoCount[i].gameObject == null){
                OppoCount.RemoveAt(i);
            }

        if(OppoCount.length < HowMany){
            StartCoroutine ("Spawn");
        }
    }
}

function Spawn(){
    var length = Oppos.length - 1;
    var index = Mathf.Round(length*UnityEngine.Random.value);
    curSpawn = Oppos[index];

    var xz = Random.insideUnitCircle * spawnSizeArea;
    var newPosition = Vector3(xz.x,0,xz.x) + transform.position;

    yield WaitForSeconds(Random.Range(2,4));

    var newOp : GameObject = Instantiate(curSpawn, newPosition, transform.rotation);

    OppoCount.Push(newOp);
    StopCoroutine("Spawn");
}

```
> 0 votes

---
Tags: unity, javascript
---


# Question
Title: Get an exponential number between two numbers
Bit of a math question here...

lets say I want to supply a number (any number) and I want the result to be clamped between 0 and 1.

For instance, see the following graph.

Is there a way that when a number larger than 1 is supplied, that it returns a number that is still within those bounds (0 - 1), but still resulting in a number larger than any smaller supplied numbers that came before it (for instance, a supplied 2 would be a slightly larger number than a supplied 1.5)?

Thanks for your help!

# Answer
How about this?

You can increase the exponent to make it "steeper." The expression "1/(x+1)" is bounded between (0,1\] for x \>=0, so subtracting any exponent of that will never quite reach 1.
> 2 votes

# Answer
This is a tricky problem to solve in practice.

The answer is yes and no.

---

## No:

Not unless you use a value format with **better precision to contain your result value** (0 ... 1) than the value format of your original value.

In your question you want to ensure that a number on the input side of your function that is larger than another number on the input side **will always** give a larger number on the output side.

Due to precision loss you cannot guarantee this unless you use a larger format.

**Otherwise very close but distinct numbers on the function's input will give the same result on the output.** This is probably something you do not want.

```
(A != B) && (Remap(A) == Remap(B))

```

Is guaranteed to be true for some cases if you do not use a larger precision for the result of your `Remap` function.

---

## **Yes:**

There are multiple ways to do this but all require a larger precision for the result.

One very simple and quick way for **positive numbers** if your language and compiler uses IEEE 754 (Also known as IEC 60559) floating points and allows re-interpretation of bits in memory. Is to interpret the bits of this floating point positive number as an integer of the same bit size, convert it to a larger floating point with enough bits to contain the integer value, then divide the result by (2 to the power of integer\_bits-1).

C example:

```
#include <stdint.h>
double RemapPositives(float x){
    return (*(int32_t *)&x) * (1.0 / 2147483648.0);
}

```

This works because the standard guarantees that comparing two positive floating points stored in memory as integers will give the same relation (larger, equal, smaller).

But in your question you say:

> I want to supply a number (**any number**)

So to do this with negative floating point numbers you must convert the 1's complement value.

```
#include <stdint.h>
double Remap(float x){
    uint32_t v = *(uint32_t *)&x;
    if(v & ((uint32_t)1 << 31)){
        v = ~v;
    } else {
        v = v + ((uint32_t)1 << 31);
    }
    return v * (1.0 / 4294967296.0);
}

```

If you need to do this with double (64bits) floating points as input you must be able to use a larger floating point format (80bits or 128bits). Not all platforms support floating points larger than 64bits.
> 1 votes

---
Tags: mathematics
---


# Question
Title: How to store an array of prefabs together with configuration parameters
I have attached the following script to a number of weapon prefabs:

```
public class WeaponScript : MonoBehaviour {

    public enum Direction {Right, Straight, Left};
    public Direction weaponDir;

    void Start () {
        prepareDirection (weaponDir);
    }

    void prepareDirection(Direction dir)    {
        if (dir == Direction.Straight)  {
            transform.localEulerAngles = new Vector3 (0, 0, 0);

        }

        else if(dir == Direction.Left)  {
            transform.localEulerAngles = new Vector3 (0, 0, -30);
        }

        else if(dir == Direction.Right) {
            transform.localEulerAngles = new Vector3 (0, 0, 30);

        }
    }
}

```

I also added the following script to an empty game object SetupWeapon:

```
public class SetupWeaponsScript : MonoBehaviour {

    public GameObject[] weaponPrefabs;
    public GameObject[] weapons;

    void Start ()
    {
        weapons = new GameObject[weaponPrefabs.Length];

        for (int i = 0; i < weaponPrefabs.Length; i++)
        {
            weapons[i] = Instantiate(weaponPrefabs[i]) as GameObject;
        }

    }
}

```

When I select my SetupWeapon object, I am able to populate the `weaponPrefabs` array with the weapon prefabs I want to use, but I can't directly alter their parameters in that same inspector view. I want to be able to override the direction of each weapon prefab in the list, rather than use the value that's stored on the prefab itself.

How can I create the `weaponsSetupScript` in such a way that I can set the direction enum for each weapon entry at the same time that I set select the prefab in the editor? I believe it might have something to do with inheritance, just not too sure how to go about it though.

# Answer
> 0 votes
If you want a tuple - a type that contains your two pieces of data together in a package - then just define one. ;)

```
public class SetupWeaponsScript {

    // Here's our tuple combining a weapon prefab and a direction.
    [System.Serializable]
    public struct DirectedWeapon {
        public WeaponScript weapon;
        public WeaponScript.Direction direction;
    }

    // The prefabs array is now this tuple type.
    public DirectedWeapon[] weaponPrefabs;
    public WeaponScript[] weapons;

    void Start ()
    {
        weapons = new WeaponScript[weaponPrefabs.Length];

        for (int i = 0; i < weaponPrefabs.Length; i++)
        {
            // Using typed Instantiate to save a GetComponent call.
            weapons[i] = Instantiate<WeaponScript>(weaponPrefabs[i].weapon);
            weapons[i].weaponDir = weaponPrefabs[i].direction;
        }
    }
}

```

In the Inspector it looks like this, so you can populate the prefab and direction side-by-side:

---
Tags: unity, c#, gameobject
---


# Question
Title: How can i convert a non-convex mesh collider object to a convex mesh collider object
I created a character object in Maya and stored it as char.obj, then I imported the object into Unity.

The character object is not colliding with any other Unity objects like cube, plane, sphere, etc.

Then I found non-convex mesh colliders do not collide with any other Unity default objects. How can I convert the non-convex mesh collider to a convex mesh collider?

Here is the error message I see:

> Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported in Unity 5. If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component. Scene hierarchy path "mesh\_octopus/Default", Mesh asset path "Assets/PlaceAsset/mesh\_octopus/mesh\_octopus.obj" Mesh name "Default"

# Answer
> 1 votes
Mesh colliders have some limitations. Specifically, it has to be set to Convex (if your Rigidbody is not kinematic) and the object should have less than 256 vertices. In addition, Mesh colliders are expensive. Better is to use Box Colliders and Sphere colliders on your object. Use multiple colliders if necessary. If you want, remove the mesh collider component and add Box and Sphere Colliders.

Also, check this video on colliders in Unity. It is official Unity tutorial and covers the basics of different colliders and when and how to use them.

# Answer
> -2 votes
Just tick the convex option to check. The current body will now behave or react on other collider.

---
Tags: monogame, unity, level-design
---


title: Apply a special effect to a scene area

text:
# Question
Title: Apply a special effect to a scene area
My 2D game has a second camera on the scene that renders an upside down image of the scene and distorts it, giving the effect of water reflection. I render this camera first, and on top of it I render the main camera.

This is working correctly as expected, however, I want to improve it's performance by performing this process in small sections of the scene instead of the whole screen. I created a trigger to detect which items should be turned upside down and rendered.

How can I turn these items and distort them as I did with the whole scene, but only to the `GameObject`s detected inside the trigger?

Note: I can't assign them to a layer since the layer is already in use.

# Answer
> 1 votes
If you are looking for a water effect like the one used in the *"Ramboat"* game, you need to that use a replica for each image of which you want water reflection and distortion, and then use a raw image in your second camera, with a minimum opacity value.

This gives you an effect, like as follows:

# Answer
> -2 votes
Inside the trigger : then activate object renderer. Outside the trigger : then deactivate object renderer.

---
Tags: unity, shaders, graphics-programming
---


# Question
Title: What is the different between "LoadSceneMode.Additive" and "LoadSceneMode.Single"?
What is the different between `LoadSceneMode.Additive` and `LoadSceneMode.Single`? When should I use one, over the other? I read the documentation, but I can't find any good examples of use for a definitive situation.

# Answer
> 9 votes
The document is actually pretty self explanatory, though the documentation for the new implementation is not as helpful as the original documentation. Let's take a look:

> # LoadSceneMode
>
> *enumeration*
>
> ## Description
>
> Used when loading a scene in a player.
>
> ## Variables
>
> Single Closes all current loaded scenes and loads a scene.
> Additive Adds the scene to the current loaded scenes.

This tells us everything we need to know about the two; If you use `LoadSceneMode.Single`, you close the current scene, and load the new scene. If you use `LoadSceneMode.Additive`, you leave the current scene *open*, and load the *contents* of the additional scene into the current scene.

---

If you were to have a game with distinct levels, where a player directly moves from one level into another, you would probably use `LoadSceneMode.Single`. Think of it like a level of *"Super Mario Bros."* or *"Rayman"*. Once you move in to the next level, you do not want to use the contents of the previous level. You might be able to move from level one to level two, and you might even be able to move back to level one from level two; but you would *not* be able to be in both level one *and* level two, at the same time.

If you were to have a game with one big game world, where the player can freely move around in an open world, you might want to only load areas of the game world specific to the location of the player. Think of it like the game world of *"The Legend of Zelda: Ocarina of Time"* or *"The Elder Scrolls IV: Skyrim"*; areas would be broken up into sections, in this case "scenes", and only loaded when relevant. There is no reason to need the parts of the world on the complete opposite side of the game map, for example; why waste memory by having it loaded, anyway?

In the above example, the player would *always* be in the game world; however, you would only keep *neighbouring scenes* loaded. If I was in the area marked as *"1"*, you might only have *"1"* loaded. If you wanted me to see out into the game world, you might only have as far as *"2"*, *"5"* and *"6"* loaded. If you wanted to get really tricky, you could implement a "vision distance" parameter based off player input and/or user hardware capabilities, and allow your game to load in as far back as *"12"*; but *only* if the user computer can handle all the additional data, in the local memory. As I move to the area marked as *"2"*, you might choose to load *"3"* and *"7"*, in anticipation of moving into further areas. If I continue on into the area marked as *"3"*, you might choose to unload *"1"* and *"5"*, while you load *"4"* and *"8"*, assuming I am too far from the unloaded area to even notice the fact that the area is not currently loaded.

---
Tags: unity
---


# Question
Title: What is the Default Pawn class and what is used for in Unreal Engine?
I'm newbie in Unreal Engine and also in games development.

I have developed my own version of Pong game (sources here) and I'm confuse with the behaviour of `DefaultPawnClass`: Its creating another Paddle in game (I posted a question about it here).

I have to questions:

1. What is Default Pawn class?
2. And, what is it used for?

# Answer
When you click on the 'Play' button in Unreal Editor, the engine spawns a pawn for you to control in the game. You can specify which *pawn* you want to spawn by DefaultPawnClass specified in the game mode.
> 1 votes

---
Tags: unreal
---


# Question
Title: Why is the image appearing smaller, in the scene?
I have a fresh Unity project, with just one 480x800 pixel image. It's platform is set to Android, and the aspect ratio in the game view is WVGA Portrait (480x800). However, the image doesn't occupy the whole screen.

The camera is orthographic, with a size of 5. My intention is to test different resolutions on the same device, and maybe test on other devices.

Why is the image appearing smaller, in the scene?

---

The project is set to 2D. I added the image firstly by pasting it directly to my Sprites folder using the Windows explorer, then by clicking Assets-\>Import New Asset, and got the same result. My only GameObject on scene is the one holding the image, this will be used as one of my game backgrounds.

Here are the texture import settings and the inspector for the GameObject:

I haven't tested anything regarding the UI on Unity yet, so no Canvas. My experience with the engine is two weeks.

# Answer
Your **pixels per unit** value in your texture import settings is 100. That means the default scale when you drop your sprite into the world will pack 100 pixels into each unit of world space - so your 480 x 800 image will take up **4.8 x 8 units of world space**.

Your camera has a vertical **size of 5**, which is a measured as a half extent (distance from the center to the top), so in total it sees **10 units of world space** vertically.

The middle 8 units are filled by your sprite, but at either side you have 1 unit of world space leftover.

**The simplest fix is to change your camera size to 4** \- then it will exactly match the size of your sprite in the world.

See this answer for more details on using pixels per unit and world space in Unity.

This use of world space as an intermediate between texture & screen coordinates might seem odd if you're coming from an environment that just blits image texels straight to the screen's pixels one-for-one, but it lets us do some powerful things, like...

* Displaying consistent gameplay on multiple different resolutions (all of our behaviour uses world space, so the play experience stays the same, while the mapping of that space to the screen grid and even which sprites we use can be adjusted independently)
* Complex transformation hierarchies, including 3D rotation (if 1 sprite texel = 1 screen pixel, then how do we foreshorten a sprite when looking at it on an angle?)
* Mixing 2D and 3D content / effects in a single world coordinate system
> 1 votes

---
Tags: unity, resolution
---


# Question
Title: How do I storage only integers value on a Vector3?
I need to figure out a way to lock or avoid Vector3 storage float numbers. I do need save only integers because each integer represents a place on an array. I don't wanna my objects moving with float precision. I need them moving on integer precision in world space (2D Game)

I tried force a type casting to round them up or down but it doesn't work

```
timeOffset += Time.deltaTime;

    if (timeOffset >= 0.75f)
    {
        Vector3 dir = playerCenter.transform.position - this.transform.position;
        transform.position += new Vector3((int)dir.x / dir.magnitude, (int)dir.y / dir.magnitude,
            (int)dir.z / dir.magnitude);
        timeOffset = 0;
    }

```

Any ideas?

# Answer
You're not rounding the position, you're rounding only the input from the direction.

Instead of having this code for rounding:

```
transform.position += new Vector3(
    (int)dir.x / dir.magnitude,
    (int)dir.y / dir.magnitude,
    (int)dir.z / dir.magnitude);

```

Try this code:

```
transform.position += new Vector3(
    (int)(dir.x / dir.magnitude),
    (int)(dir.y / dir.magnitude),
    (int)(dir.z / dir.magnitude));

```

Notice that the type casting is done on the whole value that is set to the position, and not just partially (with the extra set of parenthesis).

---

Although this fixes your issue with keeping your positions as integer values, using the casting to int is probably not what you want, as the values in the range \]-1, 1\[ will all be rounded to zero, which will result in weird behaviour near zero. You can use a method such as `Mathf.Round` or `Mathf.RoundToInt` (like DMGregory specified in his comment), or use a method like `Mathf.Floor` or `Mathf.FloorToInt` to achieve a more constant behaviour.

I don't have access to Unity, but I've created a small set of data and applied the different actions on it in C#, here is the formatted result:

```
ValToStrng    cast to int    Round    Floor
-2.0         -2              -2       -2
-1.9         -1              -2       -2
-1.6         -1              -2       -2
-1.5         -1              -2       -2
-1.4         -1              -1       -2
-1.1         -1              -1       -2
-1.0         -1              -1       -1
-0.9          0              -1       -1
-0.6          0              -1       -1
-0.5          0               0       -1
-0.4          0               0       -1
-0.1          0               0       -1
 0.0          0               0        0
 0.1          0               0        0
 0.4          0               0        0
 0.5          0               0        0
 0.6          0               1        0
 0.9          0               1        0
 1.0          1               1        1
 1.1          1               1        1
 1.4          1               1        1
 1.5          1               2        1
 1.6          1               2        1
 2.0          2               2        2

```

Depending on your needs, you can apply the method that is most appropriate.
> 3 votes

---
Tags: unity, c#
---


# Question
Title: How does transvoxel algorithm work and how can I implement It?
After wasting over three days of researching on DuckDuckGo/Google, trying to understand transvoxel paper and existing implementation, I come here to clarify the subject for me and made it easier for the next person who wants to implement it.

Here is the transvoxel's homepage which explains well what the algorithm solves. So now I'm happy to find something that solves my current problem, so I would like to implement it to my code, but the website doesn't explain how to implement it or sharing code (except tables). So I was looking for existing implementation of the transvoxel algorithm:

* Transvoxel (XNA): Looks great but this solution all-in-one (octree, caching, voxel, etc.) I *really* tried to understand the transvoxel class into this one, but no.
* Transvoxel (OGRE3D): Looks great too but again, all in one. I tried too to understand, I translated the code from C++ to C#, but no again.

Finding for marching cube was so easy, one class copy&paste, one public function.

So I gave up the idea to use existing implementation. Why not implementing it myself? (Sadly I don't have the skill to fully understand what the paper said, for example the ambiguous case).

The first thing I didn't understand was if transvoxel is a modified marching cube or a seconds layer that modify the work of the marching cube. In the C++ code (second link of the list) the code uses a implementation of marching cube and *transvoxelize* each border, on the paper they talk about 19x19x19 voxel data on 16x16x16 chunk and about a modified version of marching cube.

So do you guys can **explain me how the transvoxel algorithm works and how can I implement it on my existing project**?

My existing project is an Unity3D project which uses marching cubes for an infinite world, LOD chunk are ready, the only one thing missing is fixing crack between different LOD level chunk.

# Answer
The transvoxel paper is a fairly in-depth work, discussing a variety of topics on how to create an entire voxel terrain system, including an overview of marching cubes, how to fix the ambiguity problem, vertex sharing, triplanar texturing, and texture splatting. The area you are interested in is covered in chapter 4, Level of Detail.

It introduces 512 new types of marching cubes, which are adapters between a voxel of one level of detail and another with half the level of detail. For example, a 16 unit voxel with a 32 unit voxel.

The new marching cubes can be constructed using the lookup tables provided on the transvoxel's homepage. The lookup tables are structured differently than the one used by the original marching cubes. I will walk through the first shape as an example, and it should be pretty easy to figure out the rest.

The values in transitionCellClass define which of the 56 equivalence classes the shape belongs to. (With the high bit set to indicate that the triangles should be winded in reverse) The value at index 1 is 0x01, telling us that its equivalence class is 1.

The transitionCellData array is information about the equivalence classes, containing the vertex count, triangle count, and the order of the vertexes. If we look up the value at index 1 (which we got from transitionCellClass) we see the following:

{0x42, {0, 1, 3, 1, 2, 3}}

0x42 in binary is 0100 0010, which means there are 4 vertices, and 2 triangles. And the rest that the ordering of the vertices for triangle 1 is 0, 1, 3; and the ordering for triangle 2 is 1, 2, 3.

What remains to be calculated is the actual edges these vertices and triangles are on. This is contained in the transitionVertexData array. Looking up index 1 (this is the shape number not the equivalence class) we see the following:

{0x2301, 0x1503, 0x199B, 0x289A}

These numbers define the vertex reuse in the high nibble and the vertex edges in the low. In binary (which makes the structure more apparent) it looks like this:

0010 0011 0000 0001, 0001 0101 0000 0011, 0001 1001 1001 1011, 0010 1000 1001 1010

Throwing away the information we aren't interested in at the moment, we are left with:

0000 0001, 0000 0011, 1001 1011, 1001 1010

or:

0, 1, 0, 3, 9, B, 9, A

In other words vertex 0 is between corner 0 and 1; vertex 1 between 0 and 3; vertex 2 between 9 and B, and vertex 3 between 9 and A.

In marching cubes there were 12 edges between 8 corners, and in transvoxels there are 16 edges between 13 corners. 9 facing the higher detail and 4 the lower.

You could if you wanted, assign each edge a number like in the original, as follows:

0 -\> 1 = 0

0 -\> 3 = 2

9 -\> A = 12

9 -\> B = 13

It would then be pretty trivial using these edge numbers to combine the data and put them into a single table like the original marching cubes. The first shape would look like the following:

{0, 2, 12, 2, 13, 12, 0}

Using this new table, you can build it the exact same way as you did in the original.

Now that you have these 512 shapes, what do you do with them? Wherever the level of detail changes, you have to insert transition cubes between (previous answer has an excellent picture of this) For each side of the cube that faces a higher level of detail, you place a transition cell.

Each transition cell is constructed by taking the sign values of the 9 corners of the side facing the high detail voxels, and creating a lookup value the same way you did with the original marching cubes, and creating the shape using the lookup tables, as I explained. The transition cells should be a percentage of the cube, like .25 or .125. And of course it has to be reoriented to face to appropriate side. Both of these transformations can be done when converting the edges to world coordinates.

After you add each of the transition cells, you can then place a regular marching cube scrunched up right in the center of the transition cells, using the standard eight corner lookup.

And that's pretty much all there is to it :)
> 12 votes

# Answer
> The first thing I didn't understood was if transvoxel is a modified marching cubes or a second layer that modifies the work of the marching cubes.

My reading of the paper is that Transvoxel's novel addition is a kind of "adapter" to bridge regions of voxels at different resolutions.

Let's say you have an area of very dense voxel samples near your player's camera, and some distance away you want to drop down to half the resolution, and further out to a quarter res:

(Visualized here in 2D for simplicity)

Within the body of each of these regions you have a regular grid of potential samples you can turn into a mesh with the conventional marching cubes algorithm - no problem. (Cells in blue above)

But where these grids of different resolutions butt up against one another, you have these weird voxel cells that have more samples along one face than the others. (Cells in green above)

If we ignore these mid-edge/mid-face samples and just build our mesh for the cell using the samples at the corners as usual, then we risk mis-matching the adjacent mesh formed from the higher resolution sample grid, which does include this information.

So instead, we use the lookup table provided by Transvoxel to select and fit the correct adapter mesh into these border cells, taking into account dense samples on one side, and sparse samples at the other corners.

Its operation is very similar to marching cubes, it just considers a different arrangement of sample points and so has a different collection of mesh templates it uses to bridge them.

> on the paper they talk about 19x19x19 voxel data on 16x16x16 chunk

I think that means this:

Does that help you get oriented with how this algorithm fits into a voxel meshing system?
> 9 votes

---
Tags: unity, algorithm, voxels, level-of-detail
---


# Question
Title: How should I deal with different enemy types?
I'm making simple space shooter game for Android in Unity. I want to have different types of enemies (different weapon, stats, movement schemes) and I'm not sure how to do it. I'm quite new to objective programming and I don't really know what classes should I create. I guess I could just make a prefab for every enemy since there won't be many types, but that is not what I'm looking for. I have some ideas:

First of all I'd write an BaseEnemy class and enemy type subclasses that inherit from it.

My first idea is to create those without MonoBehaviour. Then I'd have to make an EnemyScript with MonoBehaviour that I'd add to enemy game object. It'd have a specific subclass object inside, which will set every variable. BaseEnemy would just have undeclared variables and in subclass I'd set particular values. But I'm not sure how to deal with different movement schemes then. I wouldn't be able to put move() function in subclass since it wouldn't have MonoBehaviour, so I'd have to find another way. I might put in EnemyScript every possible scheme and then use correct one depending on some type value, but it doesn't seem like a proper way, does it?

The second idea is to just make a MonoBehaviour BaseEnemy class. Then while creating enemy game object I'd just add correct subclass script (aaand... I'm not sure how to do it :/ )

Could you tell me which one is a better way? Maybe neither of those?

# Answer
> 1 votes
There are many different approaches, with different pros and cons. One good approach here, and the one most suited to Unity's entity/component system, is to simply mix and match different MovementBehavior, AttackBehavior, etc.components on different objects to make different enemies.

However that still runs into this problem you mentioned in your question, so I'm curious for clarification on what you're having a problem with there:

> aaand... I'm not sure how to do it :/

Is your problem that you simply don't know how to subclass MonoBehaviour? Because you totally can, just like any other class. Technically you already do, you just might not realize it; the `public class MyClass : MonoBehaviour {` at the top of most scripts *is* inheriting from MonoBehaviour.

Thus you can simply make a `public class BaseEnemy : MonoBehaviour` for your enemies to inherit from, and then make a script `public class SpecificEnemy : BaseEnemy`for specific enemies. Now you can just drag the SpecificEnemy script onto gameobjects just like any other component.

ADDITION: This other thread alludes to the same issue and solutions, so you should read it.

---
Tags: unity, c#
---


# Question
Title: How to Refresh Dependencies after Adding FreeType Extension in Android Project
I'm planning to use FreeType fonts in my game (LibGDX and Android Studio) and I already added the freetype dependencies in my project. How can I refresh the dependencies after adding them? I have found few similar questions regarding this topic but didn't offer much help. Here is an image of the dependencies:

# Answer
Try this command for explicit refreshing

```
./gradlew --refresh-dependencies

```

but I guess your ide should resolve it after you save the gradle file. You also can press `Sync Now` (not exactly sure what it does); it's on top right on your screenshot.

The command was taken from here: https://github.com/libgdx/libgdx/wiki/Dependency-management-with-Gradle#libgdx-dependencies
> 1 votes

# Answer
There's a banner that says :

> Gradle files has changed since last project sync. A project sync may be necessary for the IDE to work properly

You can click`sync now` and it will refresh the `Gradle` project
> 0 votes

---
Tags: android, libgdx, fonts, android-studio, gradle
---


# Question
Title: OnTriggerEnter doesn't detect collision until at least one of the two colliders move
I'm having trouble coding a melee attack script.

I've set up an attack hitbox that toggles enabled/disabled whenever you press a button (The hitbox itself doesn't move, it just blinks in and out) and I'm trying to have it hit an unmoving target. The first hit gets registered, but the next do not unless I move either the static target (by pushing it) or the player itself.

Both the hitbox and the hurtbox have kinematic rigidbodies in them. They are separate BoxCollider2Ds in their own "Hitbox" and "Hurtbox" layers, which only interact between themselves. My hit detection code is as follows:

```
void OnTriggerEnter2D(Collider2D col) {
    Debug.Log(col + " got hurt");
}

```

Here's a graphical example of what's going on. You can see how hit detection doesn't work until I nudge Test Monster. When I try to attack it without moving it, detection stops working.

# Answer
> 3 votes
OK, after a bit of tinkering, my brother and I finally found the answer.

The issue is as follows: **Enabling/disabling a BoxCollider** (or any collider for that matter) **doesn't wake up the RigidBody to which it's attached, but movement does. That's why it only worked when moving.**

All we needed is to make the Game Object's RigidBody2D to "Never Sleep". It's as simple as that.

# Answer
> 1 votes
You might try using OverlapArea instead of creating separate colliders for your hitboxes. That approach might make your code cleaner too, since you'd be detecting hits in the same place that the hitbox is activated, rather than a separate OnTrigger function.

# Answer
> 0 votes
The OnTriggerEnter2D only works when you enter for the first time then it will only work again when you exit the Trigger and re-enter so what who should use is:

```
void OnTriggerStay2D(Collider2D col)
{
    Debug.Log(col + " got hurt");
}

```

OnTriggerStay2D will work while you are inside the trigger.

The Problem is that it will be sending a Debug Log while you are inside

So you need to add some kinda of if statement like this

```
void OnTriggerStay2D(Collider2D col)
{
    if (Input.GetMouseButton(0))
    {
        Debug.Log(col + " got hurt");
    }
}

```

Change if statement depending on what key you want to use to attack.

if OnTriggerStay2D doesn't work well alone try using both OnTriggerStay2D and OnTriggerEnter2D. Also this code

```
void OnTriggerEnter2D(Collider2D col)
{
    Debug.Log(col + " got hurt");
}

```

will always send got hurt even if you are attacking or not so who should add a if statement like this

```
if (Input.GetMouseButton(0))
{
    Debug.Log(col + " got hurt");
}

```

---
Tags: 2d, collision-detection, physics, rigidbody
---


# Question
Title: Can not tweak collider`s border manually in Unity
Why can not I change collider\`s border manually? I remember being able to do that. I just clicked the gray button under in this case Box Collider 2D component, then went to the Scene view and tweaked it as I wanted by clicking and moving collider\`s border. But now when I do the same procedure on trying to click and drag the border in Scene view I am just losing focus of the collider, but do not change it in any way.

# Answer
> 1 votes
You need to reset layout to `Default` and then back to your work layout (if needed) and collider editing will work.

Also, you can close the `Inspector` and `Hierarchy` tab and then - reopen it.

Taken from `Unity` forums: http://answers.unity3d.com/questions/969724/i-cant-edit-my-collider-cursor-even-if-i-pressed-t.html

---
Tags: unity, 2d, ide
---


# Question
Title: How to initiate manually an animation in Unity?
I have a prefab and I want to control when an animation is initiated. I can't seem to figure out how to do that. I have already created the animation clip, the animator component for the prefab, and the animator controller. The animation works, when I enter play mode in the unity editor (it plays automatically), but I want to control when the animation occurs when providing input (such as pressing on the space bar or clicking on the prefab).

How would I go about doing that?

# Answer
> 0 votes
to call on an animation at will, the object must start in an empty state. To initiate an animation get the animator component for the object and call Play("stateName") on it. Remember to revert back to the empty so that the playable state can be replayed later

# Answer
> 1 votes
I'd advise you to refer to Unity Documentation for these kind of questions.

What you want to do can be achieved by using Animation States and Transitions.

Basically, you need to create an empty state in the **Prefab's** Animator Controller and set it to *Default* (Orange color). And create a transition from this empty state to the state which contains your light animation then set the condition for transition (Which could be bool indicating an user input).

---
Tags: unity, animation
---


# Question
Title: Changing the origin/pivot point of the parent in Unity
I create a game object, add some children to it, and would like the pivot point of the parent to be somewhere inside the area occupied by the children, not far away in the scene.

Like in the example below, I have three blocks of platforms situated near each over. I add them into a parent, then try to move that parent and notice that the origin point of the parent is actually not somewhere between its children, but outside them on the upper right:

Does someone know a way to change the origin point in such case?

# Answer
> 5 votes
The solution is straightforward.

First remove all the children from under the parent and put them somewhere else in the hierarchy temporarily.

Then move your parent's position to where you want it to be with respect to the children.

After that, move all children back inside the parent with the help of Hierarchy view.

Since the editor won\`t move your objects in the Scene view if you make some changes in the Hierarchy view, the children will stay in the same net coordinates. So, after doing that you will get the origin point of the parent in any place that's convenient for you.

---
Tags: unity, 2d, pivot
---


# Question
Title: Animating child objects via parent object animator in script
I'm using unity 5

I'm trying to animate multiple child objects via a parent object. The animation worked in the animation view but would not work when I tried to preview the game. In the script I use the code:

```
ParentObject.GetComponent<Animator>().Play("intro");

```

to play the animation. A similar line of code worked when playing a singular object, not sure what's going wrong now, any sugestions?

# Answer
I must admit, I'm somewhat of a neophyte when it comes to unity. But the solution that worked for me is switching the animator components for the parent and child objects on when I need them the animations to play and off when I didn't. It's like unity can only work with one animator component at a time...but hey whatever works right?
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How can I speed up Unity3D Substance texture generation?
I'm working on an iOS/Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re-import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change.

Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere?

# Answer
The substances by nature are generated at runtime. I have noticed a bit of lag sometimes myself, but from what I've noticed its only in the editor. A few tips to alleviate this check your substances you probably have a few that have some inefficient runtimes that could be causing a bottleneck. Also, if there are any substances that you are not generating variations, you don't need to have external seeds and can use a static number for in the substance itself.
> 2 votes

# Answer
# Bake those substances

Substance painter is a very powerful tool, but it has downsides. I did...let's call it "unpaid work" for "an organization" that saw that the substance code was smaller (file size) than the baked texture files and thought it was an optimization because of fanciful notions about bandwidth and hosting. Six months later I joined and was tasked with figuring out why it took the game 30 minutes to change scenes (or start, as you're seeing).

They also wanted to use one material for everything because the artists wanted to do all of their work inside Unity rather than in substance painter just by fiddling with properties in the inspector. And wanted all of the tools substance painted offered.

Rather than exporting the material properties of your substance, bake it down into a texture or two. Also, you seem to be planning for mobile devices, where my advice is: don't use substance painter at all. Mobile devices do not have the cpu, gpu, and ram necessary to handle complex materials (heck, most mobile shaders don't even offer color multipliers). You need to think about batching, both static and dynamic and complex materials will almost certainly break batching. *Especially* if they are procedurally generated.
> 1 votes

---
Tags: unity, testing, procedural, productivity, substance-engine
---


title: Game loop with multithreading

text:
# Question
Title: Game loop with multithreading
I have learned how to create and manage threads in C++. Now I'm trying to create game loop based on multithreading but I can't imagine how should I split whole game to tasks. I mean, should rendering be separated from updating physics?

# Answer
First of all, heed the warning by DMGregory in the comments to the question. Multithreading is an evil source of weird, randomly appearing and impossible to reproduce bugs. Do not use it unless you *know* you have a performance problem and you already exhausted all other options of optimization.

Unfortunately there is no easy answer to the question which game features to parallelize and which not, because every game is different. But the general rule of thumb is that you want to parallelize tasks which are very CPU-intense, can be separated into independent units of computation and do not write any data to memory which is used by the other units of computation. The reason for this is that whenever you have one thread reading data another thread is writing, you might once in a while hit a weird race-condition where you are reading an intermediate state of the old and the new data.

For example, if you want to do route finding on a complex nav-mesh for 10000 actors at once, you might be able to multithread that by having 4 threads process 2500 actors each. But only if your actors don't communicate the results of their route-finding to each other and no unit actually executes a move until all threads have finished calculating their routes. Make sure to join all threads before you continue.

Regarding separating game mechanics from rendering: I would usually advise against this stunt, for the reason described above: Race Conditions. If you do this naively, then your rendering loop might from time to time end up rendering an object which is half in the previous frame and half in the next frame, which can manifest as really weird graphic glitches. Also, keep in mind that the heavy lifting of rendering usually happens mostly on the GPU, not the CPU, and those computations are asynchronous anyway. So the benefit of this is in many cases dubious anyway.

But *if* you do something in your rendering loop which is unusually CPU-intense and you *really* want to do this, you can avoid those race conditions by using a double-buffering strategy on your game-state. Have two copies of your game-state. While state A is rendered, your game loop calculates a new game-state B. When both the rendering-thread and the game-thread are finished, you switch the two states. game-state B is rendered while a new game-state A is calculated based on B. The same strategy can be used to execute any other game systems in parallel, as long as no two game systems need write-access to the same data-structure of the new game-state.

Another problem you should keep being aware of is that creating, managing and switching between threads is quite expensive on most operating systems. For that reason you should avoid creating short-lived threads and you should never have more threads than you have CPU cores (unless they are threads which idle most of the time, like a network listener or a file reading thread).
> 4 votes

---
Tags: c++, game-loop, multithreading
---


# Question
Title: How do you create a perfect maze with walls that are as thick as the other tiles?
http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/

I read this article about dungeon and maze generation. The author uses a kind of specialized algorithm for generating 'perfect' mazes that have walls of non-zero thickness.

(Edit: I misunderstood the term 'perfect' here. It actually means there are no loops in the maze)

As I understand, typical maze algorithms work for walls of zero thickness but this is not what I want.

He posted his code in the article, but after a cursory glance, I think I need someone to explain the procedure (or a similar one) in plain english.

My first two attempts looked like:

Which produces an effect with the diagonals that are unsightly.

and then:

Which is better but its not 'perfect' in the sense that it seems to waste some space.

If someone can give me simple english instructions I might post the python code after I get it working.

# Answer
If I understand you correctly, you want to create a densely packed maze like this, where each wall is the same thickness as each corridor:

But you say the maze algorithms you've found only deal with infinitely thin partitions between cells corridor cells, rather than thick walls like these.

Let's look closer. Here I've overlaid a grid on the maze above, colouring all the even columns blue, and all the even rows orange:

You can see, the walls only show up on the coloured rows & columns. This gets a bit more obvious if we play with the grid spacing, making the coloured rows & columns thinner:

Gosh, that looks a lot like the output of one of those algorithms with infinitely-thin maze walls, doesn't it? Just at half the resolution.

So, we can take any maze algorithm that works on a rectangular grid with infinitely thin partitions between cells, and convert it to a thick maze like so:

* Open cell at (x, y) --\> Open cell at (2x + 1, 2y + 1)
* Wall between (x, y) and (x, y + 1) --\> Wall cell at (2x + 1, 2(y + 1))
* Wall between (x, y) and (x + 1, y) --\> Wall cell at (2(x + 1), 2y + 1)
* --\> All corner cells (2x, 2y) are walls
> 11 votes

---
Tags: python, maze
---


# Question
Title: How to access arrays of prefabs and other properties through the inspector in a given hierarchy
The script below is added to an empty game object `WeaponGroup`, which can be populated using the editor. I have made a new game object `WeaponGroups` which should have a script `SetupWeaponGroupsScript`. How can I transfer the properties below so that each `WeaponGroup` (`SetupWeaponGroupsScript` will have an array of `WeaponGroup` objects) is setup in a way similar to what is done below, so that I make the `SetupWeaponsScript` properties hidden to the inspector and populate them through `SetupWeaponGroupsScript`?

```
public class SetupWeaponsScript {

// Here's our tuple combining a weapon prefab and a direction.
[System.Serializable]
public struct DirectedWeapon {
    public WeaponScript weapon;
    public WeaponScript.Direction direction;
}

// The prefabs array is now this tuple type.
public DirectedWeapon[] weaponPrefabs;
public WeaponScript[] weapons;

void Start ()
{
    weapons = new WeaponScript[weaponPrefabs.Length];

    for (int i = 0; i < weaponPrefabs.Length; i++)
    {
        // Using typed Instantiate to save a GetComponent call.
        weapons[i] = Instantiate<WeaponScript>(weaponPrefabs[i].weapon);
        weapons[i].weaponDir = weaponPrefabs[i].direction;
    }
}
}

```

In other words I'd like to have the following hierarchy in the editor:

# Answer
> 3 votes
Use `ScriptableObject`. Create a script called `WeaponGroups` and put this inside:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class WeaponGroup{
    public Weapon[] weapons;
}

[System.Serializable]
public enum WeaponType{
    SWORD, GUN, BOW
}

[System.Serializable]
public enum WeaponDirection{
    LEFT, RIGHT, UP, DOWN
}

[System.Serializable]
public class Weapon{
    public WeaponType type;
    public WeaponDirection direction;
    public int damage;
}

[CreateAssetMenu(fileName = "WeaponGroups", menuName = "Custom/WeaponGroups")]
public class WeaponGroups : ScriptableObject {
    public WeaponGroup[] groups;
}

```

Now do:

and here go you:

You can use your `ScriptableObject` wherever you want. Just drop it somewhere :)

---
Tags: unity, c#
---


title: Acknowledgement reliability using UDP

text:
# Question
Title: Acknowledgement reliability using UDP
I have a question about UDP. For context, I'm working on a real-time action game.

I've read quite a bit about the differences between UDP and TCP and I feel I understand them quite well, but there's one piece that has never felt correct, and that's **reliability**, and specifically **acknowledgements**. I understand that UDP offers no reliability by default (i.e. packets can be dropped or arrive out of order). When some reliability is required, the solution I've seen (which makes sense conceptually) is to use acknowledgements (i.e. the server sends a packet to the client, and when the client receives that message, it sends back an acknowledgement to the server).

**What happens when the acknowledgement is dropped?**

In the example above (one server sending a packet to one client), the server handles potential packet loss by re-sending packets every frame until acknowledgements are received for those packets. You could still run into issues of bandwidth or out-of-order messages, but purely from a packet-loss perspective, the server is covered.

However, if the client sends an acknowledgement that never arrives, the server would have no choice but to eventually stop sending that message, which could break the game if the information contained in that packet was required. You could take a similar approach to the server (i.e. keep sending acknowledgements until you receive an ack for the ack?), but that approach would have you looping back and forth forever (since you'd need an ack for the ack for the ack and so on).

I feel my basic logic is correct here, which leaves me with two options.

1. Send a single acknowledgment packet and hope for the best.
2. Send a handful of acknowledgment packets (maybe 3-4) and hope for the best, assuming that not all of them will be dropped.

Is there an answer to this problem? Am I fundamentally misunderstanding something? Is there some guarantee of using UDP I'm not aware of? I feel hesitant to move forward with too much networking code until I feel comfortable that my logic is sound.

# Answer
This is a form of the Two Generals Problem, and you're right - no number of retries is enough to perfectly guarantee receipt.

In practice in games, there's usually a time horizon beyond which the information doesn't really matter though even if it technically arrives reliably. Like finding out you had a perfect headshot lined up 2 seconds ago - it's too late for the player to use that information now.

If your packet loss is so high that you can't routinely get the needed info through inside a tight reaction window, then for a realtime game you might be better off kicking the player and trying to find a better match for them elsewhere, rather than continue trying to send the packet to emulate a reliable connection.

Because of this, some game replication systems skip acknowledgement & retries altogether and opt to just spam the newest update as often as they can. If one gets dropped or arrives late, too bad, skip it, pick up the next one and carry on, relying on the prediction & interpolation systems to smooth the gap and minimize hiccups visible to the player.

I suddenly want to start calling this "Simba Replication" for how it disregards problems in the past and tries to live in the present moment. ;)

A hybrid solution is to race ahead sending the new update AND (since game state updates can often be quite small / compressible) also pack-in the last update, and maybe the one before that... So just in case the client missed them, you don't have to wait a full round trip time to find out and fix it. Most of the time the client already saw this, so there's redundant data this way, but the latency for correcting a missed message is lower. The client's updates can include the index number of the most recent consecutive update they've seen, so you can be minimally conservative with how many old updates you include in the next update packet.

You could also implement a two-tier system as another type of hybrid, where short-lived state is replicated in an unreliable rapid-fire manner, and long-term state is synchronized reliably, using TCP or your own reliability implementation with a high retry count. This gets more complex to manage though, because you have two messaging systems to maintain, and the two snapshots can be out of sync with one another, adding a whole new class of edge case.
> 32 votes

# Answer
The approach TCP uses is that the sender will keep resending the packet until it receives an acknowledgement. The receiver will ignore duplicate packets, but still send acknowledgements for them. The sender will ignore duplicate acknowledgements.

If a packet gets lost, the sender resends it, as you already know.
If an acknowledgement gets lost, the sender resends the original packet, which causes the receiver to resend the acknowledgement.

If an acknowledgement is not received within a certain time (perhaps 60 seconds, or 20 retries) then the player is considered to be disconnected from the game. You *must* implement some kind of timeout rule, or otherwise a player who unplugs their network cable will tie up resources on your server forever.
> 9 votes

# Answer
If you want to reinvent TCP, it makes sense to look at TCP first, which deals with the exact problem you describe (part of the solution is to use user defined values for retry attempts and timeouts).

Solutions that use 2 channels, a TCP channel (for reliable communication) as well as a UDP (for low latency communication) channel are not uncommon.

Some solutions detect when a client is missing some information for too long, and start a resynchronization, which may use UDP or TCP.

Another common approach is to design communication such that it doesn't rely on acknowledgements at all, but that's outside the scope of the question.
> 7 votes

# Answer
In an RTS you really cannot use a protocol like TCP, and you cannot make UDP reliable either. If you try to, the game will freeze whenever a there is a network hick-up.

Instead, you design the protocol so that missed packets don't matter too much.

The short version is that you don't care where the other players were last frame as long as you know where they are *now*. The long version is more complicated.

The question then becomes, what do you do when a packet goes missing? And the answer is... you guess. The player is probably moving in a straight line, right? Just move them one step further along that line. ... Except no RTS player *ever* moves in a straight line. And then there is collision detection.

This is hard. Many games get it wrong. It can be argued that there is no *right* answer to this, only various wrongs that can be traded off.

The reason these games work pretty well is not only that they have thought long and hard about these problems, but also that the Internet has become pretty reliable. Almost all UDP packets actually reach their destination in a timely manner. (Unless there is a permanent problem like a firewall)
> 3 votes

---
Tags: networking, udp
---


# Question
Title: Does it make sense to use both TCP and UDP at once?
After reading Is UDP still better than TCP for data-heavy realtime games?, I'm wondering if it makes sense to use both TCP and UDP at the same time, but for different things:

* TCP for sending information that is sent infrequently, but should be guaranteed to arrive reliably.
Such as score updates, a player's name, or even the on/off state of a light in the game world.
* UDP for transmitting information that is updated constantly and can be lost occasionally, since newer information is always on the way.
Such as position, rotation, etc.

Is this a reasonable idea? What are the possible drawbacks?
Are there better ways to handle this?

# Answer
It results in packet loss for UDP due to contention between the two protocols - remember that UDP is not guaranteed delivery, while TCP is. More TCP packets will get through while UDP suffers - TCP induces UDP packet loss. There has also been the (historical) idea that router infrastructure favours TCP over UDP, though I doubt that is still true by this late stage.

I think you'd be better off finding one of the connection-oriented UDP protocols that is out there for use in games and the like, that offers you some of the benefits of TCP with none of its downsides. There are a few such, usually with a whitepaper detailing each concept.

An example of those is the open source Enet library, its primary feature being optional reliable, in-order delivery of packets over UDP.
> 9 votes

# Answer
Here's a quote by Sam Jansen from a comment on gafferongames.com:

> Speaking as a network researcher and not a game developer, the conclusion to never use TCP and UDP together seems a bit strong. TCP will only have packet loss if it is sending too much data; in some ways just like the UDP data you are sending. The difference is you have no direct control on the rate TCP sends at, this is hidden to you.
>
> If you just need to send some reliable data and do not want to worry about retransmission and implementing a reliable protocol, and you know the rate will be low, then there wont be any problems with using both TCP and UDP.
>
> The relationship isn’t all that complex between the two really: TCP merely increases its send rate (if there is data to send) until it gets packet loss, in which case it dials back its rate, then starts increasing the rate again (this time more slowly). When its increase in rate causes packet loss, it is quite likely to hit any other streams of data as well, including your UDP packets.

The paper *Characteristics of UDP Packet Loss: Effect of TCP Traffic* got its results by opening multiple TCP connections at once and flooding the network with data. This leads to the congestion followed by global synchronization, both of which cause dropped packets. Obviously, a game client will not open a dozen connections at once and flood the network with data, and so your results will be different.

To answer your question:

> I'm wondering if it makes sense to use both TCP and UDP at the same time, but for different things \[...\]

Yes, this is an acceptable thing to do assuming you stay within your bandwidth limits.

> * TCP for sending information that is sent infrequently, but should be guaranteed to arrive reliably. Such as score updates, a player's name, or even the on/off state of a light in the game world.

When using both TCP and UDP, you should always prefer to send as much as possible over UDP and as little as possible over TCP.

Now, I ask you this: Is it really necessary to send the score, the player's name, and the state of a light over TCP? While it is true that you need to receive this data eventually, is it true that you need to receive this data strictly-in-order and exactly once?

Probably not.

UDP works fine for these cases, and Quake 3 is a good example of how.

So what's a good example of TCP alongside UDP then? Well, think of a game's chatbox. The updates to this chatbox (that is, the new lines of text) need to be sent both reliably and strictly-in-order. Thus, TCP is a good fit.
> 5 votes

# Answer
**Is this a reasonable idea?**

* Yes

**What are the possible drawbacks?**

* Packet Loss, more code complexity, another connection to manage == more chance for disconnects, time outs, exceptions, whatever ...

**Are there better ways to handle this?**

* Use an existing Reliable UDP Library. Two of the most popular are: Lidgren Network (C#), RakNet (C++). From experience I can say Lidgren is super easy to use, fast, and reliable.
> 3 votes

# Answer
There is an additional resource constraint to consider. Most implemenations (I Believe all, but have no reference) of TCP on the server has limits on how many concurrent TCP Connections the server can have open at the same time. This would limit the number of players you can have open at the same time if each player needs its own connection.

The limits are defined by settings in the network system. Additionally every Connection uses up some memory which has to come from somewhere on the server.

One solution is to only open a temporary TCP Connection while data is transferred and Close it immediately. This will make transactions slower, opening a tcp Connection is a rather "expensive" process. As Always, it is all about designing a robust system from the beginning in order to allow large growth.
> 1 votes

---
Tags: networking, multiplayer, udp
---


# Question
Title: Access gameObject array value from other script
I'm trying to access gameobject array values from one script to another. I have attached certain gameobject capsules with the array in the editor as shown in the figure below and I'm trying to access the values of array to another script. But I get null values when i try to pass the values. I don't want to use gameobject tag since i have to set gameobject active and deactive during runtime.

**PinsScript.cs**

```
public class PinsScript : MonoBehaviour {

        // Use this for initialization
        public GameObject[] pins;
        void Start () {

        }

        // Update is called once per frame
        void Update () {

        }
}

```

**MovingBall.cs**

```
PinsScript p = GetComponent<PinsScript>();

        foreach (GameObject pin in p.pins)
        {

             pin.SetActive(false);

        }

```

# Answer
Attach a PinScript to each pin. Keep a reference to each of your pins in an array when you Awake. Your PinScript can be empty. Then you have a reference to turn them on or off as you please. Your scripts would look like this:

PinScript.cs

```
public class PinsScript : MonoBehaviour { }

```

MovingBall.cs

```
public class MovingBall : MonoBehaviour
{
    private PinsScript[] pinScripts;

    private void Awake()
    {
        pinScripts = FindObjectsOfType<PinsScript>();
    }

    public void SetPinActivity(bool active)
    {
        foreach (var pin in pinScripts)
        {
            pin.gameObject.SetActive(active);
        }
    }
}

```

Then you can deactivate them by calling:

```
myMovingBall.SetPinActivity(false);

```

This, however, is not a great architecture. But it is a simple solution.

I assume you do not know how many pins you have. If you know your pins ahead of time, let me know, and I will suggest a more optimized solution. But this will work either way.
> 1 votes

# Answer
Your problem here is with referencing **which PinsScript are you trying to access.**

Whenever you are instanciating a new MovingBall, you **must** reference the PinsScript somewhere. I usually do this by adding a small portion of code on the MonoBehavior which create the MovingBall :

```
public PinsScript pinsScript;

```

Then, you just have to drag the GameObject holding the PinsScript into that variable. Another way to do it is by accessing the GameObject by name :

```
PinsScript p = GameObject.Find("TheNameOfTheGameObjectHoldingThePinsScript").GetComponent<PinsScript>();

```
> 0 votes

---
Tags: unity
---