# Question
Title: Connecting Player and Rope classes in a rope-swinging game
I am trying to build this game where the player hops between a number of ropes.

For now, in addition to my main activity that I kept empty, I built two additional classes:

* `Ropes.java`, storing the coordinates of the ropes and their movement
* `Player.java`, storing the player's details

Can you advise me about the next step to join them? For instance, where to include the "attach function" that links the player to the rope in case he reaches it?

And how would I populate the main activity to organize the game?

To further explain my problem, I will join my three activities below: the first is the rope class; the second is player class:

Rope class:

```
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.app.Activity;
import android.media.SoundPool;
import android.graphics.Paint;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

import java.util.List;

import static androidx.core.graphics.drawable.IconCompat.getResources;

public class ROPE extends Activity {
    public List<Float> ab=[,,,];
    public List <Float> ord;
    public float speed_up=-1;
    public final TARZAN tarzan;

    public static final float WIDTH         = 67;
    public static final float HEIGHT        = 416;
    public static final float ROPE_DISTANCE = 50;
    private static final float SPEED        = -2;

    public ROPE (Context context, List ab, List ord, TARZAN tarzan){
        this.tarzan=tarzan;

    }
    public void move_rope(){
        for(int i=0;i<4;i++){

        }
    }

    public void draw(Canvas canvas) {
        Drawable rope= getResources().getDrawable(R.drawable.rope);
        rope.draw(canvas);
    }
}

```

Player class:

```
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.SoundPool;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public abstract class TARZAN extends Activity implements View.OnClickListener{
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    private  boolean  isAlive=true;
    public final float K=20;
    public final int WIDTH       = 44;
    public final int HEIGHT      = 31;
    private final int BASE_COLLISION  = 521 - HEIGHT - 5;
    public float X;
    public float Y;
    public float vitesse=0;
    static final int gravity = -10;   // constant downward acceleration
    static final int flapping = 25;   // upward acceleration whenever isFlapping is true
    Boolean isFlapping = false;   // Is TARZAN flapping

    public TARZAN(float X,float Y) {
        this.X=X;
        this.Y=Y;

    }
    public float getX () {
        return X;
    }
    public float getY () {
        return Y;
    }
    public boolean isAlive () {
        return isAlive;
    }

    /**
     * Kills
     */
    public void kill () {
        isAlive = false;
    }

    /**
     * Set new coordinates when starting game
     */
    public void setGameStartPos () {
        X = 90;
        Y = 500;
    }
    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X-=K;
                    Y=
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X+=K;
                    Y=
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }

    public void stick_to_rope(){

    }

    public void draw(Canvas canvas) {
        Drawable tarzan=getResources().getDrawable(R.drawable.mario);
        tarzan.draw(canvas);
    }

}

```

My Main\_Activity is currently empty.

# Answer
> 2 votes
Depends how your engine works.

Your player could be responsible for checking for ropes, or your ropes could be responsible for checking for the player.

Either way, I think both your player and your rope are going to need to know that they're attached, so whichever way you choose, you're going to need to have an `'attach'` function in both classes.

---
Tags: java, android
---


# Question
Title: How to get multiple string values from override ToString()?
I want to get multiple string values(`selectedName`and `selectedCurrency`) individually from `public override string ToString()`below. How do I go on about it?

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

       [CreateAssetMenu(fileName = "Country", menuName = "Country/Country", order = 0)]
       public class country : ScriptableObject
       {
           [System.Serializable]
           public class Item
           {
               public string Name;
               public string Currency;
               public string Capital;
               public string[] City;

    public override string ToString()
    {
    string selectedName = this.name;
    string selectedCurrency = this.currency;
    return selectedName + selectedCurrency;
    }

           }

           public Item[] m_Items;
       public Item PickRandomly()
    {
        int index = Random.Range(0, m_Items.Length);
        return m_Items[index];
    }
}

```

I need to use the selected string values in the script below.

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

    public class GameController: MonoBehaviour
    {   public country country; //This is the scriptable object country
    public Text countryText;
    public Text currencyText;

    void Start(){
    countryText.text = country.PickRandomly().ToString(); // This is where I need the country name string to show up.
currencyText.text = country.PickRandomly().ToString(); // This is where I need the currency string to show up.
    }
    }

```

Right now it just displays a random country name and currency for example USA USD in both the fields.

# Answer
There are many ways of implementing what you are after.
As @DMGregory said you could write your own separate methods for getting the country and the currency:

```
[System.Serializable]
public class Item
{
    public string Name;
    public string Currency;
    public string Capital;
    public string[] City;

    public string GetCurrency()
    {
        return Currency;
    }

    public string GetName()
    {
        return Name;
    }
}

```

Alternatively, you can just access the fields of `Item` directly:

```
void Start(){
    countryText.text = country.PickRandomly().Name;
    currencyText.text = country.PickRandomly().Currency;
}

```

PS: If you want to do more advanced stuff with the data without having to implement lots of methods to get strings (such as if you wanted to be able to get country name and currency as one string) I would suggest you have a look using properties: Using Properties - C# Programming Guide | Microsoft Docs
> 0 votes

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


# Question
Title: Handling multiple pressed keys with KeyListeners
I'm making a game Applet with Java that uses `KeyListener`s to control a paddle (for a game like Breakout/Pong). My basic implementation goes like this:

```
public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            direction = "LEFT";
            break;
        case KeyEvent.VK_RIGHT:
            //repeat for the rest
    }
}
public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)
        direciton = "";//paddle doesn't move
}

```

My problem is that when the user tries to change the direction of the paddle twice too fast (let's say you press *left*, then *right* and *left* again super fast), the paddle freezes for a split second, and continues to move along its direction.

I understand that the problem is the logic in my code, but I can't think of a better implementation. What am I missing?

# Answer
It needs **state**.

At the moment, this is what happens if you press *Left*, press *Right*, then release *Left*:

```
-> keyPressed(left):  direction = "LEFT";
-> keyPressed(right): direction = "RIGHT";
-> keyReleased(left): direction = "";

```

The paddle doesn't move, even though *Right* is still pressed!

You can solve this by checking in `keyReleased` if the opposite direction is still down and reset the direction to `""` only if it isn't.

Unfortunately, since `KeyListener`s only tell you when keys go down and up, not whether they are down at the moment. You must track this state yourself. You can do it by setting variables `leftIsDown` and `rightIsDown` in the `keyPressed` and `keyReleased` cases for each key.
> 1 votes

# Answer
... A more expensive way:

```
public class TimerExample implements KeyListener {
private Timer right;
private Timer left;
private Timer down;
private Timer up;
public void defineTimers() {
    ActionListener l = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Move LEFT
        }
    };
    right = new Timer(10, l);
    ActionListener r = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Move RIGHT
        }
    };
    right = new Timer(10, r);
    ActionListener d = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Mode DOWN
        }
    };
    down = new Timer(10, d);
    ActionListener u = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Move UP
        }
    };
    up = new Timer(10, u);
}

    @Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
        up.start();
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        down.start();
    } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        right.start();
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
        left.start();
    }
}
@Override
public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
        up.stop();
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        down.stop();
    } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        right.stop();
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
        left.stop();
    }
}

```

}
> 0 votes

# Answer
States can be achieved with enums, I'm writing a similar game too and thanks to @Anko I implemented his solution like this:

```
public enum PaddleWay {
    UP, DOWN, STOP
}

```

---

```
private void handleMovement(){
    if(p1paddleway == PaddleWay.STOP) {
        paddle1yPos = paddle1yPos;
    }
    if(p1paddleway == PaddleWay.UP) {
        paddle1yPos -= PADDLESPEED;
    }
    if(p1paddleway == PaddleWay.DOWN) {
        paddle1yPos += PADDLESPEED;
    }
    if(p2paddleway == PaddleWay.STOP) {
        paddle2yPos = paddle2yPos;
    }
    if(p2paddleway == PaddleWay.UP) {
        paddle2yPos -= PADDLESPEED;
    }
    if(p2paddleway == PaddleWay.DOWN) {
        paddle2yPos += PADDLESPEED;
    }
}

    @Override
public void keyPressed(KeyEvent e) {
    switch(e.getKeyCode()) {
    //p1 inputs
    case KeyEvent.VK_A:
        p1paddleway = PaddleWay.UP;
        break;
    case KeyEvent.VK_Z:
        p1paddleway = PaddleWay.DOWN;
        break;
    //p2 inputs
    case KeyEvent.VK_O:
        p2paddleway = PaddleWay.UP;
        break;
    case KeyEvent.VK_K:
        p2paddleway = PaddleWay.DOWN;
        break;
    }
}
@Override
public void keyReleased(KeyEvent e) {
    switch(e.getKeyCode()) {
    //p1 inputs
        case KeyEvent.VK_A:
            p1paddleway = PaddleWay.STOP;
            break;
        case KeyEvent.VK_Z:
            p1paddleway = PaddleWay.STOP;
            break;
    //p2 inputs
        case KeyEvent.VK_O:
            p2paddleway = PaddleWay.STOP;
            break;
        case KeyEvent.VK_K:
            p2paddleway = PaddleWay.STOP;
            break;
    }

```

It's a little long but you can just copy paste once you write one method and simply manipulate.
> 0 votes

---
Tags: java, keyboard, control, callbacks
---


# Question
Title: Positioning ropes equidistantly on a landscape display
I would like to render 4 similar ropes in my game that are equidistant on a landscape mode display.

How can I proceed? My screen is 1920\*1080, at 420 dpi.

Is there any way that I could link the ropes coordinates with pixels or is there another way?

# Answer
I think your screen size will likely vary between phones.

You should use a method to access the screensize.

Probably subtract a buffer (say 200 pixels) from each side of the screen size (e.g. `1920 - 2*200`)

Divide the remainder by 5, as you want 4 ropes (so 5 gaps between them)

---

`B = Buffer , G = Gap, | = Rope`

`B G | G | G | G | G B`

---

Use a `'Screen Space to World Space'` transformation to transform co-ordinates for the rope positions into world space coordinates at which they can be placed.

---

`Rope n Position = BufferSize + n*GapSize`
> 1 votes

---
Tags: java, android
---


# Question
Title: How to move player out of multiple penetrating colliders?
The player in my game can teleport like Noctis from ffxv.The player shots a weapon projectile and then teleports to the projectile. I'm using raycast to calculate the weapon position after thrown. However, I need to check if the weapon is stuck in an unteleportable position after being thrown. It is possible to have multiple penetrating colliders. Ex: spear gets sandwiched between two walls that is narrow enough for the weapon to pass through but not tall enough for the player to stand. I want to somehow check for a nearby valid position for after teleporting in that situation.

I also want the teleport to fail if the weapon is horizontally in the middle of the "pipe".

I could do a bunch of overlapBox checks within a radius distance from the teleport point but that doesn't seem efficient. I want to give the player some leeway when aiming a teleport.

Also, the teleport is not immediate. The player can wait some time before teleporting to the weapon. So it is possible for a moving platform to block a raycast from the player. In which case I still want the raycast to succeed.

I'm using unity and a custom raycast based 2d character controller for normal movement.

# Answer
I suspect raycast may not be the best option. Rather, actually shooting something that represents the teleport location might work better.

In the event you want to stick with raycasts, a standard one is "eaten up" by its first collision, but there are modified ones that don't. If I recall it's something like RaycastAll.

The advantage of shooting the actual teleport location along with the weapon is then it follows your weapon's physics or custom behaviour if the weapon bounces or is blocked by something.

The moment the player clicks "teleport" You then take this location, and search around it for a valid spot. There are many ways to do this, the simplest of which is to make a 2d mesh of valid spots of the ground that can be teleported to, similar to a navmesh. Then you find the nearest spot on this mesh from the teleport location, and if it's farther than some threshold you disallow the teleport, if it's allowed, you let the teleport happen to this valid location.

I can forsee cases where you want them to be able to teleport in ways that can kill themselves, you you might make this (invisible) teleport mesh extend across pits etc, meaning that you can teleport there, but then you'll fall to your death.

Hope that gives you some ideas to get started.
> 1 votes

---
Tags: unity, collision-detection, collision-resolution
---


title: Unity trigger method does nothing

text:
# Question
Title: Unity trigger method does nothing
I have the following script on my object:

```
public class PlayMyCube : MonoBehaviour
{
    [SerializeField] private Animator myAnimationController;

    private void onTriggerEnter(Collider other) {
        if (other.CompareTag("Player")) {
            myAnimationController.SetBool("playSpin2", true);
        }
    }

    private void OnTriggerExit(Collider other) {
        if (other.CompareTag("Player")) {
            myAnimationController.SetBool("playSpin2", false);
        }
    }
}

```

When the player character is inside the first cube's trigger, my second cube should play a spinning animation. When they leave, the second cube should stop.

But what happens in the game now is, when the character runs into the trigger, it does nothing.

I have configured my trigger object like this:

I have configured the object that should spin like this:

And configured the Animation Controller like this:

And configured my Player object like this:

What can I do to make this animation play when the player is inside the trigger?

# Answer
> 2 votes
The method is called `OnTriggerEnter` (uppercase O)

What you wrote in your script is `onTriggerEnter` (lowercase o)

Identifiers in C# are case-sensitive, so these are two completely different functions as far as the compiler/engine is concerned. When it tries to call `OnTriggerEnter`, it discovers there's no method on your script with exactly that name, so it does nothing.

Please be careful to type your scripts correctly, and proofread your code for typos.

You can find this class of error faster in future by using a breakpoint or `Debug.Log` to determine whether the method is even being called when you expect. That will let you isolate the problem and find your own answers quickly. Or, if the answer still eludes you, it will at least help you ask a more concise question: all the extra detail you showed with the animator here isn't relevant to the problem, if the `onTriggerEnter` method is never being called.

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


# Question
Title: How to load additive scenes to the master client, per player, in unity using photon?
I have already successfully created a multiplayer scene where multiple users can join, however there are some issues like unity not allowing multiple sound listeners per scene. In order to alleviate this problem (hopefully) I would like to load an additive scene that connects to the master client. In the additive scenes will contain the other players. How can I achieve this using photon PUN2?

In normal unity non multiplayer it is a easy as `SceneManager.LoadScene(sceneName,LoadSceneMode.Additive);` With that code a new scene adds on to the scene already at play as a new scene. I wish to do so with photon PUN2 somehow, where the master client loads his scene and other players join the game using their own scenes. Currently the other players are loading into the scene with a simple instantiation of their prefabs `PhotonNetwork.Instantiate`and this is giving me errors such as the one stated above (multiple sound listeners)

Please help

# Answer
> 2 votes
This might not be the most elegant solution but it's certainly an effective one:

What I have done in the past when using PUN for this is to use the `PhotonNetwork.Instantiate()` method for player instantiation. What you to avoid issues with multiple audio listeners and cameras is to write a NetworkPlayerManager script and add it to the player prefab. In this script in the `Start()` method you add a simple check to see if the player is the local player or a remote player and if it's a remote player you can disable the camera and audio listener (as well as any UI/Input management, etc...) components.

```
void Start() {
  if (photonView.IsMine) {
    //Any initialisation required for the local player goes here.
  } else {
    foreach(MonoBehaviour c in disableComponentsIfNotMine)
      c.enabled = false;
    foreach(GameObject g in disableGameObjectsIfNotMine)
      g.SetActive(false);
  }

  DontDestroyOnLoad(gameObject);
}

```

# Answer
> 1 votes
I basically combined Thomas Mathieson's answer combined with DMGregory's response to successfully add two players. I used `if (photonView.IsMine)` and within it I placed DMGregory's suggestion to instantiate the player objects such as camera and audio listener locally.An empty player object is spawned in through Photon and within that empty player object is the script that instantiates the player cam and audio listener locally. Thanks! –

---
Tags: unity, networking, multiplayer, scene, photon
---


# Question
Title: How much does joystick axis resolution matter?
While developing, I started integrating joysticks into my framework, and had some questions since different OSs handle joysticks differently. My framework may potentially be opened to the public at a later date, so I thought I'd ask these for consideration:

What's the minimum amount of resolution a framework should offer to developers? While watching the values of the axes, I can get a reasonably smooth range from my joystick; however I can't think of too many use cases for the higher resolutions.

Are there any real benefits of having high resolution vs a lower one? I was thinking about having just a 3-bit resolution for my games, (standing, creeping, walking, running, plus one bit for the opposite direction).

I can only see high resolutions being useful on driving or airplane simulator games, so are there reasons to use them in other types of games? Personally, I still see having three, or even four bits for such games as enough.

Thanks.

# Answer
> 1 votes
This totally depends on which kind of game you want to make. Driving games and flight simulators are obvious candidates for high resolution. But there might be other use cases. Think of the control stick of a Playstation as joystick equivalents. If you play an FPS and don't have a mouse, you want at least some ability to aim with fine-grained control (I have to admit here, that I don't really know how much control a PS control stick offers). You can also use it to give the player better control of his character's movement speed. There are also games with the possibility to drive or maneuver an aircraft without being a racing game or a flight simulator, like GTA, Battlefield, etc.

Additionally, there is the question: What is the point of using a joystick in the first place, if you don't use its capability to give you a high-resolution input? If it is not needed, you can simply use a control-pad.

So if I would search for a framework for my game, I would answer your questions as follows:

> What's the minimum amount of resolution a framework should offer to developers?

The maximum that is possible from the utilized hardware + drivers.

> Are there any real benefits of having high resolution vs a lower one?

If MY game needs it, yes, if not, no.

> so are there reasons to use them in other types of games?

Yes, see above. And there are certainly many, many more.

> I still see having three, or even four bits for such games as enough.

This attitude is fine if you are developing a game. If you want o to provide a framework for developers, you are taking options away from them. This might be a reason to decide against your framework.

---
Tags: joystick
---


# Question
Title: Changing contents of level depending on which character was selected
I'm trying to create a character selection menu in Unity, where each character has their own version of the level that follows.

There are about 10 characters. Each character has a different location where they spawn in the level, and each enemy has a different spawn position as well, depending on which character was selected.

What I have been doing is to create separate levels (scene files) for each character. Then in the character selection menu, I load the level depending on the level selected by the user.

This seems to be a lot of code and data repetition, as the scene is the same in all levels; it's just that the spawn positions and enemies are different.

Is there any way have only one level scene, and get the spawn position and enemy spawns based on the character?

This is the code I have so far in `GameManager.cs`:

```
public GameObject enemy;
public Transform enemySpawnPoint;

public GameObject player;
public Transform playerSpawnPoint;

public static GameManager instance;

private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
}

void Start()
{
    StartCoroutine("SpawnEnemies");
    SpawnPlayer();
}

IEnumerator SpawnEnemies()
{
    while (true)
    {
        yield return new WaitForSeconds(1.0f);
        SpawnEnemy();
    }
}

public void SpawnEnemy()
{
    Vector3 enemySpawnPos = enemySpawnPoint.position;

    Instantiate(enemy, enemySpawnPos, Quaternion.identity);

}

public void SpawnPlayer()
{
    Vector3 playerSpawnPos = playerSpawnPoint.position;

    Instantiate(player, playerSpawnPos, Quaternion.identity);

}

```

...and the character selection script:

```
public void Level1()
{
    SceneManager.LoadScene(1);
}

public void Level2()
{
    SceneManager.LoadScene(2);
}

// ...

public void Level10()
{
    SceneManager.LoadScene(10);
}

```

Now the issue is, if I want to make any changes in one scene, like the skybox or background color, I will have to open all the other level scenes and make the changes.

Another thing is that if I want to add new levels, I will have to do the same thing, which seems like a lot of repetition.

Is there some way to set the enemy prefab, enemy spawn positions, player prefab and player spawn position once the character has been selected?

For example, if the user clicks on level1, all the preceding variables are set automatically and so on.....

# Answer
> 0 votes
For something like this, I'd set up a separate asset file for each "version" of your level that you want to load. We'll use this data structure to transform the scene on start-up. Even though we're always transitioning to the same single scene file, we can use this data to change which spawn points are active and what spawns at each one in the first frame after we arrive in the new scene.

Let's this data structure a "scenario":

```
[CreateAssetMenu(fileName="Scenario.asset", menuName="Level Data/Scenario")]
public class Scenario : ScriptableObject {

    // Hold the current scenario for ease of access.
    // (Global variable to be quick & dirty, but you can improve on this later if needed)
    public static Scenario current;

    [System.Serializable]
    public struct SpawnInfo {
        public string name;
        public Transform prefab;
    }

    [SerializeField]
    List<SpawnInfo> _spawns;

    public Transform GetPrefabForSpawnPoint(string name) {
        // Return the prefab slated for that spawn point name in our list, or null.
        var info = _spawns.Find(i => i.name == name);
        return info.prefab;
    }
}

```

This will let you create an asset in your project broswer like this:

You'll create one scenario for each character. Inside a character's scenario asset, you can specify a list of what should spawn at each spawn point in your level. You can also add other parameters - like a time limit or special scoring rule or alternate music track / rendering effects to apply when this character is playing.

Now, at each spawn point, you can add an empty GameObject with a script like this:

```
public class SpawnPoint : MonoBehaviour {

    void Start() {
        // Ask the current scenario what is supposed to spawn here.
        var prefab = Scenario.current.GetPrefabForSpawnPoint(gameObject.name);

        // If nothing is set up to spawn here, abort!
        if (prefab == null)
            return;

        // Otherwise, spawn the selected prefab at this marker object's position & orientation.
        Instantiate(prefab, transform.position, transform.rotation);
    }
}

```

Name each spawn point game object something clearly identifiable, so you can easily recognize which spawn point is which in your hierarchy view, and match that name when wiring up the spawns in your scenarios.

Note that the names don't have to be unique: you could have 5 spawn points named "Spawn Group A" - then anything the scenario says should spawn at "Spawn Group A" will spawn from all 5 of those locations. This can help when setting up masses of grunt enemies or pickups/powerups.

Lastly, we need your character selection script to set the current scenario before loading the scene. Here's one way to do it:

```
public class CharacterSelect : MonoBehaviour {

    [System.Serializable]
    public struct CharacterInfo {
        public string name;
        public Scenario scenario;
        public int sceneToLoad;
    }

    [SerializeField]
    List<CharacterInfo> _characters;

    public void SelectCharacter(string name) {
        var info = _characters.Find(i => i.name == name);

        // Catch errors where we type a name wrong, or forgot to provide a scenario.
        if(info.scenario == null) {
            Debug.LogErrorFormat("No scenario set for character names {0}!", name);
            return;
        }

        // Remember this character's scenario,
        // so spawn points in the next scene can reference it.
        Scenario.current = info.scenario;

        // Load the appropriate scene for this character
        // (so you can still use an alt scene for some characters, if needed)
        SceneManager.LoadScene(info.sceneToLoad);
    }
}

```

Instead of having a separate scene-loading function for every character, your UI buttons can all just call this one character select method, and pass the name of the character they should use:

Note that here I've used a "stringly typed" strategy for maximum flexibility: your level designers can add new spawn points or even new characters with new names purely in data, with no code changes. The downside is that you get no compile-time validation that the names link up correctly. One typo, and no scene loads or nothing spawns at that location because the strings don't match exactly. If you want tighter control, you can use an `enum` instead, to have a list of allowed characters / spawn point IDs, and get stronger tool support to verify that only valid IDs are used.

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


# Question
Title: libgdx - Problem occurring after collision detected
I have just implemented collision detection in my little 2d rpg-like game. I'm using Tiled for the maps, mechanism is simple - I have one layer called 'collision' in my tiled map, and while loading this map in game, I'm adding Rectangle objects to the tiles in 'collision' layer. Therefore, when player's rectangle overlaps tile's rectangle, collision is detected. My problem is - what proper action should be taken after this detection? Note - my player object has field like (float) movementSpeed, (Vector2) position. By pressing arrow keys player moves in a particular direction, algorithm looks like: Keys.RIGHT clicked ---\> player.position.x += movementSpeed; Keys.DOWN clicked ---\> player.position.y -= movementSpeed; ...and so on. **The REAL problem begins here** \- after collision has been detected, I'm adjusting player's position, just like in code below.

```
public void adjustPosition() {
    switch (currentMove) {
        case UP:
            position.y -= movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case DOWN:
            position.y += movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case LEFT:
            position.x += movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
        case RIGHT:
            position.x -= movementSpeed;
            rectangle.set(position.x, position.y, playerWidth, playerHeight);
            break;
    }
}

```

But it doesn't work as expected - after spamming arrow keys in different directions near the collision tile, player somehow is put onto the collision tile or is going just through it (and player definitely shouldn't be able to do so). My question is - *what should I do after collision has been detected in such a situation?*

# Answer
> 0 votes
I have this problem before and for me, the best solution (at least for my 2D game) was to calculate where the player is going to be *before* moving, and if the location is not valid just don't move the player. This will prevent lot of issues even with spam, as you directly won't move the player.

As this is done before moving the player you can tweak how it's done. For example, you could stop completely the player if it's going to be a collision, or calculate the angle of the collision and only stop the x or y value of the player (so the player will slide around), or you can bounce the player back (from a valid position to another valid position, without entering the invalid one).

Calculating the direct future position of the player should not affect performance.

# Answer
> 0 votes
Maybe you should try a different approach, instead of moving the player back by its speed that depends on the games frame per second rate, you better move to object by a constant value, if its a tile based game and the ties do not overlap just put the player in the previous tile. Since your game speed can vary you can not rely on the movement speed of the player without taking into account the current FPS.

---
Tags: java, libgdx, collision-detection
---


# Question
Title: How do I make an actor move to the foreground temporarily in LibGDX scene2d?
I have an inventory UI which is a table in scene2d. Then the table had a bunch of Containers which are basically inventory slots. They have a transparant grey background color. Then in each container is an ItemStack with a picture of an item and a stacksize. When I pull this ItemStack over a container that was created later, it moves behind the container and the transparant grey background will be in front of the item picture. How do I temporarily (or permanently) move it to the foreground so it doesn't matter in front of which container I drag the item?

Example of what happens: https://i.imgur.com/yq4njex.gifv

This is how I create the containers:

```
// Create inventory slots
table.row();
inventorySlots.clear();
for (int i = 0; i < inventory.getInventorySize(); i++) {
    if (i % SLOTS_PER_ROW == 0) table.row();

    Container cont = new Container();
    cont.fill();
    cont.background(Utils.createDrawable(1, 1, new Color(0, 0, 0, 0.4f)));

    inventorySlots.add(cont);
    table.add(cont).prefHeight(50).prefWidth(50).pad(5);
}

```

After that I add each ItemStack to the list of containers/inventoryslots like this:

```
// Add ItemStacks from Items to their respective slot
ArrayList<Item> items = inventory.getItems();
for(Container slot : inventorySlots) {
    Item item = items.get(inventorySlots.indexOf(slot));

    if(item != null) {
        ItemStack itemStack = new ItemStack(item);
        addInventoryEvent(itemStack, items);
        slot.pad(5);
        slot.setActor(itemStack);
    }
}

```

# Answer
> 1 votes
The ZIndex of an Actor describes its position in respect to its siblings (other Actors in the same Group)

you can manipulate it with `Actor.setZIndex()`. There are also convienience methods for your usecase: `Actor.toFront()` and `Actor.toBack()`

The Group class has methods to add Actors in front or behind another Actor. It can allso swap the ZIndex of two of its children.

---
Tags: java, libgdx, gui, scene2d, inventory
---


# Question
Title: How to damp the velocity of an object only in one axis in Box2d?
I want to damp the velocity of a ball linearly on the x-axis. but when applying linear damping on the ball, the damping also applies in the y-axis which makes it look like its floating.

I tried to refer the Manual but it says: "Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. **I generally do not use linear damping because it makes bodies look like they are floating**."

So how can I damp the ball in the axis while there is no damping in the y-axis

# Answer
I guess you will have to implement the dampening yourself. something along the lines of:

```
private static float dampening;

//called every frame
public void dampen(float deltaT){
    Vector2 vel = ball.getBody().getLinearVelocity();
    float newX = vel.x * (1 - delta * dampening);
    vel.x = newX;
    ball.getBody().setLinearVelocity(vel);
}

```

The comment about Dampening looking floaty refers to the fact, that the velocity never reaches 0 this way. So bodys that are only slowed down by dampening look somewhat like hovercraft.

To avoid that you can reduce the velocity by a fixed amount somewhat like friction.

My example would be better if the dampening was applyed as a force to the body instead of setting the velocity, but the math becomes more complicated.

Here is an example of my custom implementation of friction in my top-down game. It works pretty good so far:

```
    // Linar Gleitreibung
default void applyLinearFriction(float deltaT) {
    float fGleit = getFriction().getLinearFriction() * getBody().getMass();
    Vector2 curVel = getBody().getLinearVelocity();
    Vector2 wGleit;
    float fMax;
    // apply friction to full velocity
    wGleit = new Vector2(-curVel.x, -curVel.y);
    fMax = curVel.len() * getBody().getMass() / deltaT;

    if (fGleit > fMax) {
        wGleit.setLength(fMax);
    } else {
        wGleit.setLength(fGleit);
    }
    getBody().applyForceToCenter(wGleit, true);
}

```

sorry im too tired to write that into a clean example right now ;)
> 2 votes

---
Tags: libgdx, box2d
---


# Question
Title: Why is it that I’m still able to call a coroutine from another script, even though I marked it as private?
I have this private coroutine in my WinDialogue script:

```
private IEnumerator ActivateStars(int count)
{
    for (int i = 0; i < count; i++)
    {
        _stars[i].SetActive(true);
        yield return new WaitForSeconds(.3f);
    }
}

```

And somehow I’m still able to call it from my UIManager script:

```
_winDialogue.GetComponent<WinDialogue>().StartCoroutine("ActivateStars", starCount);

```

How can that be if I marked it as private?

# Answer
> 25 votes
When you start a coroutine by providing the method name as a string, then the Unity engine uses reflection to find the method at runtime, which doesn't care about the visibility of methods. This is not unusual for Unity. You might have noticed that methods like `Start` and `Update` are declared `private`, yet the Unity engine invokes them from outside the class.

If you would prefer proper software engineering principles - like names being resolved at compile-time and visibility rules being respected - use the variant of StartCoroutine which takes an IEnumerator instead of a string to denote the method.

```
WinDialogue dialogue = _winDialogue.GetComponent<WinDialogue>()
dialogue.StartCoroutine(dialogue.ActivateStars(starCount));

```

This will give you a compile-time error if `WinDialogue.ActivateStars` is private (or does not return an IEnumerator... or gets called with the wrong arguments... or is misspelled...).

# Answer
> 13 votes
The answer from Philipp is correct; I'd like to extend it slightly by addressing directly your statement:

> somehow I’m still able to call it ... how can that be if I marked it as private?

The question indicates an important but subtle misunderstanding of what "private" applies to. "Private" does NOT mean "cannot be called from outside". Consider:

```
class C
{
  private static void M() { whatever }
  public static Action A() { return M; }
}

```

Any code can call `M()` by invoking `C.A()()`. Notice that in this scenario the call to M is made from code *outside* C; there is no *call* to `M()` inside `C`, merely returning a delegate to it.

And as Philipp's answer notes, there are other ways that code can access `C.M`, such as having been granted sufficient permissions to do private reflection.

What then does `private` mean, if not "this code can only be called from inside `C`?"

`private` means **the name of the thing declared may only be legally referred to by an *identifier* within the *accessibility domain* of a private member**. That is, use of the identifier `M` to refer to the private member `C.M` is only legal inside the *accessibility domain* of `C.M`.

The private accessibility domain for a method of a class is *the region of program text* that falls within the outer `{ }` braces for the class (including partial class declarations and nested classes).

The thing that I'm emphasizing here is that `private` gives a restriction on **the source code of a legal program**. It says that the actual program text `M` may only be used to refer to member `C.M` if that program text appears somewhere inside the braces of the class declaration. An attempt to use the program text `M` outside of the accessibility domain will result in either binding to a *different* thing named `M`, or an error.

But the key thing to understand here is that `private` is all about *the legality of the text of the program's source code*. It is *not* a fact about behaviour at runtime! You can still call a private member; you just can't do it by writing *source code* that uses identifier `M` outside of the declaration of `C`.

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


title: ArgumentOutOfRangeExeption in unity C#

text:
# Question
Title: ArgumentOutOfRangeExeption in unity C#
I keep getting this error:

```
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument,
System.ExceptionResource resource) (at <23c160f925be47d7a4fd083a3a62c920>:0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <23c160f925be47d7a4fd083a3a62c920>:0)
Controller.UpdateDisplays () (at Assets/Scripts/Controller.cs:100)
Controller.ChangeTab (System.Int32 tab) (at Assets/Scripts/Controller.cs:54)
Controller.AddTask () (at Assets/Scripts/Controller.cs:63)

```

I have been trying nonstop for days to figure out what is causing it, but i have found nothgin Here is my code:

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

public class Controller : MonoBehaviour
{
    //Store All
    List<string> taskNames = new List<string>();
    List<string> taskDesc = new List<string>();
    List<int> taskPriorities = new List<int>();
    List<int> taskTab = new List<int>();
    //Active Tab
    List<string> actTaskNames = new List<string>();
    List<string> actTaskDesc = new List<string>();
    List<int> actTaskPriority = new List<int>();
    //Input Fields
    [SerializeField] InputField taskName;
    [SerializeField] InputField taskPriority;
    [SerializeField] InputField taskDescription;
    //Task Displays
    [SerializeField] Text[] taskDisplays = new Text[5];
    //Task Input Field
    [SerializeField] GameObject TaskCreationMenu;
    //Page Display
    [SerializeField] Text pagesDisplay;
    //Other Variables
    int activeTab;
    int activePage;
    private void Start()
    {
        activeTab = 1;
        activePage = 1;
        ChangeTab(1);
    }
    public void ChangeTab(int tab)
    {
        activeTab = tab;

        actTaskNames.Clear();
        actTaskDesc.Clear();
        actTaskPriority.Clear();
        if(taskTab.Count >= 1)
        {
            for (int x = 0; x < taskNames.Count; x++)
            {
                if (taskTab[x] == tab)
                {
                    actTaskNames.Add(taskNames[x]);
                    actTaskPriority.Add(taskPriorities[x]);
                    actTaskDesc.Add(taskDesc[x]);
                }
            }
            UpdateDisplays();
        }
    }
    public void AddTask()
    {
        taskNames.Add(taskName.text);
        taskDesc.Add(taskDescription.text);
        taskPriorities.Add(int.Parse(taskPriority.text));
        taskTab.Add(activeTab);
        ChangeTab(activeTab);
        TaskCreationMenu.transform.localPosition = new Vector3(1120f, -168f, 0f);
    }
    private void UpdatePages(int page)
    {
        if (taskNames.Count > 1)
        {
            int count = actTaskNames.Count;
            int countMod = count % 5;
            count -= countMod;
            int pages = 0;
            if (countMod != 0)
            {
                pages = 1;
            }
            pages += count / 5;
            activePage = page;
            pagesDisplay.text = ("page " + activePage + " of " + pages);
        }
    }
    private void UpdateDisplays()
    {
        int t = 0;
        for(int x = (0 + (activePage - 1 * 5)); x < (5 + (activePage - 1 * 5)); x++)
        {
            Debug.Log(t);
            if (actTaskNames.Count > x)
            {
                taskDisplays[t].text = (actTaskNames[x] + "\n" + actTaskDesc[x] + "\n" + actTaskPriority[x]);
            }
            else
            {
                taskDisplays[t].text = " ";
            }
            t++;
        }
        UpdatePages(activePage);
    }

    public void OpenTaskCreationMenu()
    {
        TaskCreationMenu.transform.localPosition = new Vector3(0, 650, 0);
    }
}

```

And here is a screenshot of my Inspector configuration:

**I found the answer** The line

```
for(int x = (0 + (activePage - 1 * 5)); x < (5 + (activePage - 1 * 5)); x++)

```

is supposed to be

```
for(int x = (0 + ((activePage - 1) * 5)); x < (5 + ((activePage - 1) * 5)); x++)

```

# Answer
**I found the answer**

The line

```
for(int x = (0 + (activePage - 1 * 5)); x < (5 + (activePage - 1 * 5)); x++)

```

is supposed to be

```
for(int x = (0 + ((activePage - 1) * 5)); x < (5 + ((activePage - 1) * 5)); x++)

```
> 1 votes

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


# Question
Title: Points evenly spaced along a bezier curve
I have looked around for a while and I can't find a solution to this problem. Let's say I have a cubic bezier curve (defined by 4 points) and I want to get a set of points that are spaced evenly along the curve. Think of placing a text along a curve for an example.

Now the problem is that if I input `t` (interpolation value from 0-1) with a constant increment the points are not evenly spaced. The distance along the curve is smaller when the curve makes a turn and longer when the curve is straight.

So how do I place points evenly along a bezier curve?

# Answer
Well it has been some time...

But I was finally able to solve this problem!

Everything you need is in this post: Moving ships between two planets along a bezier, missing some equations for acceleration
> 2 votes

# Answer
It's more of a math question. So a bezier curve has the following formula, both in the `x` and `y` component.

```
B_x(t) = (1-t)^3 * P0_x + (1-t)^2 * t * P1_x + (1-t) * t^2 * P2_x + t^3 * P3_x
B_y(t) = (1-t)^3 * P0_y + (1-t)^2 * t * P1_y + (1-t) * t^2 * P2_x + t^3 * P3_y

```

Length traveled by `t` along a curve `gamma` is given by:

```
length_gamma(t) = integration( sqrt( derivative(  gamma_x(s)  ) ^2 + derivative(  gamma_y(s)  ) ^2 ) )

```

There's no human-writable solution to the integral, so you have to approximate.

Replace the `gamma(t)` by the expression `B(t)` to get the length `length_B` traveled by `t` along the bezier segment. Let's say it travels from `0` to `L`.

Now pick `n` values between `0` and `L` that correspond to the evenly spaced points. For examples, lengths of the form `k*L/n` for `k` from `0` to `n`.

Now you need to inverse the function `length_B`, so you can compute the `t` back from the length `l`. It's quite a lot of math and I'm lazy as hell, try doing it yourself. If you can't, you can go to the math stackexchange. For a more complete answer, you can go there anyway.

Once you have that inverse `length_B` function (or a reasonable approximation), you process is quite simple.

* Create lengths `l[k]` of given path distance away from the origin `(P0_x,P1_x)`.
* Compute their corresponding `t[k]` using `length_B_inverse`.
* Positing the points using `(B_x(t[k]),B_y(t[k]))`.
> 3 votes

# Answer
Just to expand on what Marco said, a common technique for doing this is to walk down the curve in much smaller increments than the fixed length steps you want to take and store the resulting output point (and perhaps distance?) in a table.

Then, you go through the table and discard all the entries except those points that are closest to the integer multiples of the distances you want to walk.

Then you are left with a table you can index directly at runtime very quickly. If you want to go to the spot that is 5 times the size of your distance you look in your table at index \[5\].

Note that you could do the two steps in one and not actually store the extra items in the table to begin with, but it's easier to visualize and understand in two steps.

I once saw a technique for actually calculating this on the fly without precalculating a table (it didn't use iteration / root finding either!), but unfortunately I can't remember the details at all ):

If i remember it or find it, i'll post the info!
> 0 votes

# Answer
Step 1 - Generate N+1 points by interpolating the curve in increments of 1/N. N should be large enough for good visual results but small enough to be easily computed. A value of 50 should be OK for most situations but it should be tuned for your specific case. I will call this the "interpolated points".

Alternatively you can generate a short list of segments and recursively break each segment that is longer than the desired maximum segment length (initially you should generate at least four segments to account for S curves where the start is very close to the end).

Step 2 - "Walk the line" using the interpolated points and the spacing you want between each point.

I'll leave it here my Unity code:

```
public static Vector2[] InterpolateBezier(Vector2 start, Vector2 startControlPoint,
    Vector2 end, Vector2 endControlPoint, int segments)
{
    Vector2[] interpolated = new Vector2[segments + 1];
    interpolated[0] = start;
    interpolated[segments] = end;

    float step = 1f / segments;
    for (int i = 1; i < segments; i++)
    {
        interpolated[i] = GetBezierPosition(start, startControlPoint, end,
            endControlPoint, i * step);
    }

    return interpolated;
}

public static Vector2 GetBezierPosition(Vector2 start, Vector2 startControlPoint,
    Vector2 end, Vector2 endControlPoint, float t)
{
    float omt = 1f - t;
    float omt2 = omt * omt;
    float t2 = t * t;

    return
        start * (omt2 * omt) +
        startControlPoint * (3f * omt2 * t) +
        endControlPoint * (3f * omt * t2) +
        end * (t2 * t);
}

public static List<Vector2> WalkLine(Vector2[] points, float spacing, float offset = 0)
{
    List<Vector2> result = new List<Vector2>();

    spacing = spacing > 0.00001f ? spacing : 0.00001f;

    float distanceNeeded = offset;
    while (distanceNeeded < 0)
    {
        distanceNeeded += spacing;
    }

    Vector2 current = points[0];
    Vector2 next = points[1];
    int i = 1;
    int last = points.Length - 1;
    while (true)
    {
        Vector2 diff = next - current;
        float dist = diff.magnitude;

        if (dist >= distanceNeeded)
        {
            current += diff * (distanceNeeded / dist);
            result.Add(current);
            distanceNeeded = spacing;
        }
        else if (i != last)
        {
            distanceNeeded -= dist;
            current = next;
            next = points[++i];
        }
        else
        {
            break;
        }
    }

    return result;
}

```
> 0 votes

# Answer
Here's some algorithm that gives pretty ok results:

```
  Point Index(float pos) const
  {
    int count = p.NumPoints();
    Vector val(0.0,0.0,0.0);
    for(int i=0;i<count;i++)
      {
        val += bin(pos,i,count-1)*Vector(p.Points(i));
      }
    return Point(val);
  }
  float bin(float pos, int i, int n) const
  {
    return float(ni(n,i)) * pow(double(pos), double(i))*pow(double(1.0-pos), double(n-i));
  }
  int ni(int n, int i) const
  {
    if (i==0) { return 1; }
    if (n==i) { return 1; }
    return ni(n-1,i-1)+ni(n-1,i);
  }

```
> -1 votes

---
Tags: interpolation, curves, beziers
---


# Question
Title: How to store references to scene objects in prefabs?
i am instantiating a few game objects in my scene using prefabs and i would like to attach a script to some of them to do something at a certain time but for that i need to reference to scene objects and its not allowing me. anyone know why? and whats the workaround?

i can pull those prefabs into my scene and use them as game objects but that would destroy the idea of prefabs isn't?

# Answer
> 24 votes
In the editor, prefabs can only reference other prefabs. Prefabs are supposed to be shared between scenes. That means they can't rely on the object being present in every scene.

If you need them to reference something in the scene, you need to get that reference at runtime. There are several ways to do that.

* Attach the reference to the object which instantiates the prefabs and have the spawning script set it on every object it instantiates:

`GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);` `bullet.GetComponent<BulletScript>().shooter = gameObject;`
* Search for the game object in the Start method of your prefab.
* Store the reference to the object in a global variable (a `public static` variable of an appropriate class) so all the instantiated prefabs can access it.

# Answer
> 4 votes
Unity does not allow you to reference scene objects to prefabs. It allows any other reference. It's because prefabs have a template-like nature and thus are unaware of the scene.

There are many workarounds for this case, most of them involve a static variable.

1. Assign a Tag to your scene object and then find it by searching through objects

```
var all = FindObjectsOfType<GameObject>();
foreach ( var item in all ) {
    if (item.Tag.CompareTo("MyTag") == 0)
        return item;
}
//or
var item = GameObject.FindWithTag("MyTag");

```
2. Add a script to your scene object and store the reference there

```
internal GameObject MyRef;
void Awake() { MyRef = this; }

```
3. Add an empty game object (reference manager) in your scene with a script to store all references

```
//assign these in inspector
public GameObject MyRef1;
public GameObject MyRef2;

```

## Note that

in case 2,3 you may use static variables or singleton pattern.

e.g.

case 2:

```
public class SceneObject1 : MonoBehaviour
{
    public static GameObject MyRef { get; private set; }
    void Awake() { MyRef = this; }
}

```

case 3:

```
public class RefManager : MonoBehaviour
{
    static RefManager instance;
    void Awake() { instance = this; }

    public GameObject MyRef1;

    //use this in prefab script
    public static GameObject MyRef1 { get { return instance.MyRef1; } }
}

//in prefab
var inPrefabVariable = RefManager.MyRef1;

```

# Answer
> 1 votes
You should definitively read the Unity manual about prefabs

> The prefab acts as a template from which you can create new object instances in the scene.

The purpose of prefabs **is** to be instantiated into the scene.

When in the Project tab, it acts as a "regular file" and must be independant from any object in any scene (but it can have references from other prefabs also in the Project tab) so as to be reusable in any scene.

The advantage of prefabs is, when you edit the values of one of the and hit "Apply", all the instances in the other scenes will have the new values. (Except if you have already overriden the values of the instance)

You have to instantiate the prefab into your scene so as to be able to link objects of the scene into your prefab. The instantiation and creation of the links to the prefab instance can be done using the inspector, or, at runtime, using code.

# Answer
> 1 votes
I think there is a way around this. If I am getting your question right, you want your prefab's public variables to have objects reference from the scene. What you can do is make prefab instances particularly for that scene. Which means

1. you can drag and drop you prefab in hierarchy.
2. Unpack the Prefab object in hierarchy
3. Now attach the references of other object to the script of Unpacked Prefab.
4. Disable the Unpacked Prefab in hierarchy.
5. Now where ever you have code to instantiate the prefab originally, replace it with this Unpacked Prefab object from hierarchy.
6. Set Active(true) the instantiated object.

What basically we are doing here is instead of using prefab we are using object as a reference for instantiating objects. And since the object are is disabled in hierarchy it is not working but holding all the property of its prefab, just like the prefab itself.

Note while instantiating the object, don't forget to SetActive true. Here is the example how to do it :

```
GameObject cloneObject = Instantiate(Object);
cloneObject.SetActive(true);

```

# Answer
> 0 votes
One workaround is to note the instanceID of any scene object references, they are merely ints, and will save to the prefab just fine. In order to restore missing object references in new instances of the prefab, write a script that searches for GameObjects whose instanceID match with the ones we stored in the prefab. To get a full list of all available GameObjects in all open scenes, you can use eg GameObject.FindObjectsOfType(typeof(GameObject));

I'm not suggesting this is a robust solution, or a good idea, just that it is possible to deal with this kind of scenario.

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


# Question
Title: Initializing Variables, Difference between Awake and in-class initialization
```
public class ExampleClass: MonoBehaviour
{
   int exampleVariable = 0;
   int exampleVariableForAwake;
   void Awake()
   {
      exampleVariableForAwake = 0;
   }
}

```

What is the difference between `initializing a variable at declaration` vs. `initilize in Awake`?
Which I understand is to be used in place of constructors in Unity C#, welcome to correct me if I'm wrong.

Which usage is considered a proper convention by the community, if any?

Same question might also be in order for `Properties`, so I'll leave that open ended.

# Answer
> 1 votes
Initializing something at its declaration:

* Executes immediately as the object is constructed - both at runtime and in the editor, so you can assign sensible defaults when you add a new component, even without executing `Awake()` in edit mode.
* Limits you to expressions that don't reference other members of the object. (Since, by definition, the initializers run before the object is safely initialized!)

Supplying values in `Awake()`:

* Runs after the object is constructed, but still runs to completion before the object is returned from a call to `Instantiate()` or `AddComponent()`, and before `OnEnable()`, `Start()` or other messages can fire.
* Like `Start()`, it's guaranteed to run only once for the lifetime of an object (whereas `OnEnable()` will re-run every time the component is disabled and re-enabled). But unlike either, it will run even if the script is instantiated in an already-disabled state.
* Allows you to vary the initialization of some fields based on the values of other fields or other context related to the parent game object, use intermediate temporary variables to compute the right initial values, or perform more complicated algorithms than you can easily fit in an initializer expression.
* Does not execute in edit mode unless you add extra attributes to force it to do so

You also have another option, `Reset()`:

* Executes *only* in the editor, when you add a new component or reset the component in the Inspector. Does not run in the built executable (so make sure any results you want to carry over are in public or serialized fields that will be saved).
* Can run complex computations like `Awake()`, but since it's still doing all its work before build time, the only runtime cost is deserializing the saved results.

Or a related method `OnValidate()`:

* Executes *only* in the editor, after `Reset()`, and whenever the developer makes a change to the component via the Inspector.
* Lets you re-visit your initial values in light of new information, enforce custom constraints on configuration parameters, or log warnings and errors in case of mis-configuration.

So, boiling it down:

1. Does the initial value not depend on any other aspects of the object, and fit concisely in the space of the declaration?

-\> Just initialize it when you declare it. No extra method to write, and it's obvious to a reader at a glance.
2. Does the value require more computation or relation between aspects of the object, but depend only on things we know at edit time?

-\> Use `Reset()` or `OnValidate()` to do the work ahead of time, so you can just deserialize the answer at runtime.
3. Does the value need to be revisited every time we disable / re-enable the component?

-\> Use `OnEnable()`

This can be handy if you're editing code while your game is running in the editor: all your objects will be disabled, serialized, swapped to the newly-compiled code, deserialized, and re-enabled, so you can use this to do any fix-ups to ensure the game can continue smoothly with the new code.
4. Does the value need to be initialized just once, before `FixedUpdate()`/`Update()`, but not necessarily before other scripts try to invoke our other member methods?

-\> Use `Start()`
5. Do we need the value initialized, just once, but before anyone can possibly call any of our other methods?

-\> Use `Awake()`

The reason I recommend everything else before `Awake()` is that if you have multiple scripts whose initialization depend on one another, you can run into annoying bugs where in editor the scripts each get awakened in the desired order, but in a build the depender gets awoken before the dependee. If most of your dependent initialization is happening in `Start()`, you can fix this bug by moving just the dependee's setup to `Awake()`. But if everything's in `Awake()` already, then you have to try to kludge around it with script execution order controls or lazy/on-demand initialization.

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


# Question
Title: How can I make my C++ game which installs its own DLL files?
Example: Minecraft is the same single .exe from the moment it's downloaded. Installations occur fairly quickly (very painless) for the selected version.

My case: I have a C++ game which uses the following libraries: \- SFML \- GLAD \- GLEW \- GLM \- ASSIMP

How can I make my game a single .exe which installs these libraries in the directory I want, if they're not there on execution, and also executes the game? (presumably that's how I imagine it should work).

I think I already made my point, but in essence I want the game to be a single .exe managing all external dependencies.

# Answer
According to this article by Microsoft, the first place where Windows will look for DLL files is always the directory with the .exe file that requested them. So you don't actually need to install the DLL files. You can just put these files into the same directory as the game executable.
> 4 votes

# Answer
There are multiple topic to discuss here.

* "portable" do I mean cross-platform executable = **Cross platform portability**
* How can I make my game a single .exe which installs = **Easy to distribute**

---

## Cross platform portability

* Try to **wrap platform-specific functionality in your "Game engine"** layer as much as you can. Never let game code touch platform specific function directly such as input, file, etc. That's what SFML or SDL, or today major game engine like Unity or Unreal has been doing.
* You are already using middle layer such as SFML, fine, that save you lots of OS code. But you still have to **take caution if your game code access anything directly** from, let say `<Windows.h>`, that would be another challenge to cleanup.
* For true portability to completely different hardware such as console/mobile, even access to OpenGL should be hidden behind another layer. Because OpenGL still has some difference on mobile. Or even console has their own graphics API.

---

## Easy to distribute

* You cannot completely ignore DLL, some basic library such as libpng zlib allow you to do **static linking** which merge code into your exe. Thus not requiring extra DLL.
* But some library has **different license model** such as **LGPL** will require any program (or game in your case) that statically linked to it be "Open sourced", unless you use it as library (DLL).
* Some bigger commercial library only has to be distributed with DLL such as **FMOD**.
* To distribute, for starter, study your middle ware and library each, how can you deploy with them?
* For instance, something like GLEW has an option to static link thus skipping `glew32.dll`.
* Even for SFML itself has an option to link statically, Read more from this old thread. To search more, your keyword would be something like `sfml deploy`.

> If you compile the application with the Visusal C++ compiler and link the runtime library dynamically you'll have to ship also the C++ redistrubitions. If you also link SFML dynamically you'll have to ship the SFML dlls too ofcourse. If you ship everything that's needed it should run on all (newer = XP \>) Windows systems.

* For an example playground, try some free game in itch.io see how people distributing game in their zip file. (Again, your SMFL will has its own way to distribute) try other people game package and see what feel best for you.
* But for rule of thumb, you should ship any DLL included in your working EXE folder

## Related on Stackoverflow
> 1 votes

# Answer
It seems like you're over-thinking your requirement when all that you really need is just a simple installer.

Among other thing, an installer can:

* Check system requirements.
* Resolve library dependencies.
* Ensure correct library versions.
* Make sure everything goes in the correct folder.
* Make sure that the whole thing co-exists peacefully with other programs on the computer.

Other functionality an installer might help you with might include:

* Verifying and repairing the installation, if required.
* Managing add-on content.
* Managing updates.
* Launching the game.

Traditionally these functions would be a separate program - often called a launcher - but there's no reason why they can't be rolled into the same program as the installer.

One hallmark of a robust system is that it should be simple and obvious to do the right thing, but more difficult to do the wrong thing: if you're fighting against the system then you're probably doing it wrong. An installer can help you achieve this, particularly for non-technical end-users.
> 1 votes

# Answer
Note: I added new answer (for completely new unrelated approach) as OP had update his/her question significantly

Aside from **shipping DLL normally** or do an **Installer**. Another way to create single EXE in hacky way is using **App packer**

## What is it?

It just create new EXE which encapsulate other resource you would like to pack.

This gives similar result to **GameMaker**'s Standalone EXE option, with all assets packed inside, and probably its dependency (DLL) too.

## Potential issue

There might be compatibility issue later, GameMaker itself even trying to phase this feature out.

> Not possible natively. The utility that GM used to pack single .exe exports is slowly being depreciated by Microsoft.

> single executable's don't work on every platform. Microsoft changed the tool so that something built on windows 8 (and above probably) don't work on anything below that. It's not our tool, we just use the MS one. So this is a horrible choice for a standard tool.

Again, I want to point that, for sane/normal solution, you should normally ship DLL with game exe you distributed. I just give out this answer to let you aware of such approach.
> 0 votes

---
Tags: c++, installer
---


# Question
Title: How to search for all uGui scripts in scene in the Unity editor?
I have many game objects whose properties I need to edit because of a bug/error.

However, this is very time consuming, because I need to check each game object one by one.

Is there any way to search for all game objects that (for example) contain **uGui Scripts** in a scene?

# Answer
> 0 votes
Yes, Unity will allow you to use the search box at the top of the hierarchy panel to filter the hierarchy view to objects containing certain classes of script.

For instance, you can type "collider" to find all objects with a 3D collider like a BoxCollider, SphereCollider, etc. Or you can type "collider2d" to find objects with 2D colliders (which do not show up in the previous search, despite having the word "collider" in them, which makes it seem that Unity is recognizing this as the name of a parent class and searching for instances of any subclass, rather than checking whether each component name contains the search string).

To find UI components, you can either type the name of the specific component (eg. "image"), the name of a common base class (eg. "uibehaviour"), or a common component all UI objects share ("recttransform")

---
Tags: unity, asset-workflow
---


title: SDL2 Application RAM Usage

text:
# Question
Title: SDL2 Application RAM Usage
I am developing a game that uses SDL2, SDL2 Image & SDL2 TTF, while using clang compiler under Linux. When running it in release mode(compiler flags: -Wall -O3) there is a **constant** usage of about 52MB, I've checked with Valgrind for memory leaks and there are none.

My Game class:

```
#include "Game.h"

Game::Game(Configurations configurations) {
  _graphics = std::make_unique<Graphics>(configurations.windowWidth,
                                         configurations.windowHeight,
                                         configurations.flags);
  _gameState = std::make_unique<GameState>(configurations.windowWidth,
                                           configurations.windowHeight);
  _mouseInput = std::make_unique<MouseInput>(MouseInput{-1, -1, 0});
  _fpsCounter = std::make_unique<FPSCounter>();
  _worldWidth = configurations.worldWidth;
  _worldHeight = configurations.worldHeight;
  _fpsCap = configurations.fpsCap;
}

auto Game::start() -> void {
  _fpsCounter->fpsInit();
  gameLoop(_fpsCap);
}

auto Game::convertStateToGraphicsMap()
    -> std::vector<std::pair<TileType, SDL_Point>> {
  std::vector<std::pair<TileType, SDL_Point>> convertedVector;

  for (auto o : _gameState->getGameObjects()) {
    convertedVector.push_back(
        std::make_pair(o.getTileType(), SDL_Point{(int)o.getPosition().x,
                                                  (int)o.getPosition().y}));
  }

  std::remove_if(convertedVector.begin(), convertedVector.end(),
                 [this](std::pair<TileType, SDL_Point> o) {
                   return o.second.x - (int)_gameState->getCamera().x < 0 ||
                          o.second.y - (int)_gameState->getCamera().y < 0 ||
                          o.second.x - (int)_gameState->getCamera().x >
                              _graphics->getWindowWidth() ||
                          o.second.y - (int)_gameState->getCamera().y >
                              _graphics->getWindowHeight();
                 });

  for (auto &o : convertedVector) {
    o.second.x -= _gameState->getCamera().x;
    o.second.y -= _gameState->getCamera().y;
  }
  return convertedVector;
}

auto Game::checkForSDLQuitEvents() -> bool {
  SDL_Event event;
  while (SDL_PollEvent(&event)) {
    switch (event.type) {
    case SDL_QUIT:
      std::cout << "closeRequested! quiting\n";
      return true;
    }
  }
  return false;
}

auto Game::validatePlayerPosition() -> void {
  Vector2d<float> &playerPosition = _gameState->getPlayer()->getPosition();
  if (playerPosition.x < 0) {
    playerPosition.x = 0;
  }
  if (playerPosition.y < 0) {
    playerPosition.y = 0;
  }
  if (playerPosition.x > _worldWidth) {
    playerPosition.x = (float)_worldWidth;
  }
  if (playerPosition.y > _worldHeight) {
    playerPosition.y = (float)_worldHeight;
  }
}

auto Game::handleMouseState(float fps) -> void {
  _mouseInput->mouseState =
      SDL_GetMouseState(&_mouseInput->mouseX, &_mouseInput->mouseY);
  if (_mouseInput->mouseState & SDL_BUTTON(SDL_BUTTON_LEFT)) {
    // printf("SDL_MOUSEBUTTONDOWN\n");
    auto halfWindowWidth = _graphics->getWindowWidth() / 2;
    auto halfWindowHeight = _graphics->getWindowHeight() / 2;
    _gameState->setCamera(
        {_gameState->getPlayer()->getPosition().x - halfWindowWidth,
         _gameState->getPlayer()->getPosition().y - halfWindowHeight});
    _gameState->getPlayer()->onDestinationSelected(
        {(float)_mouseInput->mouseX + _gameState->getCamera().x,
         (float)_mouseInput->mouseY + _gameState->getCamera().y},
        fps);

    validatePlayerPosition();
  }
}

auto Game::gameLoop(float fpsCap) -> void {
  float minFrameRateDelay = MILLISECOND_IN_SECOND / fpsCap;
  while (true) {
    // process events
    if (checkForSDLQuitEvents())
      return;

    _graphics->clearRender();
    float averageFPS = _fpsCounter->getAverageFramesPerSecond();
    handleMouseState(averageFPS);
    _graphics->renderGrid(convertStateToGraphicsMap());
    _graphics->renderText("FPS: " + std::to_string(averageFPS),
                          {255, 255, 0, 255}, 0, 0);
    _graphics->presentRender();

    if (fpsCap < averageFPS) {
      SDL_Delay(minFrameRateDelay);
    }
    _fpsCounter->fpsThink();
  }
}

auto Game::loadMap(const char *filename) -> void {
  int current, mx, my, mw, mh;
  std::ifstream in(filename);
  if (!in.is_open()) {
    std::cout << "Failed to open map file." << std::endl;
    return;
  }
  in >> mw;
  in >> mh;
  in >> mx;
  in >> my;
  for (int i = 0; i < mh; i++) {
    for (int j = 0; j < mw; j++) {
      if (in.eof()) {
        std::cout << "Reached end of map file too soon." << std::endl;
        return;
      }
      in >> current;
      if (current != 0) {
        GameObject tmp(DEFAULT_OBJECT_SIZE, 0, {0, 0}, HUMAN_FEMALE);
        if (current == 2 || current == 4) {
        }
        _map.push_back(tmp);
      }
    }
  }
  in.close();
}

Game::~Game() { std::cout << "Game destructor\n"; }

```

My Graphics class:

```
#include "Graphics.h"

Graphics::Graphics(Uint32 windowWidth, Uint32 windowHeight, Uint32 flags)
    : _windowWidth(windowWidth), _windowHeight(windowHeight), _flags(flags) {
  if (initializeSdl()) {
    _window = std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>>(
        createWindow(), SDL_DestroyWindow);
    _renderer =
        std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>>(
            createRenderer(), SDL_DestroyRenderer);
    _textures = std::unique_ptr<
        std::map<TileType, SDL_Texture *>,
        std::function<void(std::map<TileType, SDL_Texture *> *)>>(
        loadAllTextures(), Graphics::destroyAllTextures);
    _baseTile =
        std::unique_ptr<RectAndTexture, std::function<void(RectAndTexture *)>>(
            createBaseRect(), destroyRectAndTexture);
    _globalFont = std::unique_ptr<TTF_Font, std::function<void(TTF_Font *)>>(
        createRegularFont(), destroyFont);
    std::cout << "Graphics created\n";
  }
}

auto Graphics::initializeSdl() -> bool {
  // attempt to initialize graphics and timer system
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0) {
    std::cout << "error initializing SDL: \n" << SDL_GetError();
    return false;
  }
  if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
    std::cout << "could not initialize sdl2_image: \n" << IMG_GetError();
    return false;
  }
  if (TTF_Init() == -1) {
    std::cout << "SDL_ttf could not initialize! SDL_ttf Error: \n"
              << TTF_GetError();
    return false;
  }
  return true;
}

auto Graphics::createWindow() -> SDL_Window * {
  SDL_Window *window = SDL_CreateWindow(
      "InvasiveSpecies", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
      _windowWidth, _windowHeight, _flags);
  if (!window) {
    std::cout << "error creating window: \n" << SDL_GetError();
    SDL_Quit();
    return nullptr;
  }
  return window;
}

auto Graphics::createRenderer() -> SDL_Renderer * {
  // create a renderer, which sets up the graphics hardware
  Uint32 render_flags = SDL_RENDERER_ACCELERATED;

  SDL_Renderer *renderer = SDL_CreateRenderer(_window.get(), -1, render_flags);
  if (!renderer) {
    std::cout << "error creating renderer: \n" << SDL_GetError();
    quitSdl();
    return nullptr;
  }

  return renderer;
}

auto Graphics::loadTexture(const char *imagePath) -> SDL_Texture * {
  SDL_Texture *texture = IMG_LoadTexture(_renderer.get(), imagePath);
  if (!texture) {
    std::cout << "error creating texture\n";
    quitSdl();
    return nullptr;
  }
  return texture;
}

auto Graphics::createRectFromTexture(SDL_Texture *texture) -> RectAndTexture * {
  auto *dest = new SDL_Rect();
  SDL_QueryTexture(texture, nullptr, nullptr, &dest->w, &dest->h);
  auto *rectAndTexture = new RectAndTexture{dest, texture};
  return rectAndTexture;
}

auto Graphics::createBaseRect() -> RectAndTexture * {
  RectAndTexture *baseTile = createRectFromTexture((*_textures)[SOIL]);
  return baseTile;
}

auto Graphics::clearRender() -> void { SDL_RenderClear(_renderer.get()); }

auto Graphics::presentRender() -> void { SDL_RenderPresent(_renderer.get()); }

auto Graphics::renderGrid(
    const std::vector<std::pair<TileType, SDL_Point>> &gameObjectsPositionsMap)
    -> void {
  renderGridBackground();
  renderGameObjects(gameObjectsPositionsMap);
}

auto Graphics::renderGameObjects(
    const std::vector<std::pair<TileType, SDL_Point>> &gameObjectsPositionsMap)
    -> void {
  for (const auto &current : gameObjectsPositionsMap) {
    _baseTile->texture = (*_textures)[current.first];
    _baseTile->rect->x = current.second.x;
    _baseTile->rect->y = current.second.y;
    renderTexture(_baseTile.get());
  }
}

auto Graphics::renderGridBackground() -> void {
  // printf("renderGridBackground\n");
  int tileWidth = _baseTile->rect->w;
  int tileHeight = _baseTile->rect->h;
  _baseTile->texture = (*_textures)[SOIL];
  for (int i = 0; i < _windowWidth; i += tileWidth) {
    for (int j = 0; j < _windowHeight; j += tileHeight) {
      _baseTile->rect->x = i;
      _baseTile->rect->y = j;
      renderTexture(_baseTile.get());
    }
  }
}

auto Graphics::renderTexture(RectAndTexture *rectAndTexture) -> void {
  SDL_RenderCopy(_renderer.get(), rectAndTexture->texture, nullptr,
                 rectAndTexture->rect);
}

auto Graphics::getImagePathStringByTileType(TileType tileType) -> const char * {
  switch (tileType) {
  case TileType::SOIL:
    return SOIL_IMAGE_PATH;
  case TileType::GRASS:
    return GRASS_IMAGE_PATH;
  case TileType::STONES:
    return STONES_IMAGE_PATH;
  case TileType::HUMAN_MALE:
    return HUMAN_MALE_IMAGE_PATH;
  case TileType::HUMAN_FEMALE:
    return HUMAN_FEMALE_IMAGE_PATH;
  default:
    break;
  }
  return nullptr;
}

auto Graphics::loadAllTextures() -> std::map<TileType, SDL_Texture *> * {
  auto texturesMap = new std::map<TileType, SDL_Texture *>();
  for (auto currentTileType : tileTypeVector) {
    (*texturesMap)[currentTileType] =
        loadTexture(getImagePathStringByTileType(currentTileType));
  }
  return texturesMap;
}

auto Graphics::destroyAllTextures(
    std::map<TileType, SDL_Texture *> *texturesMap) -> void {
  for (auto const &p : *texturesMap) {
    SDL_DestroyTexture(p.second);
  }

  texturesMap->clear();
  delete texturesMap;
  std::cout << "destroyAllTextures done\n";
}

auto Graphics::destroyFont(TTF_Font *font) -> void {
  TTF_CloseFont(font);
  std::cout << "destroyFont done\n";
}

auto Graphics::destroyRectAndTexture(RectAndTexture *rectAndTexture) -> void {
  delete rectAndTexture->rect;
  //    SDL_DestroyTexture(rectAndTexture->texture); //already freed at
  //    destroyAllTextures()
  delete rectAndTexture;
}

auto Graphics::renderText(const std::string &textureText, SDL_Color textColor,
                          int x, int y) -> void {
  SDL_Surface *textSurface =
      TTF_RenderText_Solid(_globalFont.get(), textureText.c_str(), textColor);
  SDL_Texture *textTexture = nullptr;
  if (textSurface == nullptr) {
    std::cout << "Unable to render text surface! SDL_ttf Error: \n",
        TTF_GetError();
  } else {
    // Create texture from surface pixels
    textTexture = SDL_CreateTextureFromSurface(_renderer.get(), textSurface);
    if (textTexture == nullptr) {
      std::cout << "Unable to create texture from rendered text! SDL Error: \n"
                << SDL_GetError();
    } else {
      std::unique_ptr<RectAndTexture, std::function<void(RectAndTexture *)>>
          baseTile = std::unique_ptr<RectAndTexture,
                                     std::function<void(RectAndTexture *)>>(
              createRectFromTexture(textTexture), destroyRectAndTexture);
      baseTile->rect->x = x;
      baseTile->rect->y = y;
      renderTexture(baseTile.get());
      baseTile.reset();
      SDL_DestroyTexture(textTexture);
    }

    // Get rid of old surface
    SDL_FreeSurface(textSurface);
  }
}

auto Graphics::getFontFromFile(const char *file, int ptsize) -> TTF_Font * {
  TTF_Font *gFont = TTF_OpenFont(file, ptsize);

  if (gFont == nullptr) {
    std::cout << "Failed to load lazy font! SDL_ttf Error: \n"
              << TTF_GetError();
  }

  return gFont;
}

auto Graphics::createRegularFont() -> TTF_Font * {
  return getFontFromFile(FONT_PATH, FONT_SIZE);
}

auto Graphics::quitSdl() -> void {
  // these must be here or else they will get called after SDL_Quit()
  _globalFont.reset();
  _textures.reset();
  _baseTile.reset();
  _renderer.reset();
  _window.reset();
  TTF_Quit();
  IMG_Quit();
  SDL_Quit();
}

Graphics::~Graphics() {
  std::cout << "Graphics destructor\n";
  quitSdl();
}

```

The assets for the game contains .png and .tff files with a total size of about 34KiB.

The rest of the code is in My GitHub repo

Is the usage of about 50MB RAM at runtime is normal under these conditions?

# Answer
> 1 votes
I've tested the application under Windows 7, and it takes about 8MB RAM (under linux it was about 50MB) moreover the FPS is higher: about 600, while in linux it was about 370. I presume the performance drop in linux is due to poor GPU driver support, that can result in higher memory consumption and lower FPS, furthermore I am printing some output to a separated terminal window, so it is possible that Windows CMD is more lightweight than the terminal used under my linux distro(Manjaro).

Makes me think that developing games under linux is maybe not such a good idea especially since my GPU driver is not supported. So I guess ill continue the development under Windows.

---
Tags: c++, sdl2
---


title: OpenGL Viewport inside of a Viewport

text:
# Question
Title: OpenGL Viewport inside of a Viewport
I'm creating a labyrinth in opengl, and I'm trying to create a minimap. For that, I thought of creating a viewport inside of a viewport. I already tried following a tutorial from Lazy Foo, and I can create the second viewport, but instead of putting a map inside the second viewport, it puts my whole game there. How can I fix this?

# Answer
> 1 votes
glViewport lets you control the part of the screen where the output of your gl drawing commands will get rendered. It affects the gl commands that you issue after setting up the viewport. So, if you want to render the game to full screen and a minimap to a small portion, then:

1. set glViewport to the entire screen, render game
2. set glViewport to the minimap size and location, render minimap

And do these on every frame.

# Answer
> 1 votes
You need two scenes.

It looks like you know how to render both viewports correctly; so I'll not cover that.

You'll first render the main game view (the first scene), like you're currently doing. Now, instead of redrawing the same objects again for your mini-map, you'll need to define only a *subset* of your game objects so that you can render only those (your second scene) in your minimap.

One way of achieving this is to create a scene graph organized like such:

```
TopNode
+ Map-elements
|+ ground
|+ walls
||- [all the walls objects]
|+ trees
| - [all the trees objects]
+ Dynamic-elements
 + Player-character
 + enemies
 |- [all the enemies objects]
 + loot
  - [all the loot objects]

```

You first render your `TopNode` in your first viewport, which will render everything, then you only render the `Map-elements` node in your second viewport (your minimap). This will only render the static map elements that you want there.

# Answer
> 1 votes
You can render your minimap scene to the framebuffer texture, than render this texture on a 3D quad in front on the screen. This way you can create a cool looking 3D HUD for your game. You can learn more about this technique here.

---
Tags: opengl, c++, 3d, viewport
---


# Question
Title: Unity Profiler - How do I correct Audio (WASAPI) Feeder issues?
I've got the following data after running the Unity Profiler:

If I'm reading this correctly, the thing that's driving me down to ~1 FPS is the CPU Audio. I can't understand what's going on here, though, because there isn't any audio in my game right now.

# Answer
tl;dr: The Audio (WASAPI) Feeder isn't doing anything; it's just sitting idle. Something else is using the time and, spoiler alert: it's the GPU.

Here are the steps:

1. Ensure that GPU profiling is enabled
2. If GPU profiling gives you an error like, "GPU profiling is not supported by the graphics card driver," then enable "Graphics Jobs (Experimental)" in the player settings (details later)
3. Re-run with the GPU profiling enabled.
4. Notice that, in the GPU profiler, the rendering is what's taking all the time.

For me, I am developing on a laptop with a mobile version of an nVidia card, which seems like might be the reason for the GPU profiling error, and then I'm guessing that error is why GPU wasn't listed with the other profilers.

I noticed that "Other" took all the time in the GPU, but I realized later that "Other" is the editor, because I was using the Scene window to move around the scene. When I clicked over to the Game window and moved the player camera through the scene then the GPU rendering went from "Other" to "Opaque."

Finally, here's where the Graphics Jobs (Experimental) setting is located:
> 1 votes

---
Tags: unity, audio, profiling, profiler
---


title: Make enemy follow player intelligently

text:
# Question
Title: Make enemy follow player intelligently
I was trying to make a script to make my enemy follow my player intelligently (but not too much) and I want to know if there was a better way to do it (of course there is but I wanted to find a way myself) Here is what I did: I wanted my enemy to detect the player when he approach a certain distance from him. I have a varibale to determine what distance the nemy have to back up (when player is too close) and when it has to follow the player (player too far). Now, I didn't wanted the enemy to just forgot there is an intruder when the player goes around a corner and they can't see him. When the enemy sees the player directly (raycast), they rotate toward him and start following him directly by normalizing the difference of their 2 position. Now is the tricky part i'm not sure about. My player has a list that keeps the 1000 last positions of my player and that update every 0.01 second to add the lastest position and remove the oldest. If the enemy can't see the player directly (!raycast) he goes through all the positions in the list by checking for every Vector3:

1-is there something between the enemy and this position ?

2-is there something between this position and the player ?

Then it add up the distance between the enemy and the point and the distance between the point and the player and checks

3-is the lenght of the path by going at this point shorter than the last shortest path ? if it's smaller, it's assigne to the best point.

If it detected a point that matches these conditions, it goes at it and if it doesn't see the player, it continues checking for new points. If no point matches the condition, he just stop following the player (the enemy lost him). All this works with raycasting to check positions, presence of objects between enemy, player and points and path to go.

# Answer
You can make the enemy search for the path to the last point where he saw the player for the last time, and search a bit further after that along the vector where player has disappeared, but you need to save also some points after the enemy lost the player. Or you can get the vector between last and previous points for this.

Also, if you want to check all points, you can do a binary search for the best point.

And make sure to add only points that exceeds certain distance from the last saved point.
> 1 votes

---
Tags: unity, 3d, ai, path-finding
---


# Question
Title: Transparent alpha mode in Shader Graph creates unwanted jagged outline
I am currently working on a transparent shader and noticed that all my works have a jagged dark outline. I guess I've used the wrong settings somewhere, but I've been fiddling around with a couple settings without any success. I have created a basic shader, which shows the shader settings I use and the problem.

It might be a little hard to see on the screenshot, so please have a look in full resolution. There's a small black outline around the circle on the yellow background.

# Answer
> 2 votes
Only your Alpha should use the ellipse output pin.

Your RGB should be one consistent colour, and not darken from the inside of the ellipse to the outside.

For a smoothly-antialiased edge, your AlphaClipThreshold should remain at the default of zero, and you should use Transparent blending rather than Opaque.

---
Tags: unity, unity-shader-graph
---


# Question
Title: Game development equivalent of Movie Director
Is there a job in game development that is equivalent to being a movie director?

# Answer
As Almo says, roles within game development vary quite widely from studio to studio, or sometimes even between projects for a single team. But there are common patterns.

I think the closest equivalent here would be termed a Creative Director:

> The creative director is responsible for the overall vision of the product: game play, visual style, story, audio assets, cinematics, and marketing materials. This person is often the creator of the game concept, and may serve as the primary designer. He or she works under the supervision of the producer and is tasked with managing the teams of artists, designers, and programmers, interacting directly with senior supervisors of each department.
> 0 votes

---
Tags: terminology, game-industry, career
---


# Question
Title: Some autocompletion doesn't work in Visual Studio Code with Unity
I am using Unity 2018 with Visual Studio Code version 1.43.2 on a Mac.

---

Things seemed to work fine between Unity and Visual Studio Code, but now I realize that something is wrong with Code. I have been following along with a tutorial and the autocompletion functionality of Code seemed fine until the function `OnTriggerEnter`, which was shown as autocompleting for the guy in the video (who was using the *other* Visual Studio), didn't fill in. However, many other Unity things do automatically show up as options.

I looked at this Microsoft help page about VS Code and Unity, and I have everything it I seems I would possibly need to combine the two; I have .NET, Mono, Debugger for Unity, the C# extension, and got Unity Tools for good measure.

Generic C# things like `return`, `void`, `int`, etc. autocomplete, so the C# extension seems fine. Many Unity things, like `Vector3`, `GameObject`, `Destroy`, `transform`, etc. also autocomplete like they should.

**What is wrong here? How can I fix this and get full autocomplete?**

# Answer
The thing is `Vector3`, `GameObject`, `Destroy` are all staticly typed classes or methods inside classes. Thus intellisense can autocomplete them.

On the other hand, `Awake`, `Start`, `Update` and other 'unity callbacks' are not. What Unity engine does it uses reflection, to check if the `MonoBehaviour` has any of those 'callbacks' in it (through name (as string) reference). If it does, the callback gets called. Because there's no staticly typed method as `Awake`, `Start`, etc., intellisense cannot autocomplete it.

As for solution, there are extensions, can't remember names exatcly, that add snippets for `Start`, `Update` and other callbacks.
> 2 votes

---
Tags: unity, c#, visual-studio-code
---


title: How to create 3D area mask?

text:
# Question
Title: How to create 3D area mask?
I have two cubes, one parent and one child. I want to use the parent's cube mesh as a mask for the child cube. I want to make visible only the part of the child cube that it is inside the parent cube.

I can easily achieve this effect with 2D sprites using the Sprite Mask, but I can't find a way to do it for 3D areas or 3D objects.

What I have:

What I want:

# Answer
> 0 votes
In 3d editing it is called a Boolean Operation and not a mask.

The operation you are talking about is an Intersection. https://docs.unity3d.com/Packages/com.unity.probuilder@4.0/manual/boolean.html

You can use this library:

https://github.com/karl-/pb\_CSG

It should work with the cubes fine.

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


title: Why does my character move diagonally?

text:
# Question
Title: Why does my character move diagonally?
So i've been trying to make the player face towards the direction i pressed. That part works just fine but when I try to move the player it moves diagonally instead of left/right. Any clues?

```
 if (Input.GetKey(KeyCode.RightArrow))
             {
                 //moves the player
                 rb2d.velocity = new Vector3(2.5f, 0, 0);
                 transform.Translate(rb2d.velocity * Time.deltaTime);

                 //flips the player right
                 if (human.flipY == true)
                 {
                     human.transform.rotation = Quaternion.Euler(0, 0, 270);
                 }
                 else
                 {
                     transform.rotation = Quaternion.Euler(0, 0, -270);
                 }

```

# Answer
When in doubt, remember to read the documentation for the methods you're using:

> If `relativeTo` is left out or set to Space.Self the movement is applied relative to the transform's local axes.

So you're getting a velocity vector in world space, and applying it as a local-space translation. This will rotate the vector by your local orientation.

It sounds like your local orientation is twisted +- 90 degrees from world space. So the rigid body `velocity` tries to move you to the world's right, and `transform.Translate` tries you to the *object's* right (which points up or down in the world), resulting in a net movement that's diagonal.

Really, you should not have `transform.Translate` here at all. If your object has a rigid body (2D or 3D), you should consider setting `transform.position`/`rotation`, `transform.Translate()`/`Rotate()` to be off-limits. Moving a physics object via its transform makes your code fight with the physics engine for control, leading to all kinds of unwanted outcomes as you've already observed. Use velocity, angular velocity, AddForce, MovePosition or MoveRotation instead to keep your movement in the physics engine's control.
> 1 votes

---
Tags: unity, 2d, movement
---


title: Switch player model

text:
# Question
Title: Switch player model
I am doing an infinite runner game and I want to be able to change the player vehicle during the game (I mean during the race by pushing a button).

I was thinking on destroying the previous player prefab and instantiating a new one for the new vehicle prefab, but this way the playercontroller script attached is deleted too.

So my question here is if this is the best way to do this and how could I keep the attached playercontroller.

# Answer
My usual route is to separate the logical and visual parts of the game object:

* Root of my prefab (contains control script(s), rigid body if applicable)

+ "Visual" child object (contains mesh renderer / sprites / etc)

Colliders can go either at the root, or in a child object separate from the visual child.

This way I can do anything I want to the underlying visual - squash & stretch it to juice up its movement animations, bounce it around, etc. - without impacting the physics simulation or gameplay logic.

It also means we can swap the visual without losing the player controller, by either destroying the old one and instantiating a new visual child object in its place, or by having all the visuals present at all times, but disabling the game object for all but one of them at a time, and just swapping which one is active.

The latter option is good if you cycle appearances between a small-ish set of options frequently, so you're not incurring extra instantiation/destruction overhead and memory allocation constantly. But if you have a very large roster of visuals and each playthrough will only see a few, it might not be more efficient to load them on demand.
> 2 votes

---
Tags: unity
---