title: C# [DEV] Developer Tag in Unity

text:
# Question
Title: C# [DEV] Developer Tag in Unity
I’m trying to make Multiplayer FPS game in unity and i want to have Developer tag \[DEV\]. I want people to see that I’m game \[DEV\] of the game. What is the code?

# Answer
> 1 votes
Since you haven't shown us how you manage player IDs and authentication, we can't show you exactly how to plug this into your current system. But let's assume your player authentication database/API lets you query it with a method a bit like this:

```
public PlayerData GetPlayerData(PlayerID id, AuthenticationToken token);

```

Where `PlayerData` is a database record about a particular player that you can hold in-game as a struct:

```
public struct PlayerData {
    public readonly PlayerID id;
    public readonly string displayName;
    public readonly bool isDeveloper;
    // ... othee player attributes you care about.
}

```

Now when your game client joins a game session, or new players join the session with your client, we can use your authentication service to confirm their identity and download their display information, keeping a local cache of `PlayerData` instances for the players in this session.

When creating the display string for a player's name to appear in the UI, you can check the `isDeveloper` flag to render it appropriately:

```
public string FormatDisplayName(PlayerData data, string teamColor) {

    if(data.isDeveloper == false)
        return string.Format("<color={0}>{1}</color>", teamColor, data.displayName);

    return string.Format("<color=#ffff00>[DEV]</color><color={0}>{1}</color>", teamColor, data.displayName);
}

```

This lets only those players tagged with `isDeveloper = true` in your player database appear with the \[DEV\] tag in its own colour. All other players will just show their display name in their team's colour.

Since the data is stored server-side, you have full control over which accounts you tag as developers, so you can confer or revoke the tag without updating any hard-coded info in the game executable. A player could hack their local client to display other users as \[DEV\], but this wouldn't affect the experience of players running unhacked versions, since the client does not have authority to tell other clients "I'm a dev!" — only your trusted server shares this info.

---
Tags: c#
---


# Question
Title: How do I blink a sprite a few times before it disappears?
I need the 3d poop emoji model in the chest on the right to blink, visible-invisible-visible, several times:

This is a 3d gameObject oriented to face the camera, shaded with an unlit material.

I need the object to "blink/flash" to indicate that the item has been obtained. The object needs to be generated the moment the lid opens (done), stay unchanged until the lid pops all the way up (0.2 seconds), and flash 3 times during the 0.6 seconds the lid is up. The object is destroyed the moment the lid starts to come down again.

My code (blinking/flashing is not working)

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

public class ItemBox : MonoBehaviour
{

    bool disabled = false;
    private Animator anim;
    public GameObject item = null;

    void Start()
    {
        anim = GetComponent<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBoxIdleState");
        }
    }

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

    }

    void OnTriggerEnter (Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            anim.Play("ItemBoxGetItemState");
            GameObject itemClone = Instantiate(item, transform.position + new Vector3(0, 0.5f, 0), Camera.main.transform.rotation * Quaternion.Euler(0,180,0));
            Blink(itemClone);
            Destroy(itemClone);
            disabled = true;
        }
    }

    IEnumerator Blink(GameObject obj)
    {
        Renderer objRenderer = obj.GetComponent<Renderer>();
        objRenderer.enabled = true;
        yield return new WaitForSeconds(0.2f);

        for (int i = 0; i < 3; i++)
        {
            objRenderer.enabled = false;
            yield return new WaitForSeconds(0.1f);
            objRenderer.enabled = true;
            yield return new WaitForSeconds(0.1f);
        }
    }
}

```

Instead of blinking/flashing, the object is just there, doing nothing.

# Answer
> 5 votes
It appears you want `Blink` to be executed as a coroutine. But you are executing it directly.

If you call an IEnumerator method directly, you receive an `IEnumerator` object which you could then use to run that method from one `yield return` statement to the next by repeatedly calling `MoveNext()` on it. That means you could, if you wouldn't discard that IEnumerator object.

But what you likely want to do instead is make Unity use that IEnumerator to process a coroutine, like this:

```
StartCoroutine(Blink(itemClone));

```

# Answer
> 3 votes
When you call `Blink` you are discarding its return value:

```
Blink(itemClone);

```

You do not want to do that. I believe you want to call `StartCoroutine` on it.

> the turd is destroyed the moment the lid starts to come down again

Well, you are calling `Destroy` right after:

```
Blink(itemClone);
Destroy(itemClone, 0.8f);

```

If it is meant to be a continuation of the coroutine (which makes sense) then the easiest solution is to make it part of the coroutine.

# Answer
> 0 votes
You write in your code, "Blink(itemClone), but how does this start the coroutine? In my knowledge, you need to have "StartCoroutine("Blink")" Also, the Destroy function needs to be inside the coroutine or it will be destroyed before the coroutine is finished. I realize that theraot has already said that, but I was just wondering why his answer hasn't been marked as an answer that worked?

---
Tags: unity, c#, graphic-effects, timer
---


# Question
Title: How to make my character walk by clicking and holding the mouse button?
I created an Action Mapping using the right mouse button as a reference.

The Action Map is called "Andar" (walk in english).

**In the character code, I call this Action Mapping and in it I make the character walk by clicking the right mouse button (on Floor):**

But I would like the character to continue walking if the player clicked the right mouse button and held.

Like Set Destination (action mapping from Unreal).

**Other places I searched:**

https://www.youtube.com/watch?v=AIPPXGFkjF0

https://answers.unrealengine.com/questions/134746/hold-button-for-few-sec-and-play-event.html

It's a simple problem, but I can't find anything about. Not exactly. The problems I found in my search are not the same as my problem. Even changing the words and terms I was not successful.

# Answer
> 0 votes
**With the help of the answer to this question:**

https://answers.unrealengine.com/questions/438398/a-simple-question-about-click-press-hold.html

I discovered to solve my problem.

* Add a boolean variable
* Set it to true every time the mouse button is pressed
* Set it to false every time the mouse button is released
* Insert a While Loop that only ends when the boolean variable is false.

**Code:**

---
Tags: unreal-4, mouse, blueprints
---


# Question
Title: How do I keep historical variable value tied to certain period of time?
I'm currently trying to figure out how I can keep ever-changing variable values and make it available for other classes to access the said variables.

In my example, I have the following:

```
public class Item
{
    public int Quantity;
    public int BuyPrice;
    public int SellPrice;
}

```

The value for all the variables in Item class will change every day.

Let's say I'm entering Day #2, how do I save class Item's variables value for Day #1 so that other classes would be able to refer to Day #1 value on Day #2?

Further to the my earlier question, there will be multiple Vendor classes having their own instances of Item and these Vendor classes will be visited by Agent classes.

I would like for the Agent to loop through all instances of Item sell price *owned* by the last Vendor it visited. Agent will hold a record of when it last visited the Vendor and will request for Item sell prices on that particular date by that particular Vendor.

Hope that make sense.

# Answer
You can store them in an array or `List<>`, up to the maximum number of days of history you want to keep.

There are several ways to structure such a representation, but given how you phrased your query, what I would suggest would be to first wrap the changing cost data into its own type (because, presumably, some aspects of the item such as perhaps the name won't change every day):

```
struct CostData {
  public int Quantity;
  public int BuyPrice;
  public int SellPrice;
}

```

Then modify `Item` to hold a *list* of `CostData`

```
class Item {
  List<CostData> Cost;
};

```

`Cost[Cost.Length - 1]` could be "today's" data, and `Cost[Cost.Length - 1 - n]` would be the data for \\$n\\$ days ago; when the day rolls over you just insert the new day's cost onto the back of the list. I'd suggest you actually write methods to access the data though, rather than relying on consumers of the API remembering that convention.
> 0 votes

---
Tags: c#, architecture, data-structure
---


title: Array Out Of Range Exception

text:
# Question
Title: Array Out Of Range Exception
I have been working on my this aspect of my project since last night and have finally got this code to work exactly as I want it to.

However if the first target is removed before the second one, I get an out of range exception. I would like to know if there is a better way to fix my problem.

```
void LateUpdate()
{
    if (targets.Count == 0)
        return;
    Move();
    Zoom();
}

void Move()
{
    GetBoundsData();
    Vector3 newPosition = new Vector3(centerPoint.x + offset.x, transform.position.y, centerPoint.z + offset.z);
    transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime);
}

[SerializeField] Bounds bounds;
[SerializeField] Vector3 centerPoint;
public Vector3 maxBoundsPoints;

void GetBoundsData()
{
    if (targets[0] == null)
    {
        targets.RemoveAt(0);
    }
    if (targets.Count == 1)
        centerPoint = targets[0].position;
    SetUpBounds();
    centerPoint = bounds.center;
    maxBoundsPoints = bounds.max;

}

void SetUpBounds()
{
    bounds = new Bounds(targets[0].position, Vector3.zero);
    for (int i = 0; i < targets.Count; i++)
    {
        if (targets[i] == null)
        {
            targets.RemoveAt(i);
        }
        bounds.Encapsulate(targets[i].position);
    }
}

```

# Answer
You have a problem in this loop:

```
for (int i = 0; i < targets.Count; i++)
{
    if (targets[i] == null)
    {
        targets.RemoveAt(i);
    }
    bounds.Encapsulate(targets[i].position);
}

```

Imagine that you have 5 items in your list, and the last one is `null`. At `i = 4` we check our loop condition `i < targets.Count`, and get `4 < 5`, which is `true`, so we enter the loop body. Then our `if` check detects that `targets[i]` is null, so we remove it *and then continue executing the loop body*.

Now our `targets.Count` is 4 (we removed the last entry), so when we call `bounds.Encapsulate(targets[4].position)` we're accessing past the end of the list.

This code also has errors if you have two consecutive `null`s in your list, where you check for the first `null` and remove it, then run headlong into a null reference exception trying to access `.position` on the next entry which is also `null`.

So in general, you want to avoid removing items from a collection that you're in the middle of iterating. Instead, prune the bad data out first, then iterate only the good data:

```
// Remove all nulls from the list in one pass.
targets.RemoveAll(item => item == null);

// Now you have a list without nulls you can iterate without extra checks.
foreach(var item in targets) {
    bounds.Encapsulate(item.position);
}

```
> 1 votes

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


# Question
Title: Box2d: Destroy body or setActive to false?
What is better practice when a body goes out of screen, to destroy the body or just setActive(false)?

I guess in terms of memory it is better to destroy it and free the memory, but is destroying bodies expensive?

# Answer
There is no one answer that is correct. In certain cases you'd use `Destroy`, in others you'd use `setActive`. Which one to use depends on the situation.

For objects that are meant to go out the screen and never come back, definitely use `Destroy`. No question about it.

For objects that are outside of the screen, but could come in the screen again, you could use `setActive(false)` to disable that object, and enable it later.

I'm not familiar with libgx, so I can't speak about performance, but most tools/engines I've used out there handle properly what happens when an object exits the screen, so it doesn't have to be rendered and waste resources.

Also for your worry about the `Destroy` function, for 99% of the situations, you won't notice any performance hit using it. In most (if not all) tools, its designed in such a way that it destroyed all the easy stuff of an object, and queues up the difficult part to be handled when resources are available.

My advice would be, use what makes sense, and don't worry about performance, until it becomes a problem. If an object is meant to be destroyed (as in, not used anymore) then use `Destroy` otherwise `setActive`.
> 0 votes

# Answer
It is better to set active to false if the object is likely to be activated again. This saves recreating the object which is a bit more expensive.

If memory is an issue you could try using something like pooling to help with destroying bodies and keeping the cost down.
> 0 votes

---
Tags: libgdx, box2d
---


# Question
Title: How to load one of Unity's built-in UI Sprites at runtime?
I have some code that creates objects with an `Image` component, in which I want to replace the `Source Image` with one of the default built-in sprites, through the code.

**Example:**

**Code:**

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

public class PotionManager : MonoBehaviour {

    Image sourceImage;
    private float timer=25;
    static int COUNT_OF_ORDERS = 0;
    public Transform parent;
    public List<PotionAsset> potionList = new List<PotionAsset>();
    private float posX,posY,posZ;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= 30)
        {
            CreateOrderHolder();
        }
    }

    void CreateOrderHolder()
    {
        posX = 160 * COUNT_OF_ORDERS + 80;
        posY = -70;
        posZ = 0;

        COUNT_OF_ORDERS++;

        GameObject temp = new GameObject("Potion Order " + COUNT_OF_ORDERS, typeof(RectTransform));
        temp.transform.SetParent(parent);
        temp.transform.localPosition = new Vector3(posX, posY, posZ);
        temp.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
        temp.GetComponent<RectTransform>().anchorMax = new Vector2(0, 1);
        temp.GetComponent<RectTransform>().anchorMin = new Vector2(0, 1);

        CreatePotionHolder(temp.transform);

        timer = 0;
    }

    void CreatePotionHolder(Transform parent)
    {
        posX = 0;
        posY = 13.5f;
        posZ = 0;

        GameObject temp = new GameObject("PotionHolder", typeof(RectTransform), typeof(Image));

        temp.transform.SetParent(parent);
        temp.transform.localPosition = new Vector3(posX, posY, posZ);
        temp.transform.localScale = new Vector3(1, 1, 1);
        temp.GetComponent<RectTransform>().sizeDelta = new Vector2(100,50);

        sourceImage = temp.GetComponent<Image>();
        sourceImage.sprite = Resources.Load<Sprite>("Resources/unity_builtin_extra/UISprite");
        Debug.Log(sourceImage.sprite);
    }

}

```

In the end, `sourceImage.sprite` returns `null`. I tried to add at the end of the file path the file extension like png, psd, but this did not help.

# Answer
> 3 votes
You can access the built in Extra Resources in the editor. I believe if you make a public reference to the UI sprite it will create a replica to use for runtime somewhere along the way.

Otherwise the path to the sprite is 'UI/Skin/UISprite.psd'

example

```
sourceImage = temp.GetComponent<Image>();
sourceImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");

```

I'd suggest using Sprite.Create(); during runtime and you can create a texture for it also so you have no need to load their default one.

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


# Question
Title: Why do I get this C2010 error while trying to use multicast delegates in Unreal?
Other errors I got when compiling:

* No instance of ADD\_INTERNAL\_DYNAMIC matches the argument list
* DECLARE\_DYNAMIC\_MULTICAST\_DELEGATE\_Threeparams Marco redefinition Note: See previous definition of DECLARE\_DYNAMIC\_MULTICAST\_DELEGATE\_Three params

XD.cpp:

```
// Fill out your copyright notice in the Description page of Project Settings.

#include "Test2.h"
#include "XD.h"

// Sets default values
AXD::AXD()
{
  // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
 PrimaryActorTick.bCanEverTick = true;

 newMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Static Mesh"));
 newBox = CreateDefaultSubobject<UBoxComponent>(TEXT("Collision Box"));
 newBox->OnComponentBeginOverlap.AddDynamic(this, onCollide);
}

// Called when the game starts or when spawned
void AXD::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void AXD::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

```

XD.h

```
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GameFramework/Actor.h"
#include "XD.generated.h"

#define DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(UPrimitiveUPrimitiveComponent* a, AActor* b, UPrimitiveComponent c);

UCLASS()
class TEST2_API AXD : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    AXD();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;
    UPROPERTY(EditAnywhere)
    UStaticMeshComponent* newMesh;

    UPROPERTY(EditAnywhere)
    UBoxComponent* newBox;

    UFUNCTION()
    void onCollide(class UPrimitiveComponent* a, class AActor* b, class UPrimitiveComponent* c)
    {
        Destroy();
    }

};

```

# Answer
In the `#define`:

This is wrong:

```
UPrimitiveUPrimitiveComponent* a

```

This should be a pointer:

```
UPrimitiveComponent c

```
> 1 votes

# Answer
The Input to bind a delegate should be a Class instance and a Pointer to method method. The method should also be marked as `UFUNCTION`.

So the code should look like this:

```
newBox->OnComponentBeginOverlap.AddDynamic(this, &AXD::onCollide);

```
> 0 votes

---
Tags: unreal-4, unreal
---


# Question
Title: trying to create a triangle with procedural code
Using Godot3, I have a camera and added a MeshInstance node to the Spatial node and attached this script. Why am I not seeing any triangle yet?

```
extends MeshInstance

func _ready():
    var size = 10
    var st = SurfaceTool.new()
    var mat = SpatialMaterial.new()
    mat.albedo_color = Color(1.0, 0.0, 0.0)
    st.set_material(mat)
    st.begin(Mesh.PRIMITIVE_TRIANGLES)
    st.add_uv(Vector2(0, 0))
    st.add_vertex(Vector3(-size, -size,  0))
    st.add_uv(Vector2(1, 1))
    st.add_vertex(Vector3( size,  size,  0))
    st.add_uv(Vector2(1, 0))
    st.add_vertex(Vector3( size, -size,  0))
    st.generate_normals()
    var mesh = st.commit()
    self.set_mesh(mesh)

```

# Answer
> 1 votes
Use Clock wise winding order.

Here's the modified code,

```
extends MeshInstance

func _ready():
    var size = 10
    var st = SurfaceTool.new()
    var mat = SpatialMaterial.new()
    mat.albedo_color = Color(1.0, 0.0, 0.0)
    st.set_material(mat)
    st.begin(Mesh.PRIMITIVE_TRIANGLES)
    st.add_uv(Vector2(0, 0))
    st.add_vertex(Vector3(-size, -size,  0))
    st.add_uv(Vector2(1, 1))
    st.add_vertex(Vector3( -size,  size,  0))
    st.add_uv(Vector2(1, 0))
    st.add_vertex(Vector3( size, -size,  0))
    st.generate_normals()
    var mesh = st.commit()
    self.set_mesh(mesh)

```

Also move your camera back to see the traingle

---
Tags: procedural-generation, godot
---


# Question
Title: Coroutine does not resume after WaitForSeconds
None of the code after wait for seconds runs in the example below.

The idea is to stop the player attacking for 1 second after he hits an enemy.

When I run this code, `Debug.Log` "start coroutine" appears in the console, but "endcoroutine" doesn't, and CanHit doesn't return to true.

How can I fix this so the coroutine resumes after the wait?

```
public class Attack : MonoBehaviour

{

private bool CanHit = true;

   private void OnTriggerEnter2D(Collider2D other)
    {
        IDamageable Hit = other.GetComponent<IDamageable>();

        if (Hit != null && CanHit == true)
        {
            Hit.Damage();
            StartCoroutine(ResetDamage());
        }
    }

    IEnumerator ResetDamage()
    {
        CanHit = false;
        Debug.Log("start coroutine");
        yield return new WaitForSeconds(1.0f);
        Debug.Log("end coroutine");
    }
}

```

# Answer
nothing to do with the code0. I had disabled the object the code was attached to in the last few frames of my animation, that's what was causing the issue.
> 0 votes

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


# Question
Title: How can I stop a character from jumping when he is grabbing something?
I made a feature for my game that allows the player to grab certain items when the distance between the RigidBody of the player and the object is smaller than 8, however the character is also able to jump when he is grabbing something, which is a thing that shouldn't be happening.

How can I fix this?

Here's the code:

```
// Code applied to floating platforms that are supposed to be grabbable, with the Y position
// frozen and X Y rotation as well
void Start() {
    rb = GetComponent<Rigidbody>();
}

void OnMouseDown() {
    distance = Vector3.Distance(character.transform.position, this.transform.position);

    // When the player grabs a object in range
    if (distance <= 8 && !Input.GetKey(KeyCode.Space))
    {
        rb.useGravity = false;
        this.transform.position = DistToPlayer.position;
        this.rb.constraints = RigidbodyConstraints.FreezeAll;
        this.transform.parent = GameObject.Find("Grab").transform;
    }
}

// When the player releases the mouse button
void OnMouseUp() {

    this.transform.parent = null;
    rb.useGravity = false;
    this.rb.constraints &= ~RigidbodyConstraints.FreezeRotationY &
                           ~RigidbodyConstraints.FreezePositionZ &
                           ~RigidbodyConstraints.FreezePositionX;

}

```

# Answer
> 1 votes
*I'm not an expert with Unity.*

Here is how I'd approach this:

On your character game object, add a public property `bool canJump = false;`. When you consider that the character is grabbing something, set that property to false.

Then in your update functions for your character gameobject, when a behaviour involves being able to jump or not, check the property and act accordingly.

```
if ( canJump && isFrounded && Input.GetKey(KeyCode.Space) )
    jump();

```

And then whenever the user releases the mouse, of course, allow the character to jump again.

---

Additionally, instead of creating a `bool canJump` as a property of your game object, you could create variables more representative of the state of the character, which would allow the controller to take better decisions.

```
bool stateIsGrabbingPlatform;
bool stateIsUnderWater;
bool stateIsGrounded;

```

This centralized approach can lead to having a lot of flags, but at least everything is where you need it.

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


# Question
Title: Can't initialize array in C++ using const int value?
I am making a text based game. I want to make a 2d array of 'Rooms' in my 'GameWorld' class.

I'm used to using C#, but am using C++ in order to learn it. The code I wrote I expected to work, but it gives error as shown in picture. If I write the figures 10 in each array container then it works.

```
#pragma once
#include <string>

class GameWorld
{
public:
GameWorld();

private:
const int MAP_WIDTH = 10;
const int MAP_HEIGHT = 10;
Room Rooms[MAP_WIDTH][MAP_HEIGHT];

};

struct Room {
Room();
std::string Name;
std::string Description;
std::string leftDescription;
std::string rightDescription;
std::string forwardDescription;
std::string backDescription;
//// TODO: Add up and down (potentially need a 3d array map, maybe too complex?
//std::string upDescription;
//std::string downDescription;
};

```

Is it possible to create arrays this way using const? Or what is the correct way to make the array without hard-coding the size?

Thanks

# Answer
`MAP_WIDTH` (and `MAP_HEIGHT`) need to be `static` in this case:

```
static const int MAP_WIDTH = 10;
static const int MAP_HEIGHT = 10;
Room Rooms[MAP_WIDTH][MAP_HEIGHT];

```

`const` is not declaring *a constant* (in the sense of a fixed value the compiler will simply insert in place of the value's name) in this context. It is indicating that the member variable `MAP_WIDTH` *is* constant and will never change once initialized (it's more akin to C#'s `readonly`, in other words).

Because `MAP_WIDTH` is a member variable, you can't refer to it without having an instance to do `instance.MAP_WIDTH` with. If you use the `static` modifier on variable declaration in a class or struct, that makes the variable a non-member variable, so you can refer to it as you do in the array declaration.

Note that you could consider using `constexpr` instead of `const` in this case.
> 1 votes

---
Tags: c++
---


# Question
Title: How do I get a Halo component and change its color?
I have a Halo component on an object, on the same object I have a script, in the script I tried to get the Halo component, but `GetComponent<Halo>()` doesn't work, it says that it can't be found.

My question is, how can I get the Halo component and change the color of it?

# Answer
> 2 votes
I found this on internet and it did work for me...

**warning: Tested only in unity editor...**

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

public class ChangeHalo : MonoBehaviour
{
    [SerializeField] private bool _isEnabled = true;
    [SerializeField] private Color _color = Color.red;
    [SerializeField] private float _size = 1;

    private void Update()
    {
        SerializedObject halo = new SerializedObject(GetComponent("Halo"));
        halo.FindProperty("m_Size").floatValue = _size;
        halo.FindProperty("m_Enabled").boolValue = _isEnabled;
        halo.FindProperty("m_Color").colorValue = _color;
        halo.ApplyModifiedProperties();
    }
}

```

**Thanks to this person: https://answers.unity.com/users/656364/hyper00.html** Cheers!

# Answer
> 0 votes
To get the Halo component you must do as follows.

```
Behaviour halo =(Behaviour)gameObject.GetComponent ("Halo");

```

---
Tags: unity
---


title: 2d Tiled Map with images in Javascript

text:
# Question
Title: 2d Tiled Map with images in Javascript
I'm trying to create a tile map with simple 2d images (30x30). I restarted the project from my previous post, and instead of using someone else's code, i though I would learn more to start from scratch. It was going well, but I ran into a bump when attempting to use images for tiles. My previous project used to following to create simple cubes. Now I'm trying to use images, and was wondering if there is a way to make the images wihtout having to follow the exact same steps as below:

```
function renderLevel(){
// clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// walls = red boxes
context.fillStyle = "#ff0000";
for(i=0;i<levelRows;i++){
    for(j=0;j<levelCols;j++){
        if(level[i][j]==1){
            blockrow.push(i);
            blockcol.push(j);
            context.fillRect(j*tileSize,i*tileSize,tileSize,tileSize);
            console.log("add");
            //collision[i] = new Array ([i],[j]);
        }
    }
}
// player = green box
context.fillStyle = "#00ff00";
context.fillRect(playerXPos,playerYPos,tileSize,tileSize);

```

}

Currently, I'm trying to simply drop the images, and manually declare the sizes when calling them.

```
    function setmapimages(){
    for (i=0;i<mapArray.length; i++){
        for (k=0; k<mapArray[i].length; k++){
            //image for player
            if (k==positionX && i==positionY){
                ctx.drawImage(img, 30, 30);
            }
            //image for road
            if (mapArray[i][k] == 0){
                ctx.drawImage(img2, 30, 30);
            }
            //image for collision
            if (mapArray[i][k] == 1){
                ctx.drawImage(img3, 30, 30);
            }
            //image for Store
            if (mapArray[i][k] == 2){
                ctx.drawImage(img4, 30, 30);
            }
        }
    }
};

```

I set the canvas size similarly to the previous project:

```
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
canvas.width =img.width*11;
canvas.height =img.height*9;

```

Although I set the variables a bit different. Since I'm using images now.

```
var img = new Image();
img.src= "image.png";
var img2 = new Image();
img.src= "image2.png";
var img3 = new Image();
img.src= "image3.png";
var img4 = new Image();
img.src= "image3.png";

```

Am I calling the images correctly? I looked up "drawimage" and think I went the wrong way with this, but I'm unsure what could call the images correctly.

# Answer
First off, I have a comment about how you are creating your images. It is probably going to be easier for you to make a function and call it instead of manually setting everything like you're doing. Ex:

```
function imageConstruct(url) {
  var image = new Image();
  image.src = url;
  return image;
} // USAGE: var img = imageConstruct("my_cat.png");

```

Now on to the meat of your question.

Are you getting any errors that you need me to solve, or are you just wondering if your current method of creating the tile level is valid? I always use a spritesheet now, which requires a bit of different math, but I used separate images like you while I was learning. Since spritesheets are a separate topic, I'll stick to what you're doing.

The way you've set up your `for` loops for the 2d array looks good to me, but notice how each iteration you're running 3 if statements no matter what. Even if its tile 0, you check if its a 1 or 2 after, which is not as efficient as you can make it. I suggest using a `switch` statement like I will model below, or `if...else if... else` because once the tile is found to be 0, 1, or 2, it won't keep checking :)

For the best performance, the tile that appears most often in your map should be the 1st case and the tile that appears the least should be the last case so each loop executes faster with less value checking.

Your current code doesn't look like it displays a grid, it looks like each tile is getting rendered at x: 30, y: 30. If you do `ctx.drawImage(image, x, y);` the image will be rendered at its default width and height because you aren't specifying it. Since your images are all 30x30, that's not a problem for you right now, but your code above won't create a grid because you need to calculate each tile's x and y position and render it there instead of rendering them all at 30 30. `ctx.drawImage(image, i*30, k*30);` will render each tile at the correct x and y position. You have that same calculation in your first code snippet, so I assume that you know how it works, but if you want me to explain it, I can.

ex:

```
switch(mapArray[i][k]) {
  case 0:
    ctx.drawImage(img, k*30, i*30);
    break;
  case 1:
    ctx.drawImage(img1, k*30, i*30);
    break;
  //etc.
}

```

You can change i and k in your loops to y and x if that's easier for you to read.

Please let me know if you have any other questions or if I didn't understand everything you were asking!
> 1 votes

---
Tags: 2d, javascript, tiles
---


# Question
Title: How to move an object in a heart shape pattern in javascript?
How can I move an object in a heart shaped pattern? I have a move(x, y) function that I can use to move the object, but how to I make a function that will move the object in a heart shaped pattern, with something like a setInterval?

# Answer
> 3 votes
You can find a mathematical equation that looks best to you on your own. A good starting point would be here: wolfram

As far as implementing it, here is some sample code I drew up that models a cardioid (relatively heart-shaped, though I'm sure you can find something better). The equation is : `r = a + a * sin(angle)` where the angle is in radians and a is the amplitude. It's equation is polar (you get the radius from the angle), so I do a little conversion to get x and y coords from it (sorry, this was maybe a bad example to pick :p ).

```
var c = document.getElementById("c");
var ctx = c.getContext("2d");

var arr = [];

var center = {x: 100, y: 50};

var start = 0;
var stop = Math.PI * 2; //radians

var resolution = 60; //how many points to connect
var step = stop/resolution; //angle increment per point

ctx.beginPath();
for(var i = 0; i < resolution+1; i++) {
  var angle = step * i;
  var r = 50 + 50 * Math.sin(angle);
  var point = {
    x: center.x + r * Math.cos(angle),
    y: center.y + r * Math.sin(angle)
  }
  if(i !== 0) ctx.lineTo(point.x, point.y); //connecting points
  else ctx.moveTo(point.x, point.y); //starting point
  arr.push(point); //create an array of points
}

ctx.stroke();
```

```
<canvas id="c" style="border:1px solid black"></canvas>
```

Anyway, now you can send points.x and points.y to your move function each frame by using that array `arr`. Let me know if you have any questions.

**Quick Update:**

Ok, I was thinking about this again and realized that my quick method for drawing out a cardioid is not the most optimal method for you to actually update your object's position... so I made another short example - this time I made a cardioid function so each frame you update the position by calling this function (instead of getting the next element in an array). I used requestAnimationFrame because it's more awesome than setInterval - but that's a separate topic. Anyway, the code is heavily commented, so take a read and let me know if I should explain anything more.

```
var c = document.getElementById("c");
    var ctx = c.getContext("2d");

    var center = {x: 100, y: 35};

    var start = 0;
    var stop = Math.PI * 2; //360 degrees in radians

    var player = { x: 0, y: 0, r: 5 };

    function cardioid(time) { // time range is 0 to 1
        var angle = (stop - start) * time; //get angle based on time
        var r = 50 + 50 * Math.sin(angle); // The cardioid equation with amplitude of 50
        var point = { //convert from the polar equation to x and y coords.
            x: center.x + r * Math.cos(angle),
            y: center.y + r * Math.sin(angle)
        }
        return point;
    }

    const TOTALTIME = 2; //seconds
    var timer = 0;

    var last = 0;
    function main(ms) { //this is an example loop
        requestAnimationFrame(main);

        const t = ms / 1000;
        dt = t - last; // time between last frame and this frame (delta time)
        last = t;

        timer += dt; // add to the timer

        ctx.clearRect(0,0,c.width,c.height); //clear canvas

        //update player position
        if(timer <= TOTALTIME) {
            var position = cardioid(timer/TOTALTIME); //force the range to be from 1 to 0 even though the totaltime is > 1
            player.x = position.x;
            player.y = position.y;
        } else {
            timer = 0; //reset
        }
        //draw

        ctx.beginPath();
        ctx.arc(player.x, player.y, player.r, 0, 2*Math.PI); //made player a circle
        ctx.fillStyle = '#ff0000';
        ctx.fill();
}
requestAnimationFrame(main);

```

```
<canvas id="c" style="border:1px solid black"></canvas>
```

---
Tags: mathematics, javascript
---


title: Evolving a Terrain Generator

text:
# Question
Title: Evolving a Terrain Generator
I just recently asked this question and the conclusion seems to be that using genetic programming (GP) for Procedural Game Content Creation hasn't really been done. I want to change that.

I'm fairly certain GP could be deployed to help find a new terrain generator. The question I'm getting to is how might this be achieved?

All GPs have a few basic parts that can be generalized for all GPs (parent selection, recombination, mutation, survival). I can figure those out on my own. The issue arises in the problem specific parts. These are how you represent the problem in code (this usually uses a tree), and how you evaluate how good a generator might be (this can be one or more values).

# **The questions in a nutshell:**<br>

* **How would you represent a terrain generator in a way that can be parsed into a tree?**
* **What kind of terrain would this have to generate? (heightmap, vertex graph,...)**

The less this is based on a hightmap the better.
* **What would be used to evaluate the fitness of a solution?**

ex: we want interesting terrain so we could have one of the values be the average change in the normals for each vertex on the terrain.

# Answer
You may have some luck with an approach similar to Karl Sims' genetic images.

He uses a simple set of operators in a LISP-like language such that any operator's output can be utilised to influence the image, similarly to in some shader languages (ie. a scalar would be a greyscale value, a `vector3` would be `RGB`, etc..).

Though I guess that's implementation stuff, so what you probably want is his keywords, which (iirc) contain all the basics:

* trig functions (`sin, cos, tan`, etc..)
* position (`x, y`)
* basic math operators ( `sqrt, pow, abs, inverse` )
* noise functions ( `fBm, noise2, noise3` )
* other fractals ( `mandelbrot, julia` )
* interpolation functions ( `lerp, quad, step, smoothstep` )

*(Some of the above may not be in his implementation; I found his work a long time ago and have actually made a few attempts at what you're describing over the years - so memories may be leaking :)*

# Keeping it interesting (and fast)

I had a bit of luck with a multi-layered approach which massively reduced the amount of dead evolutions.

1. a set of ranges are generated for each operator (or mutated from previous rounds)
    * these ideally keep the values within a "sane" range for each function, but can evolve into ranges which have surprisingly useful results, which seems like the "right" thing to do
2. generate a few algorithm trees
    * for each of these generate a few heightmaps at random positions and evaluate fitness
    * if we have a lot of good matches then evolve down this branch a bit, perturbing the ranges from **step 1** slightly in each child
    * otherwise, we've probably got bad ranges, go back to **step 1**

# However...

Now I've conveniently skipped over the *fitness* algorithm, I mostly used Karl Sims' approach of "unnatural selection" where you see the current generation in the middle square of a bunch of offspring (popularised by Kai's Power Tools back in the day - here's an image of what I mean)..

However you could probably have a set of training images, perhaps some from satellite imagery and a few artificial ones with particular qualities and then maybe use wavelet or 2D FFT analysis on them vs. the terrain you're testing?

This is an interesting topic, but I doubt what you needed an answer on :)

**EDIT: ahh. had to remove a bunch of links because I'm a new user :-|**
> 11 votes

# Answer
I am not sure you can answer this question but I feel an explanation as to why might be a helpful enough answer. So, Answers in a nutshell:

* You will want to pick a terrain generation where certain aspects of it can simply be based off of data values. This is not hard to do but does require you to pick a terrain generation. Since the area I am working in is in voxel generation, things like sampling rates, tunneling passes, elevation levels etc would be things that can be put into data and 'evolved' over.
* Kind of goes hand in hand with the first part. It doesn't matter really what form of generation you go with as long as you can set different properties of it. This choice should have more to do with the type of game you are looking to make.
* This is where it breaks down. I can not think of a way to measure this aside from a Person actually looking at the world and going "Oh that's nice". But this removes the computer doing its own self iteration. This also implies that you are going to use this form of generation to create a single world in the end, looking for the 'best' one as opposed to a random one every time.

Genetic Algorithms are usually used to solve a known problem where you can define the environment through rules. Then you can create data sets that represent different properties that affect how things react to the rules. The computer then plays a 'round' with the initial data set, selects the top X number, mixes their values after pairing them together and does another round.. A common example of this is 'breeding a better troll' (doing the breeding to find a set of values where the troll generally does very well in its environment (Is able to hunt and eat, either kill or stay away from villagers, can collect loot and amass all the shiny objects it desires, etc).

I am just not sure what you are trying to accomplish is applicable in the realm of terrain generation. The only thing I can come up with would be game content sorts of evaluations where you did not want to plan out a world but wanted to make one that AI pathing can be calculated in nicely or something like that. Even with this however you are looking for a single or at the least limited set of worlds.
> 2 votes

# Answer
> What kind of terrain would this have to generate? (heightmap, vertex graph,...)

Definitely a vertex graph (a mesh), it is compact storage-wise and can be rasterized (tesselated) on demand.

> How would you represent a terrain generator in a way that can be parsed into a tree?

Cellular automata. I can think of two implementations:

1. Rule-set automata, maybe with elements of finite-automata (when the current state, like attempts counter or idle time, is taken into account).

* Each node is initialized with a random state
    * Each node have an instance of solver attached
    * Each solver keep calculating next state until it runs out of rules or reaches its ideal state (I'm done here)
    * All next states are calculated first and then applied all at once before the next calculations start, so the calculation order won't matter

Rule-set itself may be represented as a branching decision tree or simple command batch (not sure if it will work)

It's just one rule set for every node

2. World-builders. Instead of applying a solver for every single node you can create just a bunch of them and allow them to navigate the mesh.

* Each builder have its own rule-set
    * Prevent them from entering the node occupied by another builder
    * Each builder may be represented as a branch of the tree
    * During the evolution builders may duplicate

Still, I'm afraid that the second approach needs to be backed by the first one: initial randomness needs to be smoothed and I'm not sure if builders can do the trick. Every living cell does have mitochondria after all.

> What would be used to evaluate the fitness of a solution?

The integrity of the resulting terrain - it' shouldn't look like a mish-mash. And the diversity - generally we want as much of available variations to be represented as possible (the flat wasteland from one edge to another is no fun). Maybe something more complex like how neighboring nodes fit each other (tundra in the middle of the desert, what?)

Gotta try it for my self with my mesh generator when/if have some spare time =)
> 0 votes

---
Tags: algorithm, procedural-generation
---


# Question
Title: How do you send game data from/to server?
Recently I've learned about running my clients and servers on separate threads than main, and I was able to send string data back and forth, open/close sockets, etc.

Now I'm curious: **How do I send gameobject data (transform, variables, actions, etc.) between server and client?** I understand how you turn data into bytes with `GetBytes()` and then into strings with `GetString()`, but how do you deal with any other data types, like Gameobjects, or Transforms?

I have tried changing everything to strings, then bytes, then back to strings, but I honestly don't even know where to start otherwise, as this seems excessive and wrong.

*Important information I almost forgot to mention:*

1. I am **not** using the unity built in networking tools, as this is for my own education.
2. I'm using a Udp server and client, all coded in C#, currently using `MonoBehaviour`(which I can remove if necessary)
3. Being it's all c# Udp, I'm using `UdpClient` and `Sockets`.

Thanks in advance for any help, if more information is needed to clarify anything feel free to ask!

# Answer
> 3 votes
**Don't try to send GameObjects over the wire.** Unity objects like GameObjects, Transforms, and other components are not set up for user serialization. There isn't a way to digest the whole thing into bytes to fit down the pipe then reconstitute it at the other end. Moreover, we wouldn't actually want to. It's both heavier-weight and less effective than what we really want to do, which is:

**Send information *about* GameObjects.**

For instance, if you want to tell the person at the other end of the line "GameObject #5 has moved to a new position" then you'd send something that looks like:

1. **Identifier for a "move object" message**

(so the receiver knows what kind of conversation we're having and can parse the following fields into your intended meaning).

Since you're making up your own networking code, how you identify each kind of message you can send is up to you — you might use enum values, or JSON objects with a string label "MessageType" etc.
2. **Identifier for the GameObject you want to move**

(so the receiver knows how to find the corresponding object in its replica of the game scene)

Again, since this is your own system, you get to decide how you'll identify objects. Maybe you assign each object a unique name string or numeric ID when it's created — just make sure any method you use is consistent over the network, so all participants *agree* on the names of the objects involved.
3. **The position it's moved to**

This is a `Vector3`, so you send three floats, encoded as bytes or round-trippable strings depending on your format.

What this might look like in code, assuming a binary message format that you can read like a `BinaryReader`, might be...

```
var messageType = (MessageType)message.ReadByte();

switch (messageType) {
    case MessageType.Move:
        var id = message.ReadInt32();
        var myObject = GetLocalObjectById(id);

        Vector3 position;
        position.x = message.ReadSingle();
        position.y = message.ReadSingle();
        position.z = message.ReadSingle();

        myObject.transform.position = position;
    break;
    // ...other message cases
}

```

Notice that to send, receive, and interpret this message, we only need to use primitive types: strings, floats, integers, or enum values that boil down to integers. At no point did we convert a whole `GameObject` to a serialized form and send it over the wire. We just used a primitive message "Move GameObject #5 to these coordinates" to tell us what modification needed to be made to our existing object's transform.

This is true even for spawning new objects. We don't send the new object over the wire, we send *the recipe the recipient needs to follow* to achieve the same result. A spawn message might include:

* **An identifier for the "spawn" message**
* **An identifier for the prefab we should clone**

This references a table of runtime-spawnable objects that both copies of the game hold. So if I want to spawn a new coin object, I look in my table and find the coin prefab at entry 5, and tell you "spawn a prefab #5" again without sending the entire object's component data, model, textures, animation, etc over the wire.
* **The unique identifier this instance should have**

So in future we can agree on how to refer to this shared object in both our scenes.
* **The position we should spawn it at**

`Vector3`: three floats.
* **The orientation to spawn it with**

`Quaternion`: four floats.
* **Any data needed to initialize the object in the same state**

eg. If you're using procedural generation to add uniqueness to stuff in your game, you may send along the seed used to generate the object, so the receiver can generate it exactly the same way.

So again the rule is: only send primitive data over the wire. You can format it into your own message types that you can serialize into strings/bytes as you like, but you're only ever sending *instructions* for what to add to the scene or how to modify stuff in the scene. You're never trying to wrench a fully-fledged Unity object out of all its interconnections in the engine and scene, blend it down to bytes, and somehow re-assemble and transplant it into a foreign body at the other side.

Not only is this a lot less hassle than trying to rebuild/rewire all the object's many interconnections when deserializing, it's also a lot less data to push, which is faster and costs less bandwith.

You're exploiting the fact that you're not communicating with an alien species who doesn't speak your language: you're talking to a copy of your own program, that already knows most of what you know (What does the "coin" prefab look like? What fields does a "transform" component care about?), so all you need to tell it are the *new* details specific to your local game state in the moment ("I need a \[coin\] at \[this position\]" or "Rotate \[this\] transform to \[this orientation\]")

---
Tags: unity, networking
---


# Question
Title: How do you blend multiple colors in HSV (polar) color-space?
In RGB color space, you can do a weighted multiple-color blend by just doing:

Start with R = G = B = 0. Then we perform a blend at index *i* using a set of colors *C*, and a set of normalized weights *w* like so:

```
R += w[i] * C[i].r
G += w[i] * C[i].g
B += w[i] * C[i].b

```

But I'd like to interpolate the colors in the HSV color-space instead, so that saturation and brightness are uniform across the interpolation. I know I can blend saturation and brightness in the same way as above, but the HUE component is an angle around a continuous circle, since HSV is essentially a polar coordinate system.

Blending only two HSV colors makes sense to me, you just find the shortest arc around the circle and interpolate between the two hues. But when you attempt to blend more than 2 colors, it becomes a bit of a puzzle.

You have to handle anomalous cases, like 4 equally-weighted colors with a hue at 0, 90, 180, and 270 degrees. They basically cancel each other out, so any hue will do.

Any ideas would be greatly appreciated.

# Answer
> 0 votes
Ah ha! This is a tricky one, but I found an algorithm that works, but it's not very optimal (yet). The algorithm is a generalized form of quaternion SLerp. It requires quaternion math and some iteration to approach the correct answer. Here is my implementation:

First you create N quaternions, all using the same vector (like 0,1,0) with the angle as the hue. Then you pass them and the weights into this function (C++):

```
void Quaternion::SetBlend( uint count, const Quaternion quats[], const float weights[] )
{
    assert( count >= 2 );
    // Iterate to find the weighted mean
    operator = ( quats[0] ); // initial estimate
    for( int i = 0; i < ITERATIONS; i++ )
    {
        Quaternion qmi = Invert();
        Quaternion qe(0,0,0,0);
        for( uint n = 0; n < count; n++ )
            qe += weights[n] * (qmi * quats[n]).Log();
        *this *= qe.Exp();
    }
}

```

When you get the angle from the resulting quaternion, it is the weighted mean. This can produce a good approximation with `ITERATIONS` set to even 1 or 2. Now, obviously there's a lot of zeros and extra math in here that can be optimized away, but at least I have a solution that works and I can optimize it from here.

# Answer
> 2 votes
I'll quote my answer to this question, since it's basically the same thing - he's averaging compass angles while you're averaging hue angles, but the procedure's the same either way.

> You could convert each angle to a 2D vector and sum the vectors, then convert the result back to an angle.
>
> In pseudocode:
>
> ```
> totalVector = [0, 0]
> for each angle:
>     vector = [cos(angle), sin(angle)]
>     totalVector += vector
> if length(totalVector) < aSmallNumber:
>     # error, angles are all over the place so there's no meaningful average
> avgAngle = atan2(totalVector.y, totalVector.x)
>
> ```

That being said, I'm not sure the specification of blending hue while preserving saturation is all that reasonable. As you say, it's possible to pick hues that are distributed around the circle so that a proper blend between them *should* be a very desaturated color. Using the above approach, the output hue will be extremely sensitive to the inputs in such a case - if you shift one of the inputs just a little the output hue will change quite a lot.

# Answer
> 0 votes
This is from the hip but i wonder if you could get some mileage from barycentric coordinates - where you treat each color as a point on a polygon and convert from the barycentric coordinates back into "world space" to get the blended color.

You might get a more "flat" blend since you are blending across a flat polygon instead of a sphere, but for colors that are somewhat close on the (hyper?)sphere, i would think it would approximate the right answer (and maybe you could normalize the blended answer and scale it back to the radius of the sphere).

Totally shooting from the hip, sorry if this is obvious or non useful :P

# Answer
> 0 votes
You can do the usual (w0\*Color1.hue + w1\*Color2.hue), just ensure it approaches from the proper angle (a few comparisons and swappings will do). But yeah, hue angle blending is inherently less efficient than RGB.

Considering a and b being blended hues, and the weight being the amount of movement from a to b (all between 0 and 1):

```
float hue_blend(float a, float b, float weight) {
  if (b < a) {
    swap(a, b);
    weight = 1.0 - weight;
  }
  if (b-a > 0.5) a += 1.0;
  float r = a + (b-a)*weight;
  if (r > 1.0) r -= 1.0;
  return r;
}

```

---
Tags: mathematics, graphics, algorithm, color, interpolation
---


# Question
Title: Aligning animation frame assets with different sizes
I have code that changes texture in each frame depending on the player's state - walking, idle.

My problem is that the idle texture (from separate png) has a slightly different size, and due to that it appears not in line with rest of the animations, seemingly being in a slightly different position when returning to idle.

How can I position the frames based on the center of texture instead of the bottom left?

```
batch.draw(determineTexture(), position.x, position.y,
            currentFrame.getRegionWidth()/2f, currentFrame.getRegionHeight()/2f,
            currentFrame.getRegionWidth(), currentFrame.getRegionHeight(),1f,1f, rotation,false);

TextureRegion determineTexture(){
        if(playerState == State.idle)
            currentFrame = idleAnimation.getKeyFrame(stateTime, true);
        else if (playerState == State.walkingUP || playerState == State.walkingDOWN || playerState == State.walkingRIGHT || playerState == State.walkingLEFT )
            currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        return currentFrame;
}

```

One png has a height of 57 - idle, while 6 columns and one row of walking frames have a height of 87 pixels.

# Answer
SOLVED ! I have modified the code as follows: instead of just position.x and position.y as arguments in SpriteBatch.draw() i modified those values as follows after some trial and error

```
position.x - currentFrame.getRegionWidth()/2f
position.y - currentFrame.getRegionHeight()/2f

```

So batch draw call looks now like this:

```
 batch.draw(determineTexture(), position.x - currentFrame.getRegionWidth()/2f, position.y - currentFrame.getRegionHeight()/2f,
            currentFrame.getRegionWidth()/2f, currentFrame.getRegionHeight()/2f,
            currentFrame.getRegionWidth(), currentFrame.getRegionHeight(),1f,1f, rotation,false);

```

That makes it centered every time i think Maybe i should mark it as beginner question next time but it felt satysfying to solve after some hints from @DMGregory thanks
> 0 votes

---
Tags: libgdx, animation, sprites, assets, spritebatch
---


# Question
Title: Can't correct perspective of Main Camera in Unity 3D without losing field of view
I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen.

https://i.stack.imgur.com/exzDp.jpg (A normal screenshot of my spaceship at default position)

This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps.

https://i.stack.imgur.com/pBH8d.jpg (The tilted spaceship when it's at an end of the game window)

But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted.

Things I have considered doing:

1. Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other).
2. Tweaking the field of view by trading off a little of each feature.

# Answer
One solution to your problem would be to render your ship with one camera and everything else with another. Both cameras have the same position and rotation. The one rendering everything but your ship has a high FOV. This way your ship will look normal but your environment will be warped.
> 1 votes

---
Tags: unity, camera, shooter
---


title: instancing and GPU skinning

text:
# Question
Title: instancing and GPU skinning
I'm trying to render a large number of identical rigged entities with independent animation.

Compared to standard skeletal animation, I can't compute the pose of each entities and send it to the GPU for each frame. This would demand too much work for the CPU and saturate the VRAM very quickly. Let's say I have 5000 entities with 20 bones, I would have to compute and send 5000 * 20 * (size of matrix/quaternion-translation/dual-quaternion) poses to the GPU, each frame.

I recently found this article/paper : https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch02.html Their idea is to load animations to the GPU in order to access them independently with each instance. Correct me if I'm wrong but I think this is equivalent to move the interpolation part to the GPU.

I pre-computed all the bone transformation in local space for each frame for each animation and packed it into texture buffers. It works as expected.

However, I experience strange results with my animated models... In fact the interpolation is necessarily wrong ! I am trying to interpolate between poses in local space, not in bone space like with standard CPU interpolation. There is no problem with translations, but with rotations. (the axis is shifted to the local space origin).

I imagine I could send the bone space transformations AND the bone hierarchy. But that would impose to parse the hierarchy for each vertex (in vertex shader), in order to re-compute the interpolated bone transformations.

One other idea I had is to upsample the animations in order to have smaller interpolation intervals, but again, it will use more VRAM.

To be honest I'm not sure I understood well the paper (especially in the interpolation part)...

Any suggestion ?

---

EDIT 1 : It's maybe unclear : by "local space" I mean entity space, so it is more like "global space"...

---

EDIT 2 : To provide more details about my implementation :

In the CPU (c++) pre-process part, I pre-compute all the bone transformations in local space for each frame (natively, I get bone-space transformations using Assimp library so I have to do a bit of work here).

Then, I send this information as an array to the GPU (array of numFrames * numBones * numAnims dual quaternions). In the vertex shader, I get information about the current instance using gl\_instanceID. I get world position, current animation and time in current animation.

Then I compute the interpolated pose of the bones influencing the current vertex. I do that by finding the bounding frames using the instance's time. I interpolate my pairs of transformations (pairs of dual quaternions) for each concerned bone.

**(I know there is a mistake because the interpolation must be performed in bone space).**

Once they are interpolated, I blend linearly the transformations into one using the bone weights attached to my vertex (and I normalize my final dual quaternion).

It worked when i was doing interpolation in bone space in CPU, I'm just trying to move the interpolation part on the GPU.

# Answer
The solution I chose was to pre-compute all the *frames* rather than the *keyframes*. In fact, I plan to have less than 10 seconds for all the animations.

To store a 10 seconds animation at 50 Hz, I need 10 seconds * 50 Hz * ~50 bones * 2 quaternion * 4 floats * 4 bytes = 800 kb of VRAM, which is acceptable in my case.
> 2 votes

---
Tags: opengl, skeletal-animation, instancing, skinning
---


# Question
Title: Camera Sensitivity in PointerLockControls to match actual games
I am creating a FPS game online. I want the user to be able to use a sensitivity they are familiar with from games they've played. In this case, I want them to use their Fortnite sensitivity.

I am trying to figure out the Math behind it all.

I have figured out how to change the sensitivity in the PointerLockerControls.js file and can edit it from my main js file.

```
function onMouseMove( event ) {

    if ( scope.isLocked === false ) return;

    var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
    var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

    euler.setFromQuaternion( camera.quaternion );

    this.speedFactorX = 0.002;
    this.speedFactorY = 0.002;

    euler.y -= movementX * scope.speedFactorX;
    euler.x -= movementY * scope.speedFactorY;

    euler.x = Math.max( - PI_2, Math.min( PI_2, euler.x ) );

    camera.quaternion.setFromEuler( euler );

}

```

I want to know what type of unit the '0.002' is.

In fortnite, I have my sensitivity at '0.08'. Obviously, this is way too fast to replace the speed factor values.

What kind of math do I need to match the users sensitivity in fortnite, to the speed factor values?

Hope someone can understand what I mean. Thanks!

This may help with the fortnite values - https://jscalc.io/calc/RTCJTLMts42GYfWf

I will be using the fortnite slider.

# Answer
> 1 votes
The type of unit for 0.002, as the name suggests, is a factor. An arbitrary number chosen to lower the rate of turning so that tiny mouse movements don't spin the camera 100 times.

To get fortnite-like aim, you need to disable mouse acceleration(enabled by default in windows) and measure the distance your mouse travels for a complete rotation in fortnite. Then, you need to match this distance in your engine. If your mouse moves 5'' in fortnite for a complete rotation, and in your engine it does 1.5 rotations for 5'', you need to divide your factor by 1.5. If your engine does 0.1 rotations in 5'', divide by 0.1.

For vertical sensitivity, use aiming upward to downward instead of rotations.

There's the possibility that fortnite uses a non-linear function for its sensitivity value, so that 0.09 may be double or triple what 0.08 was. This seems unlikely though, you shouldn't need to worry about it.

Some games(not fortnite) also smooth the camera. You can do this by keeping your existing camera code, but adding a new camera whose position is updated every frame:

```
smoothCamera.quaternion.slerp(camera.quaternion, Math.min(1, clock.getDelta()*50));

```

---
Tags: javascript, three.js
---


# Question
Title: How do I add a prefab to another prefab?
I want to instantiate a prefab, and then instantiate another prefab and then set the second prefab to the first prefab.

However, this doesn't work.

This is my code:

```
    //instantiate a new weapon prefab
    Transform nNewInstantiatedPrefab = Instantiate(tPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    if (nNewInstantiatedPrefab == null)
    {
        Debug.Break();
    }

    //instantiate a new amount info canvas
    GameObject nNewAmount = Instantiate(ItemInfoCanvasPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    if (nNewAmount == null)
    {
        Debug.Break();
    }
    nNewAmount.transform.SetParent(nNewInstantiatedPrefab);

    //now test if the prefab has been attached to the other prefab:
    Transform nTest = Helpers.GoFromName(nNewInstantiatedPrefab, "AmountCanvas");
    if (nTest == null)
    {
        Debug.Break();//this line is called
    }

```

And this is the helper function. I haven't had any problems with it so far:

```
public static Transform GoFromName(Transform t, string uName)
{
    foreach (Transform g in t)
    {
        if (g.name == uName)
        {
            return g;
        }
    }
    Debug.Break();
    return null;
}

```

Am I doing something fundamentally wrong, and perhaps prefabs can't be added to other prefabs?

Thank you!

# Answer
> 1 votes
You should have no problems instantiating prefabs and parenting them to other instantiated prefabs. At runtime, instantiated prefabs do not keep a reference back to the original prefab; they end up like any other normal `GameObject`.

The problem is that your code does not account for the `(Clone)` suffix that Unity automatically adds onto instantiated prefabs. To easily fix this, you can instead search for `AmountCanvas(Clone)` in your code.

However, I would suggest that you don't search by name at all. If you spawn multiple of the same prefab, or if there's already an instance with the name `AmountCanvas(Clone)`, you'll end up with something named `AmountCanvas(Clone) (2)` and your code will break again. You already have a reference there - `nNewAmount` \- so I'd suggest passing that to whatever needs a reference to the new instance.

# Answer
> 1 votes
pass the parent into the instantiate call and see if it works correctly

```
GameObject nNewAmount = Instantiate(ItemInfoCanvasPrefab,nNewInstantiatedPrefab);

```

or if you must pass in the two other parameters with the parent you can add it at the end

```
 GameObject nNewAmount = Instantiate(ItemInfoCanvasPrefab, new Vector3(0, 0, 0), Quaternion.identity, nNewInstantiatedPrefab);

```

if you rename the Instantiated object each time and parent to the last you would have something like this.

now if you wanted to re-create or update a new prefab from a old one you can use the editors prefab utility class but will need to first Unload it then update and resave.

```
UnityEditor.PrefabUtility.UnpackPrefabInstance();
UnityEditor.PrefabUtility.SavePrefabAsset();

```

---
Tags: unity
---


# Question
Title: Showing a mesh on a Screen Space Overlay
I have created a Screen Space Overlay. This Screen Space Overlay panel hosts 3 Texts. This works fine.

Then I tried to show a mesh on this Screen Space Overlay.

First, I simply added it as a child of the panel. Since this didn't show it, I added a Canvas Renderer to the mesh. This also didn't help.

What might be the culprit here?

Thank you!

ps: What I'm trying to achieve is a mesh rotating in front of the user's eyes like this:

This a sequence of what happens in the original scene that I try to rebuild:

One can see that as soon as the item is being inspected, a (very likely a screen space) overlay is shown, and the original scene gets dark. Also the selected item is shown and is rotated continously.

I imagined that it is a screen-filling screen space overlay which has an image. The upper menu of the image is filled with a color with 50% alpha in order to blend the background out.

I imagined that the weapon was then rendered in front of the screen space overlay image. If it was behind the the screen space overlay, it would be dim / greyed out like the rest of the scene.

That's how I came to think that the weapon was part of the Screen Space Overlay.

I know now that this isn't so because a Mesh Renderer can't be rendered in the UI "pass", but I would anyway like to know how this could be done.

Edit: Here is a screenshot of an HDRP camera:

# Answer
> 2 votes
The Unity documentation defines a Canvas like so:

> The Canvas component represents the abstract space in which the **UI** is laid out and rendered. All **UI elements** must be children of a GameObject that has a Canvas component attached.

"UI elements" are the types in the `UnityEngine.UI` namespace, including:

* UI Image & Text display components
* UI widgets like buttons, sliders, input fields
* UI layout group components

Notably absent: `MeshRenderers`. These are part of your 3D scene, not UI elements. You render them through a camera, like you do with the rest of your 3D scene.

In the old rendering pipeline, we can just add a second camera to render the rotating object on top of the scene after the rest has been drawn. For HDRP, we'll need to draw it to a texture first, then show that texture, like so:

1. Create a new layer under Edit -\> Project Settings -\> Tags & Layers, call it "Overlay"
2. Place your rotating item mesh object on this layer, at the world origin for simplicity. Remove any physics components so it doesn't interact with the rest of your scene, or forbid interactions between this layer and the others in your physics settings.
3. Create a new camera, whose culling mask sees only this Overlay layer.

Adjust its framing (position, rotation, field of view...) so it shows your spinning object the way you want.
4. Create a RenderTexture with the pixel dimensions you need for your spinning object on-screen. You can create this via script at runtime if you need its size to adapt to the current screen/window size.
5. Add this RenderTexture as your Overlay camera's target texture.
6. Add a RawImage to your UI, referencing the RenderTexture as its source. Now you have a UI object that shows the view of your spinning object, and you can position it within the UI layout as you like.
7. When you don't want to see this object overlay, hide the RawImage component and disable the second camera and spinning object, so you're not paying to update them.

---
Tags: unity
---


# Question
Title: Unity Custom InputManger for Cross-Platform Input
I have been working on my game for quite a while. one of its key features is cross-platform local multiplayer for example 2 players on 1 keyboard and some people on the controller.

here is the 4th Iteration

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

public class GameManager : MonoBehaviour
{
    public GameObject playerPrefab;
    public GameObject[] Players;
    public List<string> playerOrderString = new List<string>() { };
    public bool resetPlayerSelect;
    public Image UIImage;
    public float fadeTime = 1.0f;
    public GameObject MainCamera;
    public bool isGameRunning = false;
    #region  Spawnner
    public GameObject spawnnerGameObject;
    public GameObject[] objectsToSpawn;
    public GameObject[] ObjectsToSpawnOnFloor;
    public float[] SpawnRateOfObjectsPerFloor;
    #endregion

    void Start()
    {
        MainCamera = GameObject.FindWithTag("MainCamera");
        isGameRunning = false;
        Time.timeScale = 0.0f;
    }
    void Update()
    {
        if (isGameRunning == false)
        {
            InputCheck();
            AssignPlayerInput();
            if (playerOrderString.Count != 0)
                if (Input.GetButtonDown("Select" + playerOrderString[0]))
                {
                    SceneManager.LoadScene(0, LoadSceneMode.Single);
                }
        }
        else if (isGameRunning == true)
        {
            if (Input.GetButtonDown("Start" + playerOrderString[0]))
            {
                PauseOrResumeGame();
            }
        }
    }
    public bool RestartGame = false;
    void PauseOrResumeGame()
    {
        if (isGameRunning == true)//this pauses the game
        {
            Time.timeScale = 0.0f;
            isGameRunning = false;
        }
        else if (isGameRunning == false)
        {
            Time.timeScale = 1.0f;//this resumes the game
            isGameRunning = true;
        }
        else
            Debug.Log(Time.timeScale);
    }

    void InputCheck()
    {
        if (playerOrderString.Count == 0)
            return;
        if (resetPlayerSelect || Input.GetButtonDown("resetInput"))
            ResetInput();
        else if (Input.GetButtonDown("Start" + playerOrderString[0]) && GameObject.FindWithTag("MazeGenerator") == null)
            StartGame();
        else if (Input.GetButtonDown("Start" + playerOrderString[0]))
            PauseOrResumeGame();
    }
    public GameObject floorSet;
    void StartGame()
    {

        isGameRunning = true;
        Time.timeScale = 1.0f;
        Instantiate(floorSet, new Vector3(0, -0.45f, 0), Quaternion.identity);
        playerOrderString.RemoveAll(item => item == null);
        PlayersHasBeenSelected();
        StartCoroutine(FadeOutStartScreen(fadeTime, 0.0f));
        Players = new GameObject[playerOrderString.Count];
        InstantiatePlayers();

    }
    void InstantiatePlayers()
    {
        transform.position -= new Vector3((Players.Length - 1) * 2, 0, 0);
        for (int i = 0; i < Players.Length; i++)
        {
            Players[i] = Instantiate(playerPrefab, transform.position, Quaternion.identity) as GameObject;
            Instantiate(spawnnerGameObject, transform.position, Quaternion.identity);
            transform.position += new Vector3(4, 0, 0);
            Players[i].GetComponent<PlayerMovement>().playerInput = playerOrderString[i];
            Players[i].GetComponent<PlayerMovement>().playerText = PlayersText[i];
            Players[i].GetComponent<PlayerMovement>().PlayerNumber = i + 1;
            StartCoroutine(WaitUntilScreenFades(fadeTime, i));

        }
        for (int i = 0; i < objectsToSpawn.Length; i++)
        {
            Instantiate(objectsToSpawn[i]);
        }

        MainCamera.GetComponent<CameraController>().enabled = true;
    }
    IEnumerator WaitUntilScreenFades(float fadeTime, int i)
    {
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / fadeTime)
        {
            yield return null;
        }
        Players[i].GetComponent<PlayerMovement>().enabled = true;
    }

    IEnumerator FadeOutStartScreen(float fadeTime, float fadeToValue)
    {
        float alpha = UIImage.color.a;
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / fadeTime)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, fadeToValue, t));
            UIImage.color = newColor;
            yield return null;
        }
    }
    void ResetInput()
    {

        playerOrderString = new List<string>() { };
        resetPlayerSelect = false;
        {
            for (int i = 0; i < 4; i++)
                PlayersText[i].text = "Player Not Selected";
        }
        StartCoroutine(FadeOutStartScreen(fadeTime, 1.0f));
    }
    void AssignPlayerInput()
    {
        for (int unAssignedPlayer = playerOrderString.Count; unAssignedPlayer <= playerOrderString.Count; unAssignedPlayer++)
        {
            if (playerOrderString.Count >= 0)
            {

                CheckInputFor("K", 2);
                CheckInputFor("C", 4);

            }
        }
    }
    void CheckInputFor(string repFor, int times)
    {

        for (int input = 0; input < times; input++)
        {
            string playerOrderValue = repFor + (input + 1);
            string playerThisTime = "Fire1" + playerOrderValue;

            if ((Input.GetButtonDown(playerThisTime)))
            {
                if (CheckForDuplicateInput(playerOrderValue))
                {
                    playerOrderString.Add(playerOrderValue);
                    PlayersHasBeenSelected();
                }
                else
                    return;

            }
        }
    }
    bool CheckForDuplicateInput(string playerOrderValue)
    {
        for (int i = 0; i < playerOrderString.Count; i++)
        {

            if (playerOrderString[i] == playerOrderValue)

            {
                return false;//isDupplicate
            }
        }
        return true;//not dubliclate
    }

    public Text[] PlayersText;
    void PlayersHasBeenSelected()
    {
        for (int i = 0; i < playerOrderString.Count; i++)
        {
            PlayersText[i].text = "Player " + (i + 1) + " is " + playerOrderString[i];
        }

    }
}

```

As of now in my 4ths Iteration, the code works fine but I would like to optimize it further since it still seems a bit inefficient to me

I will explain a bit more about how my code works

In unity input manager I have set up controls for 6 types of controllers which follow the pattern of thisInputK1, thisInputK2, thisInputC1... and so on where K denotes keyboard input and C denotes Controller Input.

The numbers after that denote the different sets of keys the input requests, for example, VecticalK1 is the same as VecticalK2 but K1 uses WASD while K2 uses arrow keys same is for the controller but they use separate controllers.

after a player 1 is assigned if player one presses their start button the input manager feeds controls to game manager and the game begins

# Answer
Firstly, this bit of advice is not correct:

> the reason why you might be missing the Input during some frames, might have to do with the fact that the IEnumerator is taking longer to yield

I see this a lot, where folks think that if an update method or coroutine is slow, it will somehow "fall behind" the rest of the game loop, as stuff happens in the game faster than the slow code checks for it.

Unity doesn't work that way. Update and coroutine scripts run sequentially on the main thread as part of the game loop. If one of these scripts runs slow, the game loop can't continue on, read new inputs, and render new frames. It stalls until the script finishes. So the symptom of a slow script is low framerate - but all the inputs that happen in the duration of that long frame will still be picked up on the next frame.

Rather, I think your missed inputs came from your first version of your code, where you changed the value of `repfor` on alternating frames. Effectively this meant you looked only at the keyboard on odd frames, and only at the controller on even frames. So if the player presses a keyboard key on an even frame, or a controller button on an odd frame, you ignore it. This doesn't appear to be an issue in your updated code.

---

Now, as for what to do with the updated code: I would throw this out wholesale and start again. The flow of this class is a confusing, it does gobs of redundant work, and it allocates garbage with reckless abandon with all its temporary string construction.

We can do much better.

Some strategies I'm going to use here:

1. Single Responsibility Principle: If this is the `InputManager`, then let's make it responsible only for input. The `GameManager` can be our state machine for determining when to show/hide UI (or it can delegate this to a `MenuManager`), when it's valid to accept players joining, and when it's valid to accept a start game request.

You'll likely have other screens that want to transition in & out (like a victory/end-of-match screen), so centralizing that responsibility elsewhere also helps us stay DRY.
2. Make `GameManager` and `InputManager` singletons: that way we can find them in constant time with `GameManager.GetInstance()` instead of searching every time we want to use them. (Or you could hold a reference to the managers you need as a member variable, if you feel so inclined)
3. No string construction in the game loop: instead, let's define a clear data structure that holds all the strings we need, and just re-use them each frame. You can still populate this structure in code at start-up if you want.
4. No redundant work: we won't check the same input again and again for each player slot. We won't check an already-assigned input again for assigning a new player. And so we won't have to do extra work to check for duplicate mappings.

Instead we're going to partition our possible buttons into two sets:

* those that are still unassigned: we'll check each unassigned fire button once, and assign it to the next player in line if pressed this frame.
    * those that have been assigned: we'll check the assigned start buttons once, to decide whether it's time to start the game.

Here's what this code can look like.

```
using UnityEngine;
using UnityEngine.Events;

public class InputManager : MonoBehaviour {

    // Define a data structure for a set of input keys
    // that belong together as a logical unit.
    [System.Serializable]
    public struct InputIdMap {
        public string Fire;
        public string Start;
        public string Horizontal;
        public string Vertical;
        // ... etc,
    }

    // Singleton implementation so it's easy for other scripts to find us.
    static InputManager _instance;
    public static InputManager GetInstance() {
        if(_instance == null) {
            _instance = FindObjectOfType<InputManager>();
        }
        return _instance;
    }

    public int AssignedPlayersCount { get; private set; }

    // Wire up listeners in the Inspector or scripts to trigger stuff to happen
    // when a player joins and is assigned an input slot.
    public UnityEvent<int> onPlayerAssigned;

    // Populate this in the inspector to include all the logical control
    // groupings you use, or use a script to stamp them out in Awake().
    [SerializeField]
    private InputIdMap[] _inputSets;

    // Other scripts can ask us for the set of input strings a given player is using.
    public InputIdMap GetInputsAssignedToPlayer(int playerId) {
        // Trap any attempts to get input for players we haven't assigned yet.
        Debug.AssertFormat(playerId >= 0 && playerId < AssignedPlayersCount,
            "Tried to get input for player {0} when only {1} player(s) have been assigned",
            playerId, AssignedPlayersCount);

        return _inputSets[playerId];
    }

    // GameManager can call this when it's time to reset the assigned players.
    public void ResetPlayers() {
        AssignedPlayersCount = 0;
    }

    void Update() {
        // We'll let the GameManager be the authority about game state.
        // It will dictate when we scan for joining inputs / start game inputs.
        var game = GameManager.GetInstance();
        if (game.allowJoining) {
            // We'll maintain the invariant that the bottom entries of
            // the _inputSets array represent inputs that have been
            // assigned to a player, in order by the player assigned.

            // Iterate over only the unassigned inputs, listening to
            // the "Fire" input to activate them and assign them to a player.
            for (int i = AssignedPlayersCount; i < _inputSets.Length; i++) {
                var inputToCheck = _inputSets[i];
                // If Fire is pressed this frame, swap this to our next
                // unassigned player slot, and increment our assigned players.
                if (Input.GetButtonDown(inputToCheck.Fire)) {
                    _inputSets[i] = _inputSets[AssignedPlayersCount];
                    _inputSets[AssignedPlayersCount] = inputToCheck;
                    AssignedPlayersCount++;

                    // Let listeners know we assigned a player at this ID.
                    // Now they can spawn the player, play sound/VFX...
                    onPlayerAssigned.Invoke(AssignedPlayersCount - 1);
                }
            }
        }

        if (game.readyToStart) {
            // We can allow any player to start the game, by listening
            // for Start presses from any input in the assigned group.
            for (int i = 0; i < AssignedPlayersCount; i++) {
                if (Input.GetButtonDown(_inputSets[i].Start)) {
                    game.StartGame();
                    break;
                }
            }

            // Or, if you want only Player 1 to be able to start the game:
            //if (_playersAssigned > 0 && Input.GetButtonDown(_inputSets[0].Start))
            //    game.StartGame();
        }
    }
}

```
> 0 votes

# Answer
I see a lot of inefficient code in here.

Firstly, the `StartGame` method gets called every frame. So the `GameObject.FindWithTag` and the `GetComponent` method are being called unnecessarily on every frame. I get that it might not go inside the if condition in every frame, but why not cache the GameObject and the Component in some variables?

Secondly, you are recreating the `playerOrderString` list every time in the `ResetInput` method. But as far as I can see, all you’re doing is removing null items from the list, or if it is “not selected”. So then why not use a simpler query like `placeOrderString.FindAll(x => x != null && x != “not selected”);`? Then in this case, you can just declare the list once, and be done with it.

Thirdly, the reason why you might be missing the Input during some frames, might have to do with the fact that the IEnumerator is taking longer to yield. I don’t recommend using the IEnumerator like that in Update.

Thirdly, it’ll be hard to say why there may be lag (point out the cause specifically). I would suggest using the Unity Profiler to figure out what is happening exactly on the frames where you notice lag.
> 0 votes

---
Tags: unity, input, lag
---