# Question
Title: Difference between 'max distance' and 'radius' in Physics.SphereCastAll
I needed a way to check for all gameobjects within a set sphere of my player object.

I found Physics.SphereCastAll which will return a RaycastHit\[\], exactly what I wanted. But, I am having trouble understanding the method signature/docs.

Basically, it's the two things in the title I am confused on right now:

From Unity docs:

* radius - The radius of the sphere.
* maxDistance - The max length of the sweep.

Is 'max length of the sweep' a measurement of time (or degrees?)? I would have thought the length would be the same as the radius (or at least you could calculate it from the radius) but it obviously isn't what I think length means.

# Answer
`SphereCast` methods take a sphere and slide it along a line to see where it hits objects along its travel.

The `radius` parameter is the size of the sphere.

The `maxDistance` parameter is how far the sphere should travel in the given direction.

To simply check for objects near your player, you want CheckSphere or OverlapSphere / OverlapSphereNonAlloc instead. These methods check for colliders intersecting a given sphere, and give you either a `bool` result of whether a collision was detected, or an array of the colliders overlapping the radius. They don't try to slide that sphere to find contact positions.

This is not equivalent to a `SphereCast` with a maxDistance of 0. Like a raycast, this will only detect the points where it begins to intersect with an object - not situations where it was already overlapping in its starting position.
> 8 votes

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


# Question
Title: How can I add a sprite to gameobject to make the gameobject highlight?
When I'm running the game and then moving the mouse cursor over the menu it's highlighting it with some blue color: In the screenshot the OPTIONS is highlight.

Now I want to use the same highlight sprite to highlight the word THE in white at the top in the screenshot but to make it highlight all the time without the mouse cursor.

I have New Text in the Hierarchy and in the Assets I have Select and Select is the sprite I want to highlight with the word THE:

I tried to add a Sprite Renderer component to the New Text but the New Text have already a Mesh Renderer so I can't add the Sprite Renderer.

# Answer
Copy your already existing highlight sprite, then paste it as a child to the object that holds the word "THE". Change it's position values so that it is correctly placed behind the text. Resize as desired.

Remember: One object cannot have multiple ways to draw graphics, you can however add as many children as you want to that object, and each child can have it's own graphics.
> 3 votes

---
Tags: unity
---


title: Unity navmeshagent and doors

text:
# Question
Title: Unity navmeshagent and doors
I'm trying to make an agent patrol around a maze. The maze is proceduraly generated and consists of many rooms connected with doors. The problem occurs when the agent reaches a door. I wrote a script where if the agent gets near a door, the door opens, but the results are bad because the doors are walkable, so the navmesh doesn't consider them as obstacles and the agent gets stuck if the door opens and gets in its way.

I've been looking everywhere on the internet, but haven't found a solution. If anyone has an idea or a way to make this work, I'll be very thankful.

# Answer
I think what you're looking for is the NavMeshObstacle component.

https://docs.unity3d.com/Manual/class-NavMeshObstacle.html

https://docs.unity3d.com/ScriptReference/AI.NavMeshObstacle.html
> 2 votes

---
Tags: unity, ai, unityscript, navmesh
---


# Question
Title: Can I used a NES USB controller with XInput?
I'm doing a project to graduate from my game design degree and I have to recreate two levels from MegaMan(1987). I saw that there are usb nes controllers out there that are used for emulators on PC. Before I purchase them and try out programming my game with them, I'd like to confirm that I can use them with Xinput.

If anyone knows if this is possible, please let me know!

Thank you!

# Answer
> 1 votes
Maybe.

The specific controller itself has to support the XInput API, not the other way around. You'll need to see if the specific models you are interested in support the API, likely by reading the product specs or contacting the manufacturer.

If they don't (which seems likely), you'll need to use something else like DirectInput.

---
Tags: c++, directx, input
---


title: Why is creating my sprites so slow?

text:
# Question
Title: Why is creating my sprites so slow?
My 2D Unity game has tiles and layers. It creates one game object per tile, anywhere from 100 to 10,000. To create 3,000 game objects takes 68 msec, which is just fine.

But setting up the sprite and location takes 5,000 msec, or nearly 2 msec per sprite. This is a problem. Here is the code for setting up each tile.

```
   var sprite = _main.GetSprite(LevelIndex);  // pre-computed table of sprites
   _renderer.sprite = sprite;  // the sprite renderer for the tile
   if (sprite != null) {
     var cursize = _renderer.sprite.bounds.size;
     var scale = Math.Max(Size.x / cursize.x, Size.y / cursize.y);
     transform.localScale = new Vector3(scale, scale, 0);
   }

```

How can that code take 2 msec? What's going on?

The sprite size is 80x80. Is this a problem?

Once it's all set up it renders at 100 fps easily. So why is the setup so slow, and what can I do about it?

---

Yes, I considered using a TileMap. It's not easy to see how to create one in fully procedural code, but at the heart of it is the Tile class, which has a GameObject and a Sprite. If I implement my own Tile class it's going to have code that looks a lot like the above, and (after a lot of work) most likely perform exactly the same.

Since Tile and TileMap are just layers over standard Unity infrastructure, then if they do have a way to perform much faster, I should be able to apply the same technique to my situation and get the same performance.

# Answer
> 2 votes
It turns out the problem was not in this code at all, but in some code in the instantiated game object:

```
void Start() {
  _mainx = FindObjectOfType<MainController>();
}

```

For a few objects, this is cheap enough, but this API call does an \\$O(n)\\$ search, so creating \\$n\\$ objects results in an \\$O(n^2)\\$ slowdown.

Take away this code and Unity can happily instantiate and render thousands of simple game objects with no noticeable time delay.

---
Tags: unity, 2d, sprites, performance
---


# Question
Title: Calculating the shadow cast by triangle onto the YZ plane
So, one of the exercises for my computer graphics class is as follows:

**Calculate the shadow cast by triangle T onto the YZ plane P.**

given:

* Triangle T coordinates: A=(30,10,16) B=(32,11,18) C=(31,12,24)
* Light source L=(40,10,18)

The scene described above is as follows: there is a light source emitting light onto a triangle, the triangle is in front of a plane, due to the light there will be a shadow cast formed onto the plane.

In other exercises where we had to calculate whether or not a point was inside the shadow cast we made use of a line/plane equation. But this time it is not clear for me how calculate the points of the shadow cast.

# Answer
Find the equation of each line that starts on the light and goes through a vertex of the triangle. Then make the equation equal to the equation of the plane.

Basically, lightPosition + verticePosition = lineEquation.

Then lineEquation = lineOnThePlaneEquation

Here's an example
> 1 votes

---
Tags: opengl, graphics, shadows, linear-algebra
---


# Question
Title: How to move the camera to center an object in screen?
For example, an object is located at (x,y,z) in world space. Now how to calculate the **offset translation**, I mean **no rotation**, that will be applied to the camera so as to place the object at the center of the screen?

BTW, I'm using three.js r91. But pseudo code/C++/C# is also OK.

# Answer
> 1 votes
If you want to move the camera a certain distance from an object, and looking at the object, while preserving the camera's rotation, just move the camera at the object's location, then translate on the +Z axis (or -Z, depending where your camera is looking at).

```
camera.position = object.position;
camera.Translate(0, 0, -r); // where `r` is the desired distance

```

# Answer
> 2 votes
You need to position the camera relative to the object using the negative of its front vector (zAxis) multiplied by the distance you want.

```
var ignore1 = new Vector3();
var ignore2 = new Vector3();
var front_vector = new Vector3();

// get the direction the camera is pointing at
camera.matrix.extractBasis ( ignore1, ignore2, front_vector );

// put the camera at a negative distance from the object
camera.position.copy(object.position);
camera.position.addScaledVector(front_vector, -distance_from_object);

```

---
Tags: three.js
---


# Question
Title: Is there a general name to refer to a script attached to a particular gameobject in Unity?
I am making use of OnTriggerEnter(Collider other), is there a way to get access to the script attached to my other gameobject without explicitly writing the name of the script? my code is:

```
void OnTriggerEnter()
{
  other.attachedRigidBody.GetComponent<xyz>();
}

```

xyz is the name of the script attached to other, but I don't want to write xyz, but rather want to find a way to make my other gameobject implicitly look for whatever script is attached to it.

# Answer
I am not sure what are you planning to achieve with this, but here you go:

```
other.GetComponent<MonoBehaviour>();

```

Returns you a `MonoBehaviour` attached to the `other`. I am not sure which one, probably the first as seen in the editor. If you want to get all of the components, use `GetComponents<MonoBehaviour>()`.
> 2 votes

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


# Question
Title: My own coroutines waiting until finished from within a coroutine in C#
I'm using Unity but creating my own process that has it's own coroutine process. So I can't use StartCoroutine() but I'm interested in how that method works since it's easier to use than me getting the IEnumerator and stepping over it inside my function that's already called as a coroutine.

How can I create some kind of StartCoroutine() type function for users to use instead of having them step over the IEnumerator manually. So for example below I step over the IEnumerator Utilities.Wait() function manually. How could I just call that and have it do that for me and wait the specific amount of time?

```
public IEnumerator reduceHealth(dynamic args)
    {
        int result = Health - args.reductionValue;
        Debug.Log("Before health: " + Health);
        Debug.Log("Reducing health");

        // reduce health over time
        while (Health > result)
        {
            Health -= 1;
            Debug.Log("Health = " + Health);

            // how can I simplify this for users of this library
            var co = Utilities.Wait(2000);
            while (co.MoveNext())
                yield return null;
        }

        // snap to end result
        Health = result;

        // tell everyone we've been hurt!
        //onHurt.Raise(new { value = health });
    }

public class Utilities
{

    public static IEnumerator Wait(int ms)
    {
        var watch = System.Diagnostics.Stopwatch.StartNew();

        long lastTime = watch.ElapsedMilliseconds;
        while (watch.ElapsedMilliseconds <= lastTime + ms)
        {
            yield return null;
        }

        watch.Stop();
    }
}

```

# Answer
I don't think you should implement a delay like this -- if you have a lot of things waiting then effectively you have a lot of busywork stepping into each one and waiting for it to do nothing and return.

The standard way to do this in C# (that isn't the Unity Coroutine stack) is to use `Task<T>` and `await` instead of `IEnumerable` and `yield`, since that gets you the core Task event loop, which can use efficient abstractions based on TimerQueue and IOCP:

```
public async Task reduceHealth(args) {
    log("Taking damage!");
    while(health > target) {
       health -= attackvalue;
       log("current health {0}", health);
       await Task.Delay(2000);
    }
    health = target;
    log("I've been attacked!");
}

```

---

If you still want to build your own Coroutine machinery on generator expressions, you could build a core "event loop" thread that runs your coroutines, so your IEnumerables can return some kind of `Task`-like value that it can interpret.

I've added a TIO demo showing a basic POC of how you can build such a system. I'd still recommending sticking with existing coroutine solutions, but the general idea is to model Task-based composition and delays using subclasses of Task:

```
// example function
static IEnumerable<MyTask> reduceHealth(int health, int target, int atk) {
    Console.WriteLine("start");
    while (health > target) {
        Console.WriteLine($"{MyDelayTask.sw.Elapsed} health: {health}");
        health -= atk;
        yield return MyDelayTask.Delay(100);
    }
    Console.WriteLine("done");
    yield return new MyFinishedTask();
}

```

Try it online!
> 1 votes

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


# Question
Title: how to get the 3rd index in a foreach iteration c#
here is my code

```
string[] strData = {"P  ","B  ","P  ","PB ","P  ",P  "};
string OriginalData ="";
 for(int i = 0; i < strData.Length; i++){
     OriginalData += strData[i];
     OriginalData += ",";
  }
string[] newNewData = strData.Split(',');
 //i want to get the 3rd index from inside the foreach
  foreach(string newStrData in newNewData){
      //display the 3rd index
  }

```

What i did here was split my string so that i can parse them 1 by 1 later for my conditional statement . what i want here is that i want to get the 3rd index inside of my variable `newStrData` .

# Answer
If you only have an `IEnumerator` and don't have an `IList` access, you can do this:

```
int i = 0;
foreach(string newStrData in newNewData)
{
    i++;
    if (i == 3)
    {
         //display the 3rd index
    }
  }

```

If you have `IList` access, *~~use a `for` loop~~* use the indexer as `newNewData[2]`.
> 2 votes

# Answer
Simply put: you can't. The concept of an index it's foreign to `Enumerator`s.

If you need an index, use a `for` loop instead, i.e.:

```
for (int i = 0; i < newNewData.Length; i++) {
    if (i == 2) {
        // Operate on newNewData[i]
    }
}

```

Note that the `for` loop is useless if you *only* need to do something with the third element of the array and nothing else with the others, of course, you can just access that third element directly with `newNewData[2]`.
> 1 votes

# Answer
In regular C# you a string is simply a char\[\] therefore you can do the following:

```
int index = 2;

char x = newStrData[index];

string x = (string)newStrData[index];

Debug.Log($"The item at the 3rd index is : {newStrData[index]}");

```

I honestly don't know which version of C# Unity uses but if it uses string interpolation you can do that without casting to string if you need to log it. Concatenation is typically frowned upon due to the immutability of strings and their memory cost if done a lot.

If it doesn't support interpolation you can do this to avoid concatenation:

```
Debug.Log(string.Format"The item at the 3rd index is : {0}", newStrData[index]);

```

Collections are zero-based for C# as well so to get the 3rd one in a collection you would need to get index 2.

If you wanted a range starting at a given index could use Substring();
> 1 votes

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


# Question
Title: How to apply a force to a wheeled veichle and make wheel rotate ?
I've a veichle with 4 wheel and 4 wheel collider.

My veichle is a toy.. so i would like to apply an impulse force (veichle rigidbody.addforce) to that veichle, move it and make wheel rotate...

How can i do ?

Thanks

# Answer
Here are your possible options:

# 1. Full Physics

Apply the correct frictions to all physics materials and use a torque on wheels to make them rotate and push the whole body along with themselves.

# 2. Semi-Physics #1

Apply a force to the body as a whole, make the wheels lighter so they rotate by themselves as the body moves.

# 3. Semi-Physics #2

Drive the body with physics but exclude the wheels from physics and drive them using your own code - preferably just as an animation.

# 4. No Physics

Drive everything by yourself. This is probably the most stable option, but you probably don't need that much stability.
> 2 votes

---
Tags: unity
---


# Question
Title: Why my canvas isn't showing anything after I put code in the loop for tile map?
My canvas stop showing anything when I want to display a tile 25 times. No errors. Here is the code:

```
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    image.onload = function() {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
    }
  }
}

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;

  this.image.onload=function(){
    var sprite = new StyleSheet(background, 16, 16);
    for (i = 0; i < 25; i++) {
      for (j = 0; j < 25; j++) {
        sprite.draw(background, 30, 30, 36, 36, i * 36, j * 36, 36, 36);
      }
    }
  }
  return this.image;
}

var background = new Loader("https://opengameart.org/sites/default/files/PathAndObjects.png");
console.log(background);

```

# Answer
> 1 votes
So I solved the problem by removing one of the `image.onload` functions. The problem was that I had them both in my constructor functions. And the one inside Loader constructor wasn't firing. Removed it from:

```
this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    image.onload = function() {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
    }
  }

```

---
Tags: javascript, sprites, html-canvas, tilesets
---


# Question
Title: How can I respawn enemies in Gamemaker Studio 2?
I know this may have been asked before but I would like an updated answer. So how do I respawn enemies in Gamemaker Studio 2?

Say I have an object called `objBullet` and an enemy `objenemy`; when they collide with each other I want the bullet to destroy the enemy, and the enemy to respawn after a few seconds. As a bonus, if you could tell me how to respawn the enemy in a new random spot that'd be awesome.

# Answer
Since your enemies are destroyed and don't respawn instantly, you need a different object to spawn them using a timer.

I implemented this minimal working example, in which every time an enemy is destroyed it notifies an object `objSpawnManager`, that will choose a random spot and create a new enemy there.

### Spawn locations

Every spawn point is identified by an instance of `objSpawn`, and the only thing it does is, well... *exist*. We place as many spawn as we want, because we want to recover their `x` and `y` position when we'll need them later. Spawn locations are stored in a *List* data structure in `objSpawnManager`.

### Enemy behaviour

When an enemy is hit (I simulated hit with a simple mouse click for simplicity) it destroys itself, then increments the value of variable `queue` of the `objSpawnManager`. This variable tells the `objSpawnManager` how many enemies are waiting for respawn yet.

### Spawn manager

The object `objSpawnManager` is in charge of the spawning system. Its variable `spawnTime` is the number of seconds for spawning a new enemy; `spawnPoints` is a *DS List* containing all `id`s of `objSpawn` instances.

This is how it works:

* **Step Event**: the manager checks if there are enemies waiting for respawn (`queue>0`); if so, it starts the alarm countdown if it isn't counting down already (`!(alarm[0]>=0)`, "alarm not working").
* **Alarm 0 Event**: get the `id` of a random spawn point from the *DS List*, then create a new enemy at such spawn location, finally decrease the value of `queue`.

And that's it. The rest of the code just sets up some variables, and takes care of freeing memory when objects aren't needed anymore.
> 2 votes

---
Tags: game-mechanics, game-maker
---


# Question
Title: Why is the sprite so offset from the physics body?
I'm trying to make a sprite object that has physics, but once the game runs the physics body is drawn at an unknown offset from the sprite, which varies based on the size of the sprites texture.

Physics Sprite class:

```
public class PhysicsSprite extends Sprite {
World world;
public Body body;

public PhysicsSprite(Texture texture, World PhysicsWorld, float x, float y){
    super(texture);
    this.world = PhysicsWorld;
    setPosition(x,y);
    setOrigin(getX(),getY());
    InitializeBody();
}

private void InitializeBody(){
    BodyDef bd = new BodyDef();
    bd.position.set((getX())/GameMain.PPM,(getX())/GameMain.PPM);
    bd.type = BodyDef.BodyType.DynamicBody;

    body = world.createBody(bd);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(getWidth()/2f/GameMain.PPM,getHeight()/2f/GameMain.PPM);

    FixtureDef fd = new FixtureDef();
    fd.density = 1;
    fd.shape = shape;
    Fixture fixture = body.createFixture(fd);

    System.out.println(body);
}

private void updateSprite(){
    setPosition(body.getPosition().x*GameMain.PPM,body.getPosition().y*GameMain.PPM);
    setRotation((float)Math.toDegrees((double) body.getAngle()));
}

@Override
public void draw(Batch batch){
    updateSprite();
    super.draw(batch);
}
}

```

physics world/rendering scene class:

```
public class TestLevel implements Screen {
World world = new World(new Vector2(0f,0f),true);

OrthographicCamera camera = new OrthographicCamera(GameMain.WIDTH/GameMain.PPM, GameMain.HEIGHT/GameMain.PPM);
Box2DDebugRenderer debugR = new Box2DDebugRenderer();
PhysicsSprite s;
GameMain game;
SpriteBatch batch;

public TestLevel(GameMain g){
    game = g;
    batch = g.batch;
    s = new PhysicsSprite(new Texture("badlogic.jpg"),world,300,500);
}
@Override
public void show() {

}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(.4f,0.4f,.4f,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    s.draw(batch);
    batch.end();

    debugR.render(world,camera.combined);
    world.step(Gdx.graphics.getDeltaTime(),6,2);
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

```

I've followed this tutorial and he mentions the sprite being offset but nothing occurs to him like whats happening here. I've tried to find someone with a similar issue but failed. Can someone help me out?

# Answer
I’ve figured it out. I needed to offset the body position down by half the screen height + half the sprite height and left by half the screen width + half the sprite width. And then do the opposite to the sprite position in the update sprite method.
> 0 votes

# Answer
```
 BodyDef bodyDef = new BodyDef();

float offsetX =  ((getX() +   ( getWidth() / 2 ) ) / GameInfo.PPM ) ;
float offsetY =  ((getY()  ) / GameInfo.PPM ) ;

bodyDef.position.set( offsetX ,offsetY) ;
// bodyDef.fixedRotation = true ;

bodyDef.type = BodyDef.BodyType.KinematicBody ;
body = game.getWorld().createBody(bodyDef) ;

PolygonShape shape = new PolygonShape();

float boxWidth = ((getWidth() / 2) / GameInfo.PPM ) ;
float boxHeight = (((getHeight() ) / 2)  / GameInfo.PPM ) ;

shape.setAsBox(boxWidth ,boxHeight );
//shape.setRadius(0.5f);

FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density  =2f ;
fixtureDef.friction  =0.5f ;
fixtureDef.shape = shape ;
fixtureDef.isSensor =true;
Fixture fixture =  body.createFixture(fixtureDef) ;
fixture.setUserData(this);
shape.dispose();

```
> 0 votes

---
Tags: libgdx, physics, box2d
---


title: Creating terraced terrain

text:
# Question
Title: Creating terraced terrain
Let's say I have a heightmap, but I want to create flat areas on it. The easiest solution would be to just say that every value between 0.2 and 0.4 should just become 0.3, but to keep the terrain continuous, I need to make sure that the values below 0.2 are mapped between 0 and 0.3 and the values above 0.4 get mapped between 0.3 and 1

So if we make a diagram, where the x axis is the value and the y is the outcome, then we get this:

This is fine when you have only 1 flat area, but if I'm trying to recreate something like a farmland in Peru, I have to create a lot of these:

So how can I create an efficient function, which given a value and an array containing the from and to values of the flattened areas transforms the value in the new system.

For instance, using the same example, a value of 0.25 would return 0.3 and a value of 0.5 would return 0.41666....

# Answer
Does not seem to be as complicated as it looks like to implement the algorithm you suggested. The complexity of *log(n)* is also most likely an optimal one. In order to re-iterate:

1. Find the lower bound of value
2. If it is odd index, terrace was hit and average of two adjacent values is returned
3. If it is even index, rescale the value onto interval between two adjacent pairs (terraces)

The input is just sorted pairs of the clamped intervals of terraces. As a bonus adding doubled bounds will catch edge cases:

```
std::vector<float> terrace { 0.f, 0.f, 0.2f, 0.4f, 1.0f, 1.0f };//example input
float map_terrace(std::vector<float>& intervals_bounds/*sorted!*/, float value)
{
    auto right = std::lower_bound(intervals_bounds.begin() + 1, intervals_bounds.end(), value);
    auto left = std::prev(right);
    if ((right - intervals_bounds.begin()) % 2 == 1)
        return (*left + *right) / 2.f; //hit terrace
    else //hit slope
        return remap_interval(value, *left, *right,
        (*std::prev(left) + *left) / 2.f, (*std::next(right) + *right) / 2.f);
}

```

where `remap_interval` is standard utility function remapping value from one interval onto another:

```
inline float remap_interval(float value, float min1, float max1, float min2, float max2)
{
  return ((value - min1)/(max1 - min1))*(max2 - min2) + min2;
}

```

The algorithm allows arbitrary and/or uneven spacing between terraces.
Try it online!
> 2 votes

# Answer
As an analogy to your graph, I submit

$$min(slope * mod(x, 1), 1) + \lfloor x\rfloor$$

http://www.wolframalpha.com/input/?i=plot+(min(5+\*+mod(x,+1),+1)+%2B+floor(x))+from+x%3D-5+to+5
> 1 votes

---
Tags: mathematics, heightmap
---


# Question
Title: My sprite is not listening to any keyboard keys
First time ever creating html canvas game. Once I finally got my sprite ant tiles drawn on the canvas, now I want to make my sprite interactive. Unfortunately, for some reason it is not working. I get a message in console when the certain key is pressed but the sprite is not changing its position. I wonder why? The code:

```
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var mapArray = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
  }
  this.drawimage = function(image, x, y, width, height) {
    context.drawImage(image, x, y, width, height);
  }
}

/* Initial Sprite Position */

var boatPosX = 230;
var boatPosY = 200;

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;
  this.image.onload = function() {
  var sprite = new StyleSheet(background, 36, 36);
  var ship = new StyleSheet(boat, 90, 100);
  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[i][j] == 0) {
        sprite.draw(background, 190, 230, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
      if (mapArray[i][j] == 1) {
        sprite.draw(background, 30, 30, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
      if (mapArray[i][j] == 2) {
        sprite.draw(background, 200, 20, 26, 26, i * sprite.width, j * sprite.height, sprite.width, sprite.height);
      }
    }
  }
  ship.drawimage(boat, boatPosX, boatPosY, 50, 50);
}
  return this.image;
}

/* Sprite controls */

function move(e) {
  if (e.keyCode == 39) {
    boatPosX += 2;
    console.log("works");
  }
  if (e.keyCode == 37) {
    boatPosX -= 2;
  }
}

  document.onkeydown = move;

var background = new Loader("ground.png");
var boat = new Loader("ship.png");

console.log(background);

```

# Answer
These aren't magic object, you need to draw them every frame to animate them. You should look into a game loop pattern to learn about it, but in short:

1. You should have a function, which draws everything and a function, which updates everything
2. You should be calling these every frame

Something like this:

```
function loop() {
    update();
    draw();
    // This waits until the next frame (depends on your monitor) and calls the function
    // This is not the same as simply using loop(), that will cause an stackoverflow error
    // and never lets the CPU sleep
    requestAnimationFrame(loop);
}
loop();

```

In the draw function you need to clear the canvas and draw everything again.
> 0 votes

---
Tags: javascript, sprites, html-canvas, keyboard
---


# Question
Title: Is there any specific reasons to include clearly inferior options in a game?
# Games contain inferior options

A lot of games that I have played contain some optimal options and some *clearly inferior* ones. Sometimes, like in *Heroes of Might&Magic IV*, it could happen due to the limited time the developers had to balance it (e.g. Academy benefits so much more from choosing Gold Golems and then Genies rather than Magi and Naga that there is no reason to go the second way).

# Sometimes it happens for no apparent reason

However, it often happens that the developers clearly had enough time to polish the game, didn't go bankrupt after its release etc., but it is still full of "trap" options that sound cool, but are actually inferior to something always available in the same situation, or almost always available in similar situations.

There are just so many examples of such, almost every game has something like that. For example, *Age of Wonders I* began a successful series thga, but a lot of abilities to be chosen for the heroes are clearly underperforming, and a lot of units have clearly better alternatives on the same levels in the same factions.

It is important that while some very overpowered stuff often gets nerfed (like it also happened in AoW I), the obviously underpowered choices often stay as they are (as it also happened there).

So, I ask: **Why do game developers create clearly inferior options in their games and don't rebalance them? Is it intentional? If it can be avoided -- how?**

# Answer
> 9 votes
Not all players are the same, also not all players play rationally. I'm not very familiar with the specific instances you mentioned, but sometimes there are choices that seem inferior at first, but reward you later.

**The player is more careful and pay more attention.** If all choices are equally powerful, what exactly are you choosing? Why are you given a choice? If in the past you've been given 1 choice out of three, where 2 of them were inferior, doesn't that mean in the future you should pay attention not to make the wrong decision in a similar dilemma?

**Players like to immerse in a game world**. A player might choose to not accept gold from the poor villagers, because they feel bad for them, but another player might accept it, which seems rational. A player might also decide to get a fire spell that causes slightly less damage than an ice spell, but they are a fire wizard after all.

**It's fun.** Think of it like in pokemon, there's a lot of pokemon that are just weaker, and no matter how much you train them, they will never be able to beat the stronger ones. But it's fun to use them in battle, because they have that one ability or skill that makes them unique and fun to play.

# Answer
> 4 votes
When you give the player multiple choices but one is clearly inferior to the others in every way, then you often have a case of bad game design. Either the game designers made a misjudgment in their design, greatly over- or underestimated the usefulness of a certain game element and then were too committed to the idea to scrap it. Or they just didn't testplay the game enough to figure out the obvious balance problems.

The only way to prevent such balance problems from creeping into your game is **playtesting, playtesting and more playtesting**. Get as many testers as you can and let them test your game until they figured out which strategies work and which do not. Analyze the test sessions, tweak your game, and repeat. Again and again until you run out of budget and are forced to release. Also, don't always test with the same people. Get new testers on-board regularly to get a fresh perspective on the game. A new player might try something nobody tried before and surprise you all with figuring out a glaring loophole in your game mechanics.

But sometimes bad game options can be intentional. Extra Credits mentioned some niche case where having an inferior option makes sense:

* The developers want to make choosing the right option a puzzle game with one correct solution. The player is supposed to find the clearly superior option on their own and feel good about themselves when they found it.
* You want to teach the player early in the game about how to tell good options apart from bad options. But that's nothing you should encounter with late game options.
* You provide a sub-par option for players who look for a challenge-run. A player who beat the game and looks for a greater challenge might try beating the game using only the most underpowered units.

But there is another possible answer. Maybe the option you are looking at isn't actually as underpowered as you think.

* Does the option have a hidden benefit which is not immediately apparent?
* Is there some special situation where it outperforms the other options?
* Is there some non-obvious synergy with other game features which suddenly make it far more powerful if used correctly?

A lot of hidden depths can sometimes lurk in an option which seems inferior at first glance.

# Answer
> 4 votes
It depends on the type of game you're playing, and I'll try to avoid overlap with others here:

* **Player Skill Separation**
In Magic: The Gathering there are cards sometimes nicknamed "noob traps"; these are usually Life-gain cards. While affordable in mana-cost, these are card-disadvantage cards that offer no trajectory towards winning. In drafting and sealed especially, these will cause players with a low skill level and understanding to make their deck worse inherently by choosing low value cards.
* **Chance Based Acquisition**
In Magic: The Gathering, Pokemon, and many other games; you don't have the same chance to acquire items/creatures all the time. It's much easier to get a Hypno than an Alakazam so Alakazam is better (in ways that tend to matter.) In Magic, rare cards tend to be both more complex and more powerful, in part because during Drafts you want some "bomby" cards.

You might be thinking "that's dumb"; but people need variance in order to justify losing. It's a highly important pair of things required for a successful game:

* A) That you have a chance of winning. This requires variance so that even a skilled player may lose to an unskilled player sometimes. It's even inherent in rats (study found: ncbi.nlm.nih.gov/pubmed/7250521 thanks to Theraot) that they'll stop wrestling if they don't win 30% of the time or so.
* B) Additionally, humans are more likely to keep playing if they can blame the loss on luck. "Aw man, if only I'd drawn that \[blorp\]", "You only won because you just drew \[sclub\]", "I only lost because the packs I opened were garbage"

You see, this mentality, regardless of it's occasional accuracy, means you're willing to play again because it wasn't your skill that caused you to lose, it was just that you rolled too many ones (literally or figuratively.) Notice the popularity of PUBG; it exhibits both Skill Separation in the sense that you learn what to use and what to throw away, chance based acquisition, and of course is addictive (in part) because "if I had just found a \[blipt\] I would've been fine. Stupid game."

* **Specialization**
Often times people will claim that something is inferior but not realize that it does have niche use or a specific strategy that can be employed with it. In 40k, Lootas and Tankbustas (in the 4th ed Ork codex) were an example of this. Lootas were good against most vehicles and had no real drawbacks. Tankbustas were good against all vehicles, but had less average damage against the less-armored ones, and had a significant drawback. For people like myself, I found this drawback worth mitigating because their power-level against many targets was several times better. When those targets are what you're worried about it's worth paying the penalty. To most people, however, it was clear that Lootas were the best, end of story.

---

EDIT:

* **Financial Incentive**
Financial incentive is also a cause at times. In the 40k example when the Carnifex was initially released it was very under-priced and the army allowed 6 of them. This newer model and it's ability to allow (essentially) 6 heavy support slots created an entire trend for the army called NidZilla; where 6 Carnifex, 2 Hive Tyrants, and then a few troops choices for scoring or walling off opponents were the trend.

The next codex they nerfed Carnifex to nearly double the points (from mid 80s to 160-200), nerfed Hive Tyrants a bit, then a Trygon was added with double the Hit Points (around 200 pts to purchase) and a higher power level in general (attacks, initiative, deep striking, etc) at the same time they created the Tervigon as a troops choice in a similar price range as the Fex but the Terv also created dudes.

Suddenly you had scoring Monstrous Creatures that created more scoring units, and you had better Heavy Support choices; both competing for points and slots with the Fex. This is hardly the only time this has happened in 40k; and hardly the only race. It happened with Flyers in general, Space Wolves, Blood Angels, Tau (multiple times), Necrons (multiple times), a general cheapening of units to include more models in your army, and a price hike on anything that was a common choice even when it was a balanced option (Sluggas and Shootas were both viable in different scenarios, Shootas have been nerfed in both points and effectiveness.)

While I can't claim *for sure* that this was a marketing ploy, it certainly looks like exactly what you'd do if it was a way to sell the newer models and obsolete the old ones. Regardless of it being the case for 40k, it's going to be a case for some games.

* **Purposeful Meta Game**
Again, for Mtg as an example, units and sets can be released with a purposeful expectation of what a meta-game will look like; and it may be that these units are just there as clutter for you to dig through in order to find the optimal choices. They are still choices and may serve some other metagame purpose (a unit that's good against a set of units that are not useful for the intended metagame, intended to snuff out attempts to curb the metagame into something less desirable.)

See Innistrad. They wanted a metagame of Tokens, token-buffers, and some grave-strategies for longevity; but in case it was too much they included Rest in Peace, Deathrite Shaman, Grafdigger's Cage, Dryad Militant, and other grave-hosers in standard (over time) in order to be sure that the non-grave decks stood a chance. Snapcaster was a high enough power level to keep some level of grave recursion on the map and is one of the obviously best cards ever printed. Note that this ties in with Financial Incentive above.

* **Legacy Units and Power Creep**
By power-creeping here and there, things are "exciting" for current users. If everything new is average or below average, or at best a lateral upgrade, users won't be incentivized to purchase it or expand their collection. But if it is grossly powerful (or at least *looks* grossly powerful) people will purchase a lot of product to get their chase rares, to capitalize on the secondary market, or to be sure they're able to compete in the new metagame.

Even in RTS, they don't tend to add *bad* units; but rather things that you say "holy crap, I can detect stealth units reliably now?", "I now have a mobile unit that can harass their economy?" etc. It has to be "unbalanced" in some aspect in order for it to be interesting; and hopefully you just balance it in such a way that your old units aren't completely obsolete. See Reapers for Nod in Tiberian Sun. Reapers were a strict upgrade to basically everything. A self-healing, anti-air, good against all targets unit that could create a ball-of-death much easier than before. That's exciting.

Stealth tanks, tick tanks, etc were still useful; but the feeling of having a self-sufficient unit was big; and it was clearly unbalanced in the roles it was made for (end-game ball-of-death stuff.) No more did you use Tick Tanks for that.

# Answer
> 1 votes
While the other answers so far give some excellent reasons, I can think of a few more:

* **To give the illusion of choice**. Often, designers want a more controlled, guided experience for players. Those players, however, want to feel in control. One way to make both possible is for the designers to offer a choice that is imbalanced enough that they can predict what players will choose. The players get the best experience through the outcome that designers gave the most focus, but they also don't feel like they *had* to make that choice.
* **To make the game seem bigger than it really is**. If there is a fork in the road, and you choose one road, you may never know where the other road leads. If the road you followed led to a large city, you can only assume the other road led to something just as large. You would never know that the other road just dead ends as soon as it passes out of view. Game designers want to immerse a player in a world, but making an entire world isn't easy. Why not hide a game's lack of detail by discouraging players from getting too close? If the dead-end road is obviously the wrong road, most players, at least on a first play-through, will not know that it dead-ends.
* **To offer a new challenge**. Just because one choice is obviously better does not mean the alternative is not fun. Players will often handicap themselves for the thrill of winning at a disadvantage. Picking up the heart container after clearing a dungeon instead of ignoring it is obviously the better choice, yet many Zelda players still try the 3-heart challenge.

---
Tags: game-design, balance
---


# Question
Title: Why the renderers Renderer[] array are all null?
```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightsEffect : MonoBehaviour
{
    public List<UnityEngine.GameObject> waypoints;
    public int howmanylight = 5;
    public Generatenumbers gn;
    public bool changeLightsDirection = false;
    public float delay = 0.1f;

    private List<UnityEngine.GameObject> objects;
    private Renderer[] renderers;
    private int greenIndex = 0;
    private float lastChangeTime;

    private void Start()
    {
        //waypoints = new List<UnityEngine.GameObject>();
        objects = new List<UnityEngine.GameObject>();

        if (howmanylight > 0)
        {
            UnityEngine.GameObject go1 = UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere);
            duplicateObject(go1, howmanylight);
            LightsEffects();
        }
    }

    private void Update()
    {
        LightsEffectCore();
    }

    public void duplicateObject(UnityEngine.GameObject original, int howmany)
    {
        howmany++;
        for (int i = 0; i < waypoints.Count - 1; i++)
        {
            for (int j = 1; j < howmany; j++)
            {
                Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
                UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity);
                go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
                objects.Add(go);
            }
        }
    }

    private void LightsEffects()
    {
        renderers = new Renderer[objects.Count];
        for (int i = 0; i < renderers.Length; i++)
        {
            renderers[i] = objects[i].GetComponent<Renderer>();
            renderers[i].material.color = Color.red;
        }

        // Set green color to the first one
        greenIndex = 0;
        renderers[greenIndex].material.color = Color.green;
    }

    private void LightsEffectCore()
    {
        // Change color each `delay` seconds
        if (Time.time > lastChangeTime + delay)
        {
            lastChangeTime = Time.time;

            // Set color of the last renderer to red
            // and the color of the current one to green
            renderers[greenIndex].material.color = Color.red;
            if (changeLightsDirection == true)
            {
                Array.Reverse(renderers);
                changeLightsDirection = false;
            }
            greenIndex = (greenIndex + 1) % renderers.Length;
            renderers[greenIndex].material.color = Color.green;
        }
    }
}

```

In this line if for example objects count is 5 then there will be 5 renderers but they will be all null.

```
renderers = new Renderer[objects.Count];

```

# Answer
Because `Renderer` is a reference type.

In C#, creating an array of any reference type initializes all entries in that array to `null`. To give these newly-created entries other values, you have to do so explicitly.

Note that you appear to be trying to do so in the code that follows immediately after:

```
for (int i = 0; i < renderers.Length; i++)
{
    renderers[i] = objects[i].GetComponent<Renderer>();
    renderers[i].material.color = Color.red;
}

```

On the surface, this is correct and should result in `renderers` containing five non-null references *assuming* `GetComponent` is not itself returning null. If it is, your attempt to access `renderers[i].material` is going to throw an exception.

If that's the ultimate behavior you are seeing, you probably have a bug in that `objects[i]` doesn't have a `Renderer` component. It's probably not set up correctly or is not the object you expected, for example.

If you're not seeing a `NullReferenceException`, and you're just looking at `renderers` in the debugger immediately after the `new` but before you've executed that `for` loop, then everything is as it should be.
> 2 votes

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


# Question
Title: Implementing an enum from an abstract class
Both my Player class and Enemy class should have an enum called State. (The values inside of that enum would be different in each class.) I'd like to have the Player class and Enemy class inherit from an abstract base class that would *require* those two classes to have that enum. Is this possible?

# Answer
No, this is not possible.

If your two enums define different sets of values, then they must be two different types, and C# does not have a concept of inheritance for enums, so they can't descend from a common parent type that could be described in the abstract class.

The closest you can do is something like...

```
public abstract class StatefulBehaviour : MonoBehaviour {

    // Hold a backing integer as a go-between for all different state types.
    private int _state;

    // Caller tells you what type of state they're expecting - convert to that.
    public T GetState<T>() where T: struct, System.IConvertible {
        System.Object state = _state; // Boxing! Ewwwwww....
        return (T)state;
    }

    // Caller gives you a state of a particular type - convert it to lingua franca.
    public void SetState<T>(T state) where T:struct, System.IConvertible {
        _state = System.Convert.ToInt32(state);
    }
}

```

Then your player could look something like this:

```
public class PlayerMovement : StatefulBehaviour {

    public enum PlayerState : int {
        Idle,
        Walking,
        Running,
        Climbing,
        Jumping,
        Falling,
        Dead
    }

    public void Jump() {
        SetState(PlayerState.Jumping);
    }

    public bool IsDead {
        get {
            return GetState<PlayerState>() == PlayerState.Dead;
        }
    }

    // Etc.
}

```

This means it's on you to police that you're using the right state type consistently for each object - since unrelated states from different objects might map to the same integer. (You could add some debugging support here - in development builds, have StatefulBehaviour cache the last type it was set with, and complain if someone tries to set or get a state of a different type)

---

Myself, I'd be tempted instead to take a composition over inheritance approach if you want shared state management logic between multiple different component types. That way you don't have a bottleneck where every bit of logic with states needs to inherit from a single base class.

* Introduce a State component type.
* Anything that needs states can `[RequireComponent(typeof(State))]` to ensure it has a state component attached.
* The State component references a (shared) collection of states - possibly using a type object pattern so you can define your states in data rather than enum code files
* The State component holds a current value, maintaining the invariant that it's always a member of the referenced collection.
* You can add a State component to any object via the Inspector, and configure which collection of state values it should draw from. (This makes it easy to, say, re-use a common set of states between all switch & trigger objects, even if they have different activation logic)

Or you could go even further, where each of your individual states is its own object, with references to the states it can transition to. Then you have a state machine graph not unlike the one used by Unity's Mechanim animation controllers. Now the idea of a "collection" of states is implicit in the connectivity of the graph, and the only difference between a PlayerState and an EnemyState is that they're not reachable from one another.
> 3 votes

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


# Question
Title: get the 3rd column value of a multi dimentional array c#(UNITY)
here is my code

```
string[,] table = new string[104,6];
int xIndex = -1;
int yIndex = 0;
string newPrevious = "placeholder";

string[] strData = {"P  ","B  ","P  ","PB ","P  ",P  "};
string OriginalData ="";

IEnumerator Win_Log(){

     for(int i = 0; i < strData.Length; i++){
        OriginalData += strData[i];
        OriginalData += ",";
     }
     string[] newNewData = strData.Split(',');

     foreach(string newStrData in newNewData){

     if(table.GetLength(0) < xIndex){
     break;
      }
   }
}

```

what i am trying to achieve here is that i need to compare the 3rd column of the table and check if there's a value on the 2nd row of the third column so something like this

i have table \[104,6\] so what i need to compare is table\[3,1\] and table \[3,2\].

how can achieve that

# Answer
There is somewhat a way of doing this dude.

```
int i = 0;
int j = 0;
string[,] strArr = new string[2, 3];

strArr[0, 0] = "First";
strArr[0, 1] = "Second";

strArr[1, 0] = "Third";
strArr[1, 1] = "Fourth";

for (i = 0; i <= strArr.GetUpperBound(0); i++)
{
    for (j = 0; j <= strArr.GetUpperBound(0); j++)
    {
                MessageBox.Show (strArr[i, j]);
    }
}

```
> 0 votes

# Answer
Quick Google search gleans the gleans this.

I know when I started programming it was sometimes tough to word a question correctly for Google to give you the answer you are looking, however, it appears you may not be taking that step first.

There are a number of ways to do this and that answer from SoF should give you enough direction to get what you require.

The basic "Introduction to Programming 101" solution is to do a nested loop:

```
for (int i = 0; i < UPPER; i++)
            {
                for (int j = 0; j < UPPER; j++)
                {
                    //compare arrayA[i] to arrayB[j];
                }
            }

```

LINQ is one way... this can be expensive in some cases:

```
hasDuplicates = a.Intersect(b).Any();

```
> 2 votes

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


title: Referencing a Text in Unity Error

text:
# Question
Title: Referencing a Text in Unity Error
I am working on trying to add a coin system to my game. I have it setup right now so that when the player hits a coin the score text goes up by 1. I have setup a reference in the script, which is attached to the coin, to the score text in my scene. In the game the player can click a button that will switch between two lanes to avoid enemies. These lanes are infinte and in these lanes is where I put the coins. And when a new lane is created the reference to the text disappears from the coin and teh tect does not change. I am not sure why the reference is disappearing.

Here is the coin script that is on the coin

```
public int scoreToGive = 1;

public Text coinText;

void OnTriggerEnter2D(Collider2D other)
{
    if(other.gameObject.tag == "Player")
    {
        AddScore();
    }
}

public void AddScore()
{
    TheScore.theScore++;
    if(coinText != null)
    {
        coinText.text = TheScore.theScore.ToString();
    }

    Destroy(gameObject);
}

void Update()
{
    coinText.text = GameObject.FindGameObjectWithTag("Ui").ToString();
}

```

}

Thanks to anyone who can help!

# Answer
From what I get from your problem, is that each coin has a reference to the Text, your code does not say it, but I want to guess that you instantiate them in run time.

So the problem would be this: when you reference an Object (be it a **GameObject**, **Transform**, or any other component), if it is an object instance belonging to a scene, the reference will be loss one either of them move from that scene, in the case of prefabs the same happens, you may apply changes with a scene object's reference but it won't be saved on the prefab located in the project's folder.

So, what you can do, is to instead have a controller GameObject that holds instantiable objects' references, so when you instance a Coin, that controller passes the needed Text, example (all scripts should be on different files):

```
public class ReferenceInjector : MonoBehaviour
{
    public Text coinText;
}

public class Coin : MonoBehaviour
{
    public Text text;
}

public class Game : MonoBehaviour
{
    public ReferenceInjector injector;
    public Coin coinPrefab;

    public void CreateCoin(Vector3 position)
    {
        Coin newCoin = Instantiate(coinPrefab, position, Quaternion.identity) as Coin;
        newCoin.text = injector.coinText;
    }
}

```

Hope it helps.
> 1 votes

# Answer
When it comes to updating the UI, I personally like using the singleton pattern.

```
public class MyUserInterface : Monobehaviour
{
    public static MyUserInterface instance;

    public Text score;

    void Awake()
    {
         if (instance == null)
              instance = this;
         else if (instance != this)
              Destroy(gameObject);
    }
}

```

If you add this component to any gameObject and set the reference to the Text on the inspector, you can access the Text from anywhere in your code by using the following line:

```
MyUserInterface.instance.score.text = "Your text here";

```
> 0 votes

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


# Question
Title: How do I prevent reimport when switching between computers using Unity3D Portable?
I use Unity Portable on a passport drive where my projects are also stored. How can I prevent Unity Portable reimport all assets from a project stored on the same passport drive when I change the PC I'm running both on?

# Answer
> 2 votes
You need to make sure your external drive acquires the same drive letter & path every time before launching Unity.

---
Tags: unity
---


title: How to use discord-rpc with GMS 2?

text:
# Question
Title: How to use discord-rpc with GMS 2?
I want to add Discord Rich Presence to my game using discord-rpc but I don't know how to do this?

# Answer
> 1 votes
According to this page GMS 2 can use DLLs on Windows, SO-files on Linux and DyLib files on Mac.

So, what I'd suggest is creating a DLL in C++ that offers easy-to-use functions that you can call from your GMS scripts. You could probably try to also expose the whole Discord RPC SDK as a DLL, but I feel like you might be better off simply creating a wrapper around it, since the SDK relies on pointers, and I'm not sure how you'd use those in GMS scripts. Here's a video I found about creating a DLL to be used with GMS.

This is a little hard given that the SDK uses callbacks for some stuff, but if all you want to do is to display information about the game in the user's Discord profile, this is actually quite easy to do, as you can ignore the callbacks. Just create a high-level function that sets the details in `DiscordRichPresence` like you want and then passes it to `Discord_UpdatePresence`.

---
Tags: c++, game-maker
---


# Question
Title: What API is used and not used when DirectX 11 feature level is less than 11_0?
Currently, I am programming a DX11 engine using feature level 11\_0+. I am wondering if I wanted to extend support for DX10, and DX9, what else would I have to do differently?

If I make the feature level 9\_1, what API calls/shader versions would have to be changed? Would I still be able to use all of DX11 API? If not, is there a list of API that is used and not used based on feature level?

# Answer
> 1 votes
Documentation: Direct3D feature levels.

There's quite a bit here and it's not really suitable for copy/pasting into an answer, so you really should go read it yourself.

However, and to summarize, the ID3D11Device and ID3D11DeviceContext interfaces are still used, so it's the D3D11 API that is used, but under lower feature levels certain limits may be smaller and certain API calls, formats, behaviours, etc may be different or not allowed at all.

These are summarized in a table at the linked article.

---
Tags: directx11
---


# Question
Title: How did older games manage their sprites?
I’m aware that older games would reuse sprites as much as possible (Like the bushes and clouds in Mario, or slime and red slime in dragon quest), how did they manage their sprites? Did they preload everything at the beginning, or did they load and unload as needed?

I had assumed the latter, but many games on the seas genesis, snes, gbc, etc have a sprite test mode which leads me to believe that they simply preloaded everything. Or is it possible that they used a combination of the two?

# Answer
Reusing sprites is a different thing than loading everything from the beginning. Both techniques are used either together or separate.

The example you mentioned with clouds and bushes simply means that the game loads one sprite (the cloudy-bush thingy) and uses it to draw both the bushes and the clouds. So only one sprite exists in memory, but multiple things are drawn on the screen (with some colour alternation).

Preloading everything from the beginning is another issue. In some cases you don't have the luxury of a good CPU to load a lot of data on the fly, so perhaps it is better to load everything on the beginning, especially if the game is small. It is also cheaper to include multiple sprites into a single texture, so if a game (like the old ones) is small enough to fit all sprites in a texture, then they load everything anyway.

What should you use? In today's hardware, nobody really comes to that issue. If you use a library to handle graphics for you, then you only declare when you will use them, and it's the library's responsibility to decide when to load them.

Unless you are advanced enough to want to make games for older consoles with harder programming languages like assembly, such a person would know how to load graphics manually depending on the platform.

For more information it would be better to ask the teams that actually made older games.
> 0 votes

---
Tags: textures, memory
---


title: Networking Board Game Design Pattern

text:
# Question
Title: Networking Board Game Design Pattern
I am currently working on a board game in Java with libgdx. It is supposed to be a multiplayer game, that you can play across multiple computers and for the sake of simplicity, I use kryonet.

Even though I assume my friends are no cheaters, I want all the game logic to happen on the server. This is for learning purposes, so I get to know a clean approach of anti-cheating.

However, I have been looking for design approaches for days now and really can't get my head around how I am supposed to handle actions, their verifications and distributions. You can think of the game as turn-based and similar to Monopoly, it especially has some sort of randomness (drawing event-cards).

At first, I came across FSM and thought it would be a perfect approach, because I could easily let a state process the input and send a corresponding package to the server, who does the validation and broadcasts it to the other clients, who then.. Yeah, what do they do with it? Simply updating the model (as of "Player 1 is not at tile 8) doesn't make too much sense, because I would then not have any actions, such as walking, state transitions, etc. (the game is running in an update method, with a delta parameter, so you usually step your game forwards here).

The second approach I came across was an "action" approach, that strongly discouraged the use of a FSM, because they would easily get too big and too complicated to understand later on. Every Action would have an "isvalid()" function, so the server could check the model for the action to be legal and then broadcast it to the clients to "take action" (pun intended). Here again, I feel the need of a FSM on the server side, so I can validate, whether an action would be legal or not.

Do you think it is fine to mix two approaches? Is there an major point in my understanding of the approaches, that is entirely wrong and leads me to some misconception?

Thanks in advance and have a good weekend!

# Answer
I am currently doing something similar, and would advise to use FSM as much as possible, in combination with actions.

On the server side, where the game logic is resolved, use FSM where transition from one state to another is triggered by an action from a player (or an external event such as a timeout).

On the client side, it makes sense to be able to render the current game state without performing all actions that led to this state:

1. When a player reconnects after a disconnect.
2. When a user can "watch" a game in progress.

But indeed for showing transitions it is useful to not only send the new game state to the client, but also the details of the action that led to this new state.
> 1 votes

---
Tags: libgdx, design-patterns, turn-based, board-game
---


title: Import 3D model into Unreal Engine 4

text:
# Question
Title: Import 3D model into Unreal Engine 4
*(Sorry if I misunderstood the context of what I want, I'm currently noob in game development).*

I want to retrieve a 3D model from let's say Saints Row 3, and import it to Unreal Engine 4, is it possible ? If not is there a way to create it from scratch ?

What is the right way to achieve what I want ?

# Answer
> 1 votes
Extracting assets from other games is not impossible, but you may find that game developers are reluctant to tell you how or make it easy for you.

That's because even if you've purchased a copy of a game and customized your own character, the underlying mesh and texture data that character uses are the products of other peoples' artistic and technical labour.

Legally, the copyright or licensing rights for those assets are owned by the creators or their studio/publisher (depending on the details of the agreements involved)

So, if we tell you how to extract this data, we're potentially making it easy for less scrupulous visitors to this site to steal content that belongs to us and our fellow developers.

There may be reasons to use this data that are protected under "Fair Use," but we can't guarantee that anything we write here will be used only in this way.

I'd recommend checking into game modding forums if you'd like to explore this further, with a caution to please use your powers only for good. :)

---
Tags: 3d, 3d-meshes, unreal-4
---


# Question
Title: How do I get the InputManager to recognize a certain axis/Vector2D with a Vive motion controller?
Right. So basically I want to map the Vive motion controller touchpads (certain locations) to the certain inputs in Unity's InputManager. How do I do this? Like I want a certain area on the touchpad to equate to forwards/backwards in the InputManager. How would I do this? I am not seeing a way to do it natively.

Long story short I'm wondering if I can use the Vive with the InputManager or not.

# Answer
> 1 votes
Unity's `InputManager` isn't well suited for this task, I strongly recommend interfacing directly with the APIs that `SteamVR` provides for Unity games:

`SteamVR_Controller.Device.GetAxis` is most likely going to be the easiest way to get the behavior you want:

```
public Vector2 GetAxis(EVRButtonId buttonId = EVRButtonId.k_EButton_SteamVR_Touchpad)

```

So to treat it like a joystick (for the most part):

```
// I assume you have a SteamVR_Controller.Device named `device` available:

// Is the touchpad being touched?
if (device.GetTouch(SteamVR_Controller.ButtonMask.Touchpad))
{
    // This will fetch the Axis of the Touchpad by default.
    Vector2 touchpadPosition = device.GetAxis();

    // this is nearly identical to the behavior of Gamepads
    // treat touchpadPosition like the vector form of:
    // float x = Input.GetAxisRaw("Horizontal");
    // float y = Input.GetAxisRaw("Vertical");
}

```

I used `GetAxisRaw` instead of `GetAxis` as an example because SteamVR will handle smoothing and ranges slightly differently than the Unity default inputs, but you should be able to work around it and decide how you want to handle smoothing and dead-zones yourself.

# Answer
> 1 votes
I've been doing this with Oculus Touch controllers and it's been working fine. I setup the Input Manager using the scripting documentation. For Vive that's at https://docs.unity3d.com/Manual/OpenVRControllers.html .

1. Make sure you have "Virtual Reality Supported" checked in Edit =\> Project Settings =\> Player
2. Add a new element to Edit =\> Project Settings =\> Input. ie change 18 to 19.
3. Setup the new input element to map to the controller.  `Name: VrRightHorizontal
Gravity: 0
Dead: 0.1
Sensitivity: 1
Snap: false
Invert: false
Type: Joystick Axis
Axis: 4th axis (Joysticks)
Joy Num: Get Motion from all Joysticks`
4. Reference the axis by name in your code `Debug.Log("VrRightHorizontal" + Input.GetAxis("VrRightHorizontal"));`

---
Tags: unity, c#, input, htc-vive
---


# Question
Title: My [MenuItem()] is not being added to the menu
In Unity 5, I created a `ScriptableObject` class which adds itself to the Main Menu:

```
using UnityEngine;
using UnityEditor;

[CreateAssetMenu(fileName = "MyFancyAsset", menuName = "My Framework/Objects/My Fancy Object")]
public class MyFancySO : ScriptableObject
{
    // Public and [SerializeField] data comes here
}

```

This code works as expected. When the code is compiled, I can see the new menu being crated and working (a "My Framework" entry appears, and when choosing My Fancy Object), it is created appropriately).

What I am trying to do is to create a method with extended functionality o be added to the menu. So I tried like this:

```
using UnityEngine;
using UnityEditor;

[CreateAssetMenu(fileName = "MyFancyAsset", menuName = "My Framework/Objects/My Fancy Object")]
public class MyFancySO : ScriptableObject
{
    // Public and [SerializeField] data comes here

    [MenuItem("Assets/Create/My Framework/Objects/My Fancy Object (with more stuff)", menuItem = "My Fancy Object (with more stuff)")]
    public static void CreateInstanceWithMoreStuff()
    {
        // Now I create something, with logic based on what
        //   I can read in several files in the unity2d-extras
        //   repository.
    }
}

```

And although this code compiles with no errors, I don't see the new menu being created (but just the original menu created by CreateAssetMenu).

What am I missing?

# Answer
> 1 votes
To fix this, remove the code that sets the `menuItem` variable in the attribute:

```
[MenuItem("Assets/Create/My Framework/Objects/My Fancy Object (with more stuff)"]
public static void CreateInstanceWithMoreStuff()
{
    // Now I create something, with logic based on what
    //   I can read in several files in the unity2d-extras
    //   repository.
}

```

For more usage examples, see the Unity (5.6) Documentation for `MenuItem`

On later versions of Unity (e.g. on 2017.3), your code logs an error:

```
Ignoring menu item My Fancy Object (with more stuff) because it is in no submenu!

```

---

As a side note, I'm not sure why `menuItem` variable is exposed by Unity. The Unity (5.6) documentation for MenuItem (or later versions) do not mention these variables.

See below for the `MenuItem.cs` file. You are expected to use the constructors, and not the exposed public variables `menuItem`, `validate`, or `priority`.

```
public sealed class MenuItem : Attribute
{
    public string menuItem;
    public bool validate;
    public int priority;

    public MenuItem(string itemName);
    public MenuItem(string itemName, bool isValidateFunction);
    public MenuItem(string itemName, bool isValidateFunction, int priority);
}

```

---
Tags: unity, editors, menu
---


# Question
Title: File operation(s) failure on game crash/kill by OS/User in Android
My game saves its state after fixed interval on a file in game/app internal storage. When my game is killed or crashed by user or OS respectively, We write current game state on that file. File writing after fix interval is working fine but when game is crashed/killed by OS or user, file writing operation fails. Operation failure results incomplete game state or empty game state i.e. no data written on file at all. I have tried multiple solutions using android service, In case the service is NON STICKY service is killed with the app. On the other hand if service is STICKY then it is restarted but intent that was attached initially with service is null or new one.

The question is that how can i save my data (could be ~2-3MB) completely on file in internal storage when my game/app is killed by user/OS ?

# Answer
I would suggest writing your save state in a double-buffered way, as was common for console titles in the past (where you had to cope with the memory card being removed mid-write and writes were slow).

Save:

* If no files exist, write state to file A
* If A exists, write to B
* If A and B both exist, find which one is older, delete it, and then write to that one

Load:

* If both A and B exist, try to load the newer of the two. If that fails (because the file is incomplete or corrupt), delete it and load the other
* If only one exists, load it
* If both are corrupt, inform the user that their save state was irretrievable (like you presumably have to already)

This flow will work to ensure there is always at least one valid save still present in your storage, even if the app is killed mid-write. The player will not get any of the changes in the game state since the previous save if that sort of failure occurs, but they will not have to start again.

In addition, you should be saving immediately after key events (such as in-app purchases) in addition to your interval saving, to minimise the window of vulnerability where a crash/kill would cause that key event to be lost. This is also protection against game exploits (e.g. force-killing the app after losing a life, because you know you'll restore to a game-state from before you lost a life, and get to try again). Of course if do this you must protect your interval saving with logic that says "if a save is already in progress, do not try to start saving again."
> 20 votes

# Answer
Android only kills apps when they're in the background. Does your game data really need to be updated when the app is in the background, or can you stop updating the data until the app returns to the foreground? You might be able to defer updates even in a multiplayer game, if you can grab a history of events or even just the current state when the app returns to the foreground. This is something you should probably look at doing anyway for the sake of CPU, network, and battery efficiency.

If the user kills your app, running services should receive a call to `onTaskRemoved`. I don't know what would happen if you tried to do much processing in this method. I expect that if it doesn't return within a certain time, Android will `kill -9` your app.
> 3 votes

---
Tags: unity, android
---


# Question
Title: Instantiated object not tracking collision
I have an issue, and I'm not sure why it's happening. I have a prefab that I've built in a colour-changing game. It has the following:

* Four 2D objects that if they collide with the player (2D collider attached to all), they cause the player to die.
* One 2D object that if the player strikes, it generates a duplicate of itself with the Instantiate function.

All 2D objects are created; The four objects that cause the player to die are being created as normal and continue to cause the player to die. However, the object that instantiates the prefab and increments the score can no longer be collided with. The player appears to pass behind it. I'm pasting my code below. I would really appreciate if anyone can offer advice on this:

```
void Update () {
    if (Input.GetButtonDown("Jump") || Input.GetMouseButtonDown(0))
    {
        thing.velocity = Vector2.up * bounciness;
    }
    scoreText.text = score.ToString();
}
private void OnTriggerEnter2D(Collider2D collision)
{

    if (collision.tag == "plusScore")
    {
        score++;
        Destroy(collision.gameObject);
        Instantiate(barrier, new Vector2(transform.position.x, transform.position.y + 7f), transform.rotation);
        return;
    }

    if(collision.tag != currentColour)
    {
        Debug.Log("You DIED!");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        score = 0;
    }
}

```

# Answer
> 0 votes
I just now solved the problem... although I'm not sure what I did to solve it. I deleted the prefab and recreated it, dragged it into "barrier" field on my player script and it works... might just be a Unity bug. Cheers for your help.

# Answer
> 0 votes
If your player object passes through another object with a collider, it means that the collider is set to Trigger (the 'isTrigger' checkbox is enabled on the component).

When a collider is set to Trigger, no collision happens but the OnTriggerEnter() function is called.

You need to uncheck the 'isTrigger' checkbox, and instead of using

```
void OnTriggerEnter2D(Collider2D collision)
{
    //Your code here
}

```

you should use

```
 void OnCollisionEnter2D(Collision2D collision)
 {
     //Your code here
 }

```

---
Tags: unity, c#, collision-detection, collider
---


# Question
Title: How can I format my numbers in such a way that the digits are grouped?
I am developing a game using LibGDX, how can I make the label look like that:

```
Current display:    1000000000
Desired display: 1 000 000 000

```

# Answer
If you're not calling it every frame, parsing it out with `substring` is probably the easiest approach:

```
public static String groupByThrees(String s){
    String result = "";
    int index = s.length();
    // append groups of three to the front
    while(index-3 > 0){
        result = s.substring(index-3, index) + " " + result;
        index -= 3;
    }
    // handle any partial group at the very beginning
    if(index >= 0){
        result = s.substring(0, index) + " " + result;
    }
    // remove the training space at the end
    if(result.length() > 0){
        result = result.substring(0, result.length()-1);
    }
    return result;
}

```
> 1 votes

# Answer
A naive approach would be to divide and modulus by 1000 until nothing is left (pseudo code):

```
number = 1000000000
groupedString = ""

do {
  leftOver = number % 1000 // This will give you the value of the three right-most digits
  number = number / 1000 // This will keep the left-most digits for the next group; make sure this is an int division
  stringLeftOver = Integer.toString(leftOver)  // Convert to string what has to be pre-pended

  if number > 0
    // More groups to come, left pad with 0's
    properlyPadded = "000".substring(stringLeftOver.length()) + stringLeftOver
  else
    properlyPadded = stringLeftOver

  if groupedString.length() == 0
    // first time here, we just used the padded string
    groupedString = properlyPadded
  else
    // second time here (and more), prepend the string and add a separating space
    groupedString += properlyPadded + " " + groupedString
} while ( while number > 0 )

```

---

**Alternatively**, just use the Java `String` class:

```
groupedString = String.format(Locale.US, "%,d", number).replace(',', ' ')

```

(Source)

---

*Note that both of these methods have not been tested. Last time I coded in Java was more than 10 years ago.*

*Caveat:* I'd make sure that the label is wide enough and/or that the text wrap is disabled. (Again, I have no experience with LibGDX, but that's something to be aware of.)
> 1 votes

---
Tags: java
---


title: Taxes and Approximate revenue?

text:
# Question
Title: Taxes and Approximate revenue?
I'm heading out from the prototype stage and towards my early/alpha stage.

In this transition period I've been interested in getting an estimate of what the revenue will be so I've come up with this in Excel.

I've considered taxes in general, VAT and fee transactions from Stripe and PayPal.

I'm from Europe.

This is my first game and I know no-one in the field so I don't really have an answer.

Is the following a reasonable assumption?

```
Itch.io Cut           10 %
VAT Transactions      25 %

```

With this as an example result:

```
Money Earned       +1,000 €
VAT Transactions   -  250 €
                   --------
SubTotal           +  750 €

Itch.io Cut        -   75 €
                   --------
My Final Revenue   +  675 €

```

---

Here is my question on itch.io, and here it is to my reddit question.

# Answer
## Itch.io

Itch.io currently has two different payment models for VAT:

* **Direct to you** where each purchase is a transaction to your Paypal or Stripe account. Under this model, it is your responsibility to pay VAT, etc.
* **Collected by itch.io, paid later** where EU VAT (European Value-Added Tax) compliance is handled by Itch.io.

Beyond that, your price split with itch.io is pay what you want, which they refer to as open revenue sharing. By default, they start itch.io’s share rate at 10%, but you can adjust it to whatever you think is fair.

Most of this info is on or linked from itch.io's payment options & VAT support guide.

## Steam

My understanding is that Steam contracts prohibit open discussion of terms. Also, there's not a lot of public info provided. They discuss some of the info in their getting started FAQ & some of it in their reporting and payments FAQ. Due to nondisclosure agreements, it may be difficult for those familiar with the process to answer detailed questions.
> 1 votes

---
Tags: revenue
---


# Question
Title: UE4 Drag and Drop: Place PaperCharacter Over Image Widget
I'm working on adding drag and drop functionality to my game. I have it working with the exception of I can't get what I'm dropping to be placed where it was dropped. I've tried a number of different things but I can't seem to get it to work.

The image shows my OnDrop with some leftovers of things I have been trying. And when I adjust the MakeTransform manually, a change of 1.0 seems to move the character much more than 1 pixel. The item I am creating in the OnDrop is a PaperCharacter.

Here is an image from part of the level showing the result. The white blocks circled in red are UMG images so I can eventually adjust them to look better and change dynamically as the player is dragging. The player can only drop the item over one of there squares. This functionality works. But no matter which square I drop over the item always gets placed at the point circled in green or nowhere to be seen in the viewport. This is a 2d game so everything has to be in the viewport to be seen. The white squares are attached to a PaperSpriteActor. Not sure if that matters or not.

What I need to have happen is when the player drops the item above one of the squares, the PaperCharacter must be dropped right in the middle of that square. How do I go about making that happen?

***EDIT***

Another observation, if I manually set the MakeTransform location to 0, 0, 0 and drop the item on the same white square multiple times, the item is dropped in a slightly different spot each time.

# Answer
I have a work around to manually setting the location of the spawned item. So I can now manually set the location of the spawned item to be directly above the UMG image it was dropped over. However I doubt this is the best way to do it. If there is a better way to spawn a paper actor directly over a UMG widget I would love to hear about it.
> 0 votes

---
Tags: 2d, unreal-4, blueprints
---


# Question
Title: Help understanding IEnumerator Move routine
I have this code and I know what it does (it will move an object up and down)

But I don't know how its elements work. Could someone please explain it to me?

```
IEnumerator Move (Vector3 Target) // What this IEnumerator do?
{
    while (Mathf.Abs ((Target - transform.localPosition).y) > 0.1f) {
        Vector3 Direction = Target.y == Top.y ? Vector3.up : Vector3.down;
        //Is this an if/else? and if yes why if target.y == top.y its first choice is vector3.up?

        transform.localPosition += Direction * 5 * Time.deltaTime;
        yield return null;
    }
    yield return new WaitForSeconds(1f);
    Vector3 newTarget = Target.y ==Top.y ? Bottom : Top;
    //Same line but result order is different ?.?

    StartCoroutine(Move(newTarget));
}

```

# Answer
I assume the lines you don't understand are those you put comments on, so I will explain them in order.

1. A method returning an `IEnumerator` is one which can use the `yield` instruction to return values to the caller. Whenever the program flow reaches a `yield`, the program flow goes back to the caller. The caller can then process that value and then resume the execution of the enumerator-method after the `yield` instruction (or not). When you encounter such a method in a Unity project, then it is usually used for a Coroutine. The `yield return`'s in a coroutine are the points where the program flow returns to the engine which will then resume the coroutine at a later time (how much later depends on what value you `yield return`).

Unity Coroutines can be an elegant way to express processes which are supposed to take multiple frames to complete without having to add complicated state-determination logic to your `Update` methods or opening up the box of pandora which is actual multi-threading (I personally prefer state machines, command queues and behavior trees, but that's a personal preference).
2. The `a ? b : c` construct in C# is the Ternary Condition Operator. It returns a single value. If `a` is `true`, it returns `b`, otherwise it returns `c`. In this case `a` is `Target.y == Top.y`. So in plain English, this line means "If `Target.y` is equal `Top.y`, `Direction` is up, otherwise Direction is down".
3. And so, `Vector3 newTarget = Target.y ==Top.y ? Bottom : Top;` means "If `Target.y` is equal `Top.y`, then head towards `Bottom`, otherwise head towards `Top`"
> 2 votes

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


# Question
Title: Why I'm getting ArgumentException: failed to convert parameters when trying to load a scene?
I have two scenes the first one and the one that is loading when running the game is main menu. The second scene is scene002.

I want to load scene002.

In the main menu scene I have a button. Attached to the button this script:

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

public class LoadSceneOnClick : MonoBehaviour
{
    private bool loaded = false;

    public void LoadByIndex(int sceneIndex)
    {
        SceneManager.LoadScene(sceneIndex);

        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (arg0.isLoaded == true)
        {
            loaded = true;
        }
    }

    public void ActivatePlayer(GameObject player)
    {
        if (loaded == true)
        {
            player.SetActive(true);
        }
    }
}

```

When loading the scene002 i want to enable the Player.

In the button On Click I added to the list the two methods LoadByIndex and ActivatePlayer but when I click the button the player object I dragged to the inspector of the button is gone and I'm getting this exception:

```
ArgumentException: failed to convert parameters
System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:484)
System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:528)
System.Reflection.ConstructorInfo.Invoke (System.Object[] parameters) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:77)
UnityEngine.Events.PersistentCall.GetObjectCall (UnityEngine.Object target, System.Reflection.MethodInfo method, UnityEngine.Events.ArgumentCache arguments) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:469)
UnityEngine.Events.PersistentCall.GetRuntimeCall (UnityEngine.Events.UnityEventBase theEvent) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:436)
UnityEngine.Events.PersistentCallGroup.Initialize (UnityEngine.Events.InvokableCallList invokableList, UnityEngine.Events.UnityEventBase unityEventBase) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:609)
UnityEngine.Events.UnityEventBase.RebuildPersistentCallsIfNeeded () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:775)
UnityEngine.Events.UnityEventBase.PrepareInvoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:811)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()

```

# Answer
> 1 votes
I suspect that scene loads successfully but your callback is giving you an error. `Scene arg0, LoadSceneMode arg1` \- might be wrong types.

But documentation says they are ok. https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html

So it is possible that you are passing wrong type in the inspector. Considering that it makes a call to `Reflection` it's probably related to serialization in inspector. Check out button event and correct the value if it's wrong.

**EDIT**

From the discussion with OP I understood that the problem lies in additive scene loading.

1. The problem was that the new scene was first loaded, losing all the data about previous scenes and then the button event tried to access that data.
2. A theory that references between 2 additive loaded scenes don't work in the inspector. (Will update the answer once I test it)

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


# Question
Title: When and where and how to turn on back the Player first person when loading a scene on button click ?
In the Build Settings I have two scenes at index 0 and index 1:

Then in the Hierarchy I have the two scenes: The active scene is the MainMenu:

In the StartGameButton I added to it a script component. In the script:

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

public class LoadSceneOnClick : MonoBehaviour
{
  public void LoadByIndex(int sceneIndex)
    {
        SceneManager.LoadScene(sceneIndex);
    }
}

```

And this is the StartGameButton Inspector:

I dragged the script on the OnClick I selected the function LoadSceneOnClick And set the index to 1

When the game start and I click on the button it stay on the Main Menu scene and not loading anything.

The problem I guess is that I'm getting error in the game No cameras rendering:

The problem is that when I'm running the game and it start from the main menu scene in the space station scene I'm enable false the Player and the Player is a first person character with a camera:

You can see in the Inspector that the Player is unchecked the Player is not enabled. If I will enable the Player and even if the main menu scene is the active one it will show me the player and the player camera and not the main menu. So I had to turn off the Player.

The question now is where by script do I enable back the Player when it's loading the scene ?

Inside the LoadSceneOnClick script ?

# Answer
It's a matter of preference and experience.

I would create some kind of `ScriptableObject` with events and data required after the new scene was loaded. Then I would have some kind of controller with event on scene loaded and pass the data there from assets. Then from it I would execute all required actions via method in that `ScriptableObject`. But that might look too complicated.

What I suggest that for main menu visuals, you create a separate scene that loads additively and that doesn't have all of these game-play related features. It only has what is required for the main menu. Ideally you would put all of these into Main Menu scene.

But for your case the best would be to not load the new scene, but to enable the Player and unload the Main Menu scene. This way you don't have to load the same scene again and you have your game-play ready state.
> 1 votes

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


# Question
Title: Allow code after a bugged line to continue without use of try and catch
My problem is with C# in unity, but I think the problem can be applied to all coding languages.

For example I have a start function/event that may initiate many things. Some lines of code may issue a bug but I want to allow new lines of code run after that without having to encapsulate every line of code with try and catch. Is there any common solution for this that I'm missing?

# Answer
> 0 votes
No. Try-Catch blocks are the way to go.

It tells the compiler to trap exceptions and resume after the block, making sure operations are serialised properly to resume execution and not reordered for better performance.

It's not feasible to restore an execution context to resume execution properly otherwise.

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


title: Storing 2d map data as PNG

text:
# Question
Title: Storing 2d map data as PNG
Just a question regarding the storage of 2D map data. There are several topics discussed within gamedev, i.e. Array Storage: How to store 2D tile-map, custom map formats: A way to store potentially infinite 2D map data? etc

Considering that I intend to pre-generate my entire map at the start of the game (Much like Terraria does) and store that and then load 'chunks' of the data into an array or custom format as the player moves through it and interacts with the environment.

Been a total noob my question my be a little naive, but is there something wrong with pre-generating the map data (tile based, side view with each tile type represented as a discreet integer) as a PNG (No alpha) and saving that. Then read in the section of the PNG for the chunk to be loaded and converting the specific pixels to their integer value to determine what tile it represents ?

I could possibly even have one PNG for the terrain, one to represent containers and loot, which would be read separately and overlaid, then one for structures etc.

Then also obviously update the PNGs as terrain is created/destroyed by the player.

I can only assume this is not discussed anywhere as its probably slow versus maybe just reading/writing from/to a binary data format/array?

Regards John

# Answer
Sure, you *could* do that, and it would not be "wrong" in the sense that any solution which gets you closer to a working game is never wrong.

But keep in mind that the PNG format is designed to store images for displaying them on a screen. You are using it for something it wasn't designed for. It might work, but you might get better results with a more tailor-made solution.

Which problems exactly does using the PNG format solve?

1. Organize data into chunks
2. Compress the data

First, **chunk organization**. Yes, the PNG format allows you to split the image data into individual `IDAT` chunks. You can retrieve individual chunks of the image by seeking over all those chunks which don't interest you. But this still requires to read the length-field of each chunk and seek over it to the next chunk until you've reached the chunk you want. So you still need to read a lot of the image file even if you only care about one single chunk. It would be better if you would have some data structure which tells you where to find each chunk. But that would be something you would have to build on your own.

Also, most PNG libraries do not assume that the user would care that much about how they want the chunk organization of their PNG to look. So getting your PNG encoder to organize the PNG file exactly the way you want might be difficult. You could of course write your own PNG encoder which organizes the `IDAT` chunks exactly the way you want, but then you can just as well invent your own file format.

And then you have to get your image *de*coder to get only that one chunk. This is again a very unusual use-case many libraries won't account for.

Or... maybe don't use chunks? Maybe your PNG library has a function like `getImageData(x, y, width, height)`? So why not use that to load just the data you want? Keep in mind that when all the image data is in one compressed chunk, then the library has only one way to implement this function: Read the whole image into memory, decompress the whole image, and *then* extract the section you want from the decompressed data. So in this case the PNG format would really get you no benefit at all.

Then, **data compression**. PNG uses the well-known `DEFLATE` algorithm to compress the `IDAT` chunks, which you can get just as easily as a free stand-alone implementation. Before applying DEFLATE, it can optionally apply one of several different filter methods in order to make the image data even more compressible. But these filter methods are all optimized for typical real-world image data. They are unlikely to improve the compression rate much when applied to non-image data.

So what do we learn from this? It might be easier to just roll your own map format:

1. Compress each map-chunk to a byte-array using a stock compression algorithm of your choice (which might or might not be `DEFLATE`)
2. Create an index which tells you order and length of the compressed chunks
3. Write the index to the file, followed by the chunk data

If you want to retrieve a chunk, read the index (you might want to cache it in memory so you don't need to re-read it every time you load a chunk), jump straight to the position in the file it tells you, read it, and decompress it.
> 2 votes

# Answer
It depends. If you are not saving / loading the game often, then using an image for your save file isn't likely to be a barrier in terms of speed. On the other hand, if you are frequently doing automatic quick saves or check pointing, it may be a problem.

One advantage to your approach is that depending on the level size, it may give your players a fun & easy way to trade save game data. I don't recall the title, but there was some game that deliberately made the save game file a small thumbnail image of the level itself. Players could get a sense of what the level looked like at a glance, show off & trade levels on social media by posting the images & potentially edit the levels themselves with paint or photoshop (though not all such level might be valid).

The game MidBoss did something similar:

> When a MidBoss player finishes a run—usually by dying—they can post a "death card" with the circumstances of their death or transcendence to Twitter. The embedded image doubles as a save files to allow other players to replay from the same seed or salvage loot from the failed run, since all of the information is steganographically encoded into the PNG image file.

Similarly, TerraTech and Spore used steganography & image files for sharing player-generated content.

I realize the original question isn't about steganography per say - my point is that using a format that is readily understandable by players & can be used outside your game may have benefits.
> 0 votes

---
Tags: 2d, tilemap, format
---