# Question
Title: How do i make a list of generic classes?
First of all, I want mods in my game, as stated in a previous question, I want to do that via registries. Users make content known to the game in the form of 'Registering' it, then it can be used in several other stuff. Registering a block to have it appear on the terrain is one example.

Registering is done in the form of events, where each registry has an OnEntryCollection event with a list where other classes subscribe to in order to add Entries, and then it gets invoked to gather said entries.

Basically I have a registry system, where there's a large meta-registry(The Game-registry) that has a list of smaller `Registry<T>` registries, each dedicated to a type (a `block`, an `item`, etc). I want to be able to add to these registries via a `Registry.Add(T obj)` method, but I'm not exactly sure how to do that because in order to store them I had to use an empty interface I made (`IRegistry`).

This is meant to be a way for me to add Entries in through code, from specific files I parse in, while also allowing modders to add in custom content through registry events I will add later. Nothing is meant to be added in through the inspector, rather registered in through events.

My code:

Game-Registry:

```
[SerializeField] List<IRegistry> registries = new List<IRegistry>();

```

Registry :

```
public class Registry<T> : IRegistry where T : IRegistryEntry {
    Dictionary<ResourceLocation, T> EntryDictionary = new Dictionary<ResourceLocation, T>();

    public delegate void registryAdditionHandler(List<T> entries);
    public event registryAdditionHandler OnRegisterAddEntries;

    ResourceLocation keyName;

    public Registry(ResourceLocation keyName) {
        this.keyName = keyName;
    }

    public void Register(T entry) {
        EntryDictionary.Add(entry.GetRegistryName(), entry);
    }
    public void Remove(ResourceLocation loc) {
        EntryDictionary.Remove(loc);
    }

    public T Get(ResourceLocation key) {
       return EntryDictionary[key];
    }
    public int Count() {
        return EntryDictionary.Count;

    }

    public bool ContainsEntryKey(ResourceLocation key) {
        return EntryDictionary.ContainsKey(key);
    }
    public bool ContainsEntryValue(T value) {
        return EntryDictionary.ContainsValue(value);
    }

    public bool TryGetValue(ResourceLocation key, out T value) {
        if (EntryDictionary.TryGetValue(key,out value)) {
            return true;
        }
        return false;
    }

    public ResourceLocation getRegistryName() {
        return keyName;
    }
}

```

IRegistry interface:

```
public interface IRegistry  {
}

```

# Answer
> 0 votes
Are you looking for something like this?

```
public class MetaRegistry
{
    Dictionary<System.Type, IRegistry> _registries;

    Registry<T> GetOrCreateRegistryOfType<T>() where T: IRegistryEntry {
        Registry<T> registry;
        if (_registries.TryGetValue(typeof(T), out IRegistry interfaceRegistry)) {
            registry = (Registry<T>)interfaceRegistry;
        } else {
            registry = new Registry<T>();
            _registries.Add(typeof(T), registry);
        }
        return registry;
    }

    void AddToRegistry<T>(T value) where T : IRegistryEntry {
        GetOrCreateRegistryOfType<T>().Add(value);
    }
}

```

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


# Question
Title: How to convert linear lerp to non-linear using animation curve?
I have some code I run when I fell a tree in my game. Basically it picks a random direction and then falls. However atm it linear and doesnt look very realistic. What Id want is for it to start slow, then speed up the more it's fallen.

I've been experimenting with animation curves but none of the material I can find works with my code:

```
public void FellTree()
{
    // pick a random point on the circle to match the up vector
    Vector2 pointOnCircle = UnityEngine.Random.insideUnitCircle * transform.localScale.y;

    // find the fall point, assuming the pivot of the object is at the bottom
    Vector3 fallPoint = transform.position +
        pointOnCircle.x * transform.right +
        pointOnCircle.y * transform.forward;

    // find the target up vector
    Vector3 updatedUpVector = Vector3.Normalize(fallPoint - transform.position);

    // Start the coroutine to tilt the up vector to the desired target
    StartCoroutine(UpdateUpVector(updatedUpVector, 1, 0.001f));
}

IEnumerator UpdateUpVector(Vector3 upVector, float speed, float threshold = 0.001f)
{
    // the target vector and up vector would get closer to each other until the threshold is hit
    while (Vector3.Distance(upVector, transform.up) > threshold)
    {
        transform.up = Vector3.Lerp(transform.up, upVector, speed * Time.deltaTime);
        yield return new WaitForEndOfFrame();
    }
}

```

Using `animationCurve.Evaluate(float t)` in the lerp should be what I need to do, but not working. How can I add an animation curve to my lerp?

# Answer
You're using an exponential ease out lerp, which is not appropriate for combining with an animation curve. Use a linear lerp instead. Or a Slerp, since you're interpolating directions, to get more precise control over the rate of change using your animation curve.

```
public AnimationCurve curve;

IEnumerator UpdateUpVector(Vector3 upVector, float duration)
{
    // Cache our initial orientation.
    Quaternion start = transform.rotation;

    // Form a new orientation, that tips our up vector over by 90 degrees.
    Vector3 axis = Vector3.Cross(transform.up, upVector);
    Quaternion end = Quaternion.AngleAxis(90f, axis) * start;

    // Gradually transition over our requested duration.
    float speed = 1f/duration;
    for(float progress = 0f; progress < 1f; progress += Time.deltaTime * speed)
    {
        // Transform our linear 0-1 progress into a non-linear curve.
        float nonLinear = curve.Evaluate(progress);

        // Blend between the two rotations, according to this curve value.
        transform.rotation = Quaternion.Slerp(start, end, nonLinear);

        // Wait until next frame.
        yield return null;
    }

    // Fix-up any lingering fraction left over from the last frame of the loop.
    transform.rotation = end;
}

```
> 1 votes

---
Tags: unity
---


title: Camera Aligned To Sphere Surface

text:
# Question
Title: Camera Aligned To Sphere Surface
I am writing a planet renderer and have come across a problem that is really limiting the usability of the program. When I am on the planet (anywhere but the north pole) I cannot rotate the camera to the left or to the right as I would if I was on a flat plane. Instead I can only move as if I were aligned to a regular flat plane. This gives me awkward viewing as seen here:

This limits me to only really looking straight ahead of the camera and straight behind the camera.

I drew this to try to illustrate the problem:

Will setting the up-vector of the camera to be the the point on the sphere where I am located normalized alleviate this problem? I am at a dead-end here and any ideas would be greatly appreciated. Thanks.

# Answer
If you have an up vector, and a "look" vector (forward), you can compute a *lookat* matrix. Glu (not used much these days) has `gluLookAt`, which is replicated in math libraries such as glm. There's plenty material on it, if you do some searching.

Just a quick pseudo-code summary of a `lookat` function:

```
mat4x4 lookat(vec3 up, vec3 forward, vec3 translation)
    vec3 right = cross(forward, up)

    mat4x4 lookatMatrix;
    lookatMatrix[0] = right; // 0 = first collumn
    lookatMatrix[1] = up;
    lookatMatrix[2] = forward;

    // After that, multiply by the camera's translation matrix, and you're set
}

```

Right, up and forward are essentially the positive x, y and z axes for your camera.

As for getting the the "up" direction, as you suggested, the vector from the centre of the planet, to the camera, would work.
> 1 votes

# Answer
I know this question is old, but as this took me longer than I wish to admit to get the behaviour I wanted, I decided to post it in case it helps someone.

From your image, your roll angle is undesirably not 0. We want to be able to change only the pitch/yaw of our camera as we move around, so we need to keep the camera's right vector always parallel to the ground.

Code:

```
// pitch is the desired pitch angle. You can calculate/clip it as you want

// yawOffset is the angle you want to rotate the yaw by. I calculate it using the amount of pixels the mouse moved in the horizontal since the last frame

// GetPointRotatedAroundAxis(p, axis, angle) is a helper function that returns the point (p) rotated by the angle (angle) around the unit axis (axis). You can implement it with quaternions or standard 3d rotation matrices. I'll ommit for brevity

// projPointUAxis(p, uAxis) returns the projection of point (p) in unit axis (uAxis). It can be computed as uAxis * dot(p, uAxis)

// Do game logic, update position, etc.

// Get unit vector from sphere's center to camera's position
vec3 normal = normalize(pos - sphereCenter);

// "erase" component parallel to our normal that was generated if the camera moved since last frame, as we want to stay perpendicular to the ground where we are (in other others, right vector always parallel, in other words, roll == 0)
right -= projPointUAxis(right, normal);
// This normalization is mandatory. If right is the null vector (vec3(0, 0, 0,)), normalizing results in a division by 0, but you shouldn't need to worry about it, unless you can magically teleport 90 degrees in 1 frame to get to the position where right == normal
right = normalize(right);

// Update right vector according to new yawOffset
// Always good to normalize because of floating point errors
right = normalize(GetPointRotatedAroundAxis(right, normal, yawOffset));

// Get camera's up vector from pitch in range [-PI/2, PI/2] radians
up = normalize(GetPointRotatedAroundAxis(normal, right, pitch);

front = normalize(cross(up, right));

```

Here's what I got:
> 0 votes

---
Tags: camera, rotation, planet, sphere
---


# Question
Title: Adjusted the canvas scaler in 1 level and now the camera in every scene is changed
I was attempting to add UI overlay to my game in 1 scene (to test run it) and wanted to scale it correctly so i went to Canvas scaler and changed it to Scale with Screen size, and then suddenly my screen size in play mode got very very zoomed in so i reverted the changes. I moved it back out and that fixed it but now it seems the camera is at a completely different ratio, even after turning off the canvas. Even though i only changed it in 1 scene it has changed this for my entire game, this has made the main menu buttons unusable as well for some reason, making the game unplayable

Any help would be hugely appreciated as i worry i wont get the game fixed before the game jam im participating in is over. Thanks!

**Update**

Here is a screesnshot of the canvas, i changed Canvas Scaler UI Scale Model to Scale with Screen Size and then it said 800x600 and i changed it to 1920x1080 and then it appeared to break so i changed it back to overlay but it did nothing

Here is the camera screenshot

Below is also showing the new black bars around the game, where it would have been full screen before

This was also only for 1 scene and the effects went across every camera for some reason, and it affects the build as well

# Answer
> 1 votes
...Well i just feel very dumb now. I was looking for a setting in the inpsector somewhere when all i had really changed was the aspect ratio in the game tab. As for the buttons, I had forgotten that I had added in an image on the main menu right before this problem and the transparent part was overlapping with the button and i went to the image and turned off Raycast Target, and now the images work. Big hullabooloo for nothing haha

---
Tags: unity, ui-design
---


# Question
Title: How does "internet connection required" protect from piracy on mobile phones?
Sometimes I can't play a paid Android platform game because it requires an internet connection, and I'm in a place where 3G doesn't work.

Here is my understanding so far:

* The game is a "good old platformer" which wouldn't normally require any network (no online features for the main solo story)
* Because the publisher can't control the hardware (Android, iOS), they achieve anti-piracy by requiring an internet connection when launching the game and before each level.

My question is: how can they achieve to "obfuscate" the app enough to decrease the likelihood of piracy, where thousands of players would play the full game without purchasing? Is it extremely difficult for a hacker to record the successive states (memory snapshots) of the game when playing the full version, and recombine them in a pirate app that would skip the network traffic?

I understand that the anti-piracy internet requirement is part of a legit business model, and I'm still scratching my head about how this can be implemented and enforced in practice, and how I could do the same "from scratch".

# Answer
I don't know how the DRM of this particular game works, because I do not work at Nintendo. But a common reason why DRM requires an always-on internet connection is because not every copy of the game is the same. Everyone who buys the game gets a copy with a different license key. While the player is playing the game, the license key is sent to the server. When a second player comes online with the exact same license key, then one of them is obviously playing a copy they didn't buy.

When the game is bought through a store platform which assigns unique IDs to users or devices, you can also use an internet connection to verify purchase. The game sends the user/device ID to the server, and the server verifies that this user/device has actually bought that game.

As with every DRM scheme, this system is not bulletproof. No DRM scheme is bulletproof. When a game runs on the user's hardware, it's in the hands of the enemy. A determined hacker can find out where the game stores the license key and how to replace it with a different one. Or alternatively change the game executable so it will run without comparing the license key. But that takes some time to figure out. Most games make their most revenue during the first weeks after release. So the idea is not to deter the software pirates forever, but only until the launch weeks are over.
> 2 votes

---
Tags: mobile, online, piracy
---


# Question
Title: Why Present(0,0) is removing first rendered object?
I have to render two objects, more exactly, same object twice, just to clarify, all my constant buffers are dynamics, created like whit this flags:

```
D3D11_USAGE_DYNAMIC,
sizeof(ProjectionsBufferType),
D3D11_BIND_CONSTANT_BUFFER,
D3D11_CPU_ACCESS_WRITE,

void init()
{
            HRESULT hr = createHardwareDevice(device_.GetAddressOf(), context_.GetAddressOf());
            throwIfFail(hr, "Could not initialize DX11.1 device");

            if (device_ == nullptr)
                throw "DX11.1 device null";

            if (context_ == nullptr)
                throw "DX11.1 context null";

            // Obtain DXGI factory from device (since we used nullptr for pAdapter above)
            ComPtr<IDXGIFactory1> dxgiFactory = nullptr;
            {
                ComPtr<IDXGIDevice> dxgiDevice = nullptr;
                hr = device_->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(dxgiDevice.GetAddressOf()));
                throwIfFail(hr, "Could not initialize DX11.1 device");

                ComPtr < IDXGIAdapter> adapter = nullptr;
                hr = dxgiDevice->GetAdapter(adapter.GetAddressOf());
                if (SUCCEEDED(hr)) {
                    hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(dxgiFactory.GetAddressOf()));
                }
            }
            throwIfFail(hr, "Could not initialize DX11.1 device");

            // Upgrade to DX11.1
            ComPtr<IDXGIFactory2> dxgiFactory2 = nullptr;
            hr = dxgiFactory->QueryInterface(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(dxgiFactory2.GetAddressOf()));
            throwIfFail(hr, "Could not initialize IDXGIFactory2 for DX11.1 device");

            // Create swap chain
            DXGI_SWAP_CHAIN_DESC1 sd;
            ZeroMemory(&sd, sizeof(sd));
            sd.Width = width;
            sd.Height = height;
            sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
            sd.SampleDesc.Count = 1;
            sd.SampleDesc.Quality = 0;
            sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
            sd.BufferCount = 1;
            //sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;

            //sd.SwapEffect =
            hr = dxgiFactory2->CreateSwapChainForHwnd(device_.Get(), hWnd, &sd, nullptr, nullptr, swapChain_.GetAddressOf());
            throwIfFail(hr, "Could not initialize swap chain or upgrade for DX11.1 device");

            // Note this tutorial doesn't handle full-screen swapchains so we block the
            // ALT+ENTER shortcut
            dxgiFactory2->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);

            // Create a render target view
            ComPtr<ID3D11Texture2D> backBuffer = nullptr;
            hr = swapChain_->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)(backBuffer.GetAddressOf()));
            throwIfFail(hr, "Could not initialize swap surface for DX11.1 device");

            // Create the target view
            hr = device_->CreateRenderTargetView(backBuffer.Get(), nullptr, targetView_.GetAddressOf());
            throwIfFail(hr, "Could not initialize back buffer surface for DX11.1 device");

            // Create depth stencil texture
            D3D11_TEXTURE2D_DESC descDepth;
            ZeroMemory(&descDepth, sizeof(descDepth));
            descDepth.Width = width;
            descDepth.Height = height;
            descDepth.MipLevels = 1;
            descDepth.ArraySize = 1;
            descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
            descDepth.SampleDesc.Count = 1;
            descDepth.SampleDesc.Quality = 0;
            descDepth.Usage = D3D11_USAGE_DEFAULT;
            descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
            descDepth.CPUAccessFlags = 0;
            descDepth.MiscFlags = 0;
            hr = device_->CreateTexture2D(&descDepth, nullptr, depthStencil_.GetAddressOf());
            throwIfFail(hr, "Failed DX11.1 init. Cannot create stencil");

            // Create the depth stencil view
            D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
            ZeroMemory(&descDSV, sizeof(descDSV));
            descDSV.Format = descDepth.Format;
            descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
            descDSV.Texture2D.MipSlice = 0;
            hr = device_->CreateDepthStencilView(depthStencil_.Get(), &descDSV, _zBuffer.GetAddressOf());
            throwIfFail(hr, "Failed DX11.1 init. Cannot create stencil");

            context_->OMSetRenderTargets(1, targetView_.GetAddressOf(), _zBuffer.Get());

            // Setup the viewport
            D3D11_VIEWPORT vp;
            vp.Width = (FLOAT)width;
            vp.Height = (FLOAT)height;
            vp.MinDepth = 0.0f;
            vp.MaxDepth = 1.0f;
            vp.TopLeftX = 0;
            vp.TopLeftY = 0;
            context_->RSSetViewports(1, &vp);
}

```

Here it will render the object twice..

```
void render()
{
        context_->ClearRenderTargetView(targetView_.Get(), _backgroundColor);
        context_->ClearDepthStencilView(_zBuffer.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);

//SETUP SAMPLERS textures, buffers..
        context_->IASetInputLayout(layout);
        context_->VSSetShader(vs.Get(), NULL, 0);
        context_->PSSetShader(ps.Get(), NULL, 0);

        //............setup samplers and textures..

        UINT offset = 0;
        auto sizeOfVertex = model->getSizeofVertexBuffer();
        context_->IASetVertexBuffers(0, 1, model->getVertexBuffer().GetAddressOf(), &sizeOfVertex, &offset);

        context_->VSSetConstantBuffers(PROJECTIONS_BUFFER, 1, projBuff.GetAddressOf());

        context_->PSSetConstantBuffers(PROJECTIONS_BUFFER, 1, projBuff.GetAddressOf());
        context_->Draw(faceCount * 3, 0);

        //SECOND OBJECT..
        context_->IASetInputLayout(layout);
        context_->VSSetShader(vs.Get(), NULL, 0);
        context_->PSSetShader(ps.Get(), NULL, 0);

        //............setup samplers and textures..

        UINT offset = 0;
        auto sizeOfVertex = model->getSizeofVertexBuffer();
        context_->IASetVertexBuffers(0, 1, model->getVertexBuffer().GetAddressOf(), &sizeOfVertex, &offset);
        //..........Transform projection buffer to traslate second object..

        context_->VSSetConstantBuffers(PROJECTIONS_BUFFER, 1, projBuff.GetAddressOf());

        context_->PSSetConstantBuffers(PROJECTIONS_BUFFER, 1, projBuff.GetAddressOf());
        context_->Draw(faceCount * 3, 0);

        HRESULT hr = swapChain_->Present(0, 0);

}

```

The problem is next: When I render 1 object, it will render fine, when I render second, render fine, but when I render both, the first rendered simply dissapears showing only the second one. When I debug using visual studio, the Render screen flashes constantly from first to second, never stops, however the Visual studio graphics debugger shows the calls: ClearRenderTargetView(.....) ClearDepthStencilView(......) Draw(21760,0) Draw(21760,0) Present(0,0)

When I click on first Draw call, show me the first rendered object, when I click second Draw call, shows me BOTH objects, but when I click Present, the first object simply disappears and only shows me the second one..

When I test the pixel shader in position where the first element should be, it gives me the color should be in this position, however, not showing both objects in rendered screen..

UPDATE: now checking on the Graphic debugger I have this(pixel rejected) and don't know why:

UPDATE2: Pixel shader stage did not run on 2 draws, only run on the first.. SOLVED:

```
D3D11_DEPTH_STENCIL_DESC dsDesc;

        // Depth test parameters
        dsDesc.DepthEnable = true;
        dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
        dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; //FIX TO EXECUTE ALL PIXEL SHADERS!!!

        // Stencil test parameters
        dsDesc.StencilEnable = true;
        dsDesc.StencilReadMask = 0xFF;
        dsDesc.StencilWriteMask = 0xFF;

        // Stencil operations if pixel is front-facing
        dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

        // Stencil operations if pixel is back-facing
        dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
        dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

        // Create depth stencil state
        ID3D11DepthStencilState* pDSState;
        device_->CreateDepthStencilState(&dsDesc, &pDSState);
        context_->OMSetDepthStencilState(pDSState, 0);

```

UPDATE3: All pixel shaders are executing right now, but the output merger did not show me both objects, still "PIXEL WAS EXCLUDED BECAUSE IT FAILED A DEPTH TEST"..

# Answer
> 0 votes
Finally I solve the problem, was the DYNAMIC BUFFER, on the map function do not use D3D11\_MAP\_WRITE\_NO\_OVERWRITE unless you are an expert, buffer update was the problem, instead use: D3D11\_MAP\_WRITE\_DISCARD. I have tested anything, since write 3, 4, 5 objects to change Rasterizer, to add D3D11\_DEPTH\_STENCIL\_DESC, D3D11\_BLEND\_DESC1 and none of those work, always render only 1 Object, and always the last one... When I changed from D3D11\_MAP\_WRITE\_NO\_OVERWRITE to D3D11\_MAP\_WRITE\_DISCARD in call:

`Map(buffer, 0, D3D11_MAP::D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);`

Problem solved

Microsoft: (https://docs.microsoft.com/en-us/windows/win32/direct3d11/how-to--use-dynamic-resources) D3D11\_MAP\_WRITE\_NO\_OVERWRITE indicates that the app will not overwrite data already in use in the dynamic buffer. The Map call will return a pointer to the old data, which will allow the app to add new data in unused regions of the vertex or index buffer. The app must not modify vertices or indices that are used in a draw operation as they might still be in use by the GPU.

We recommend that the app then use D3D11\_MAP\_WRITE\_DISCARD after the dynamic buffer is full to receive a new region of memory, which discards the old vertex or index data after the GPU is finished.

StackOverflow explanation: https://stackoverflow.com/questions/23368880/differences-of-directx11-d3d11-map

---
Tags: c++, directx11
---


# Question
Title: How to properly format classes for JSON deserialization with JSON.net for Unity?
\**UPDATE: This answer has been solved and this post updated to \**

I am creating an inventory system and decided to keep a master list of all the items. The goal is to use Newtonsoft's JSON.net to parse the item list and populate the database of items. The JSON item list looks like:

**JSON**

```
{
"Ingredients":
    [

    ],
"Consumables":
    [
            {
            "ID" : "TP_Small",
            "Icon" : "Sprites/porridge.png",
            "Name" : "Small Tan Pill's Porridge",
            "Consumable" : true,
            "Cooldown": 0,
            "Duration": 3,
            "Effect Description" : "Restores 100 health.",
            "Description" : "A hearty drinkable meal from everyone's favorite hypercellulose gelatin timelord!!!",
            "SFX": "{eb4e9ad8-c6ac-414f-8d5e-c3d012ca6ae6}",
            "Bonuses" : {
                "HP": 100,
                "Stamina": 100,
                "Tolerance": 20,
                "Attack": 4
                }
            }
    ],

"Concoctions":
    [

    ],
"Equipment":
    [

    ],
"Abilities" :
    [

    ]
}

```

And this is the structure of the classes we are using to match the JSON:

**Classes**

```
[System.Serializable]
public class Items
{
    public List<ItemBase> Ingredients;
    public List<ItemBase>Consumables;
    public List<ItemBase>Concoctions;
    public List<ItemBase>Equipment;
    public List<ItemBase>Abilities;
}

[System.Serializable]
public class ItemBase
{
    public string ID;
    public string Icon;
    public string Name;
    public bool Consumable;
    public int Cooldown;
    public int Duration;
    public string EffectDescription;
    public string Description;
    public string SFX;
    public StatBonus Bonuses;
}

[System.Serializable]
public class StatBonus
{
    public int HP;
    public int Stamina;
    public int Tolerance;
    public int Attack;
 }

```

**The deserialization code:**

```
TextAsset json = Resources.Load<TextAsset>(path);

    itemList = new Items();

    itemList.Abilities = new List<ItemBase>();
    itemList.Concoctions = new List<ItemBase>();
    itemList.Consumables = new List<ItemBase>();
    itemList.Equipment = new List<ItemBase>();
    itemList.Ingredients = new List<ItemBase>();

    itemList = JsonConvert.DeserializeObject<Items>(json.text);

```

This code now works as intended!

# Answer
> 1 votes
First, a few minor tweaks that might depend on your JSON library (it looks like you're using the Newtonsoft JSON library, rather than the built-in Unity `JsonUtility`); I can't say whether your version behaves differently, but for Unity's JSON implementation:

* The serializer will serialize/deserialize **fields, not properties** \- so you'd have to remove all the `{ get; set; }` auto-property markup to get the fields to be picked up that way
* Your fields need to be marked **`public` or `[SerializeField]`** \- your `ItemBase` and `StatBonus` members lack this at the moment.
* The serializer **starts at the level of the members of the root object**, rather than treating the root object as a named member of an enclosing object, so you can remove the outermost `"Items":{ ... }` wrapper and jump straight from the outer `{...}` into your categories.

Again, feel free to disregard these points if they're unique to Unity's `JsonUtility` and not reflective of the library you're using.

The more fundamental problem is that your JSON and your class definitions don't agree.

Your JSON corresponds to an `Items` class with named fields for each category, which is just a list or array of `ItemBase`:

```
[System.Serializable]
public class Items
{
    public List<ItemBase> Ingredients;
    public List<ItemBase> Consumables;
    public List<ItemBase> Concoctions;
    public List<ItemBase> Equipment;
    public List<ItemBase> Abilities;
}

```

Your `Items` class corresponds to JSON with a `type` field, and anonymous array/list entries for each category, each one having an `id` member to contain the list:

```
{
    "type": [
        {
            "id": [
                {
                    "ID": "foo",
                    "Icon": "bar",
                    "Name": "baz",
                    "Consumable": false
                }
            ]
        },
        {
            "id": [
                {
                    "ID": "foo",
                    "Icon": "bar",
                    "Name": "baz",
                    "Consumable": false
                }
            ]
        }
    ]
}

```

A good way to make sure your JSON and internal class definitions match-up: whip up a script that synthetically creates and populates an instance of your class with dummy data, then spits out the JSON that results.

```
public class JSONTest : MonoBehaviour
{
    [TextArea(5, 50)]
    public string jsonOutput;

    void Start()
    {
        var items = new Items();

        items.type = new List<ItemCategory>();
        var category = new ItemCategory();
        items.type.Add(category);
        category = new ItemCategory();
        items.type.Add(category);

        category.id = new List<ItemBase>();
        category.id.Add(new ItemBase() { ID = "foo", Icon = "bar", Name = "baz", Cooldown = 42, Duration = 7, EffectDescription = "Very Good", Description = "Something" });

        jsonOutput = JsonUtility.ToJson(items, true);
    }
}

```

Then you can compare the formatting of that result against the JSON you were trying to use, to either adjust your input to match your internal representation, or adjust your internal representation to suit your input.

---
Tags: unity, c#, serialization, json
---


title: Pygame Scrolling Bug With Enemys

text:
# Question
Title: Pygame Scrolling Bug With Enemys
I have a problem with my enemy where when my player scrolls left the enemy scrolls with the player. Is there anyway to fix this?

Video

My full code is linked below, as it's too long to fit here.

What I was trying to do is make my enemy not to change its position when my window is scrolling. Its doing the same for right and left and keeps following the player.

```

while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
  [...]
# I did the same for my players key movement  this part suppose to not make my player scroll
if playerman.y < 250:
        playerman.y += 1
        for platform in platforms:
            platform.y += playerman.speed
        for enemys in enemying:
            enemys.y += playerman.speed

```

My enemy class:

```
class enemy:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.walking_index = 0
        self.rect = pygame.Rect(x,y,height,width)
       def draw(self,window):
       self.move()
       if self.Walking_index + 1 >= 33:
           self.Walking_index = 0
       if self.vel > 0:
           window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       else:
           window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       def move(self):
       if self.vel > 0:
           if self.x + self.vel < self.path[1]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0
       else:
           if self.x - self.vel >  self.path[0]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0

```

Where I defined the enemy class:

```
black = (0,0,0)
enemys1 = enemy(550,436,50,50,300)
enemys = [enemys1]

```

My entire code is here.

# Answer
> 1 votes
The issue is caused by how you draw the enemies. When you draw an object, you are using something like: `screen.blit(image, pos)` however, when you move, that `pos` variable does not update to compensate for the moving plane of view. Instead, do something like (this is pseudocode, so it wont work):

```
def onscroll(enemies_list, delta_scroll): # the delta_scroll variable is the change in
#the screens location (positive or negative)
    for x in enemies_list:
        x.position = (x.position[0] - delta_scroll, x.position[1])

```

also, if you have a return position, you want to also compensate using:

```
x.return_pos -= delta_scroll

```

Hope this helps!

---
Tags: python, pygame
---


title: I can’t get a teleport to work c#

text:
# Question
Title: I can’t get a teleport to work c#
these are the pics of the inspect panel on the parts of the 3D pacman that you asked for.

(I just added these photos because I couldn’t while i was away and because even though the advice given so far was amazing, it didn’t resolve my problem, so please help if you can)

I’ve been trying to make a teleport for a while and it works only part of the time. the collisions work because i put a debug.log in it but the teleporting part doesn’t work. there are no errors in the collision, it just doesn’t teleport the pieces of pacman. here is the script (it's not the most improved but i was trying to make it work)

```
public GameObject pacman;
public GameObject Camera;
public GameObject pointLight;
public GameObject body;
public Vector3 pacmantele;
public Vector3 cameratele;
public Vector3 pointlighttele;
public Vector3 bodytele;

void OnTriggerEnter(Collider other)
{
    Debug.Log("works");
    pacman.transform.position = pacmantele;
    Camera.transform.position = cameratele;
    pointLight.transform.position = pointlighttele;
    body.transform.position = bodytele;
}

```

---

here is a photo of the inspection panel on the non-working teleporter

# Answer
The `OnTriggerEnter` method usually needs to know what entered it. So the correct form for that method is this:

```
void OnTriggerEnter(Collider other)

```

If you forget the parameter `Collider other`, Unity will not recognize it as an event handler for the TriggerEnter event.

Further, keep in mind that this method will be called for *any* game-object that enters the teleporter. Sometimes that's intended, but usually you want to have *some* condition on what can and can not trigger a trigger.

In this case the logic seems to be written specifically for the object `pacman`, so it seems like you only want to execute that teleportation logic if `pacman` entered the trigger. So I added a check which makes sure only `packman` will trigger this teleporter:

```
void OnTriggerEnter(Collider other)
{
    Debug.Log("Object " + other.name + " entered the teleporter");
    if (other.gameObject == pacman)
    {
        pacman.transform.position = pacmantele;
        Camera.transform.position = cameratele;
        pointLight.transform.position = pointlighttele;
        body.transform.position = bodytele;
    }
}

```

If it still does not work, make sure that:

* `pacman` has a collider which is **not** a trigger.
* `pacman` has a rigidbody. If you don't actually want rigidbody physics in your game, make it a kinematic rigidbody.
* That its physics layer collides with the physics layer of the teleporter
* That both teleporter and pacman have any of the regular colliders, not a collider of the 2D family, because 2d and 3d colliders do not interact with each other. If you actually want to use 2D physics, use the method `OnTriggerEnter2D(Collider2D other)` and use Rigidbody2D instead of Rigidbody.
> 1 votes

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


# Question
Title: In ROBLOX, how can I check what is in front of me?
In ROBLOX Studio I need to check what part is in front of the model `Freddy`.

I need to set the variable called `thingInFront` to the part that is in front of the model `Freddy` so that I can decide whether I should allow him to walk through or not. This is my current code:

```
thingInFront = nil
if thingInFront.BrickColor == BrickColor.new('Black') then
    script.Parent.Parent.CanCollide = true
else
    if not thingInFront.BrickColor == BrickColor.new('Black') then
        script.Parent.Parent.CanCollide = false
    end
end

```

# Answer
> 2 votes
Just like to say that I have little experience in the lua language

**BUT,**

If you take the x y z position of your model "Freddy" and the x y z position of all your other bricks, from there you could find the distance between "Freddy" and the brick and whether the color of that brick is black or not. Then when "Freddy" is a touching distance from the brick, you can allow him to pass through it or not.

Hopefully this helps.

# Answer
> 0 votes
I know this respond is late but for whoever will check this I highly recommend using Dot product aka scalar product (math) to see if the instances is in front of your "Freddy" character. Dot product returns the scalar which represents the length of the vector calculated by taking 2 vectors and the angle between them.

Why ? Dot product is extremely cheap as its a simple calculation. It's also easy to use and fast to set it up.

-- Note

U should be aware of calculating it by using CFrame.LookVector (depending on your case) so it won't compute World position but the relative position to your character.

---
Tags: 3d, lua, roblox
---


# Question
Title: When PlayerRemoving event is fired, for loop does not work properly
while I was implementing the Backback save feature in my Roblox Game (using `game.Players.PlayerRemoving:Connect()`, I found that when I used a loop of any form (`for`, `while`,etc.), it would not run correctly. Here is a test program which I wrote to observe this issue:

```
game.Players.PlayerRemoving:Connect(function(player)
    local testList = {"Hello", ",", "world"}
    for i=1,3,1
    do
        print(testList[i])
    end
end)

```

However, when this code is ran, all I see in the output window is:

```
Hello

```

And nothing else. This issue is causing a lot of issues with the rest of the code, can somebody please help? It would be very useful!

# Answer
> 1 votes
I tested the code as I didn't see anything wrong with it and it works fine. Be sure to check if there are any yields, breaks, anything that could stop PlayerRemoving event from firing / executing the whole code.

---
Tags: lua, savegame, roblox
---


# Question
Title: How to call StartCourotine in abstract class?
Bellow is my code. I have an abstract class and a inheriting class. This keeps giving me an `NullReferenceException`, on the `StartCoroutine(WaitForTime)` when `Activate()` is called on a `InheritedClass` instance. I can't figure it out.

```
public abstract class AbstractClass : MonoBehaviour
{
abstract protected string iD { get; }
abstract protected int CooldownSeconds { get;  }

protected bool IsInCooldown { get; set; }

public void Activate()
{
    if (!IsInCooldown)
    {
        TurnOn();
        StartCooldown();
    }
}

protected abstract void TurnOn();

public void StartCooldown()
{
    IsInCooldown = true;
    StartCoroutine("WaitForTime");
}

protected IEnumerator WaitForTime()
{

    yield return new WaitForSeconds(CooldownSeconds);
    IsInCooldown = false;
}

}

public class InheretingClass : AbstractClass
{
    protected override int CooldownSeconds { get => 30;}

protected override string collD => "Cool";

protected override void TurnOn()
{
    Debug.Log( iD + " Activated");
}
}

```

# Answer
> 1 votes
I'm unable to reproduce this problem. Testing with the following `AbstractClass`:

```
public abstract class AbstractClass : MonoBehaviour {
    abstract protected string iD { get; }
    abstract protected int CooldownSeconds { get; }

    protected bool IsInCooldown { get; set; }

    public void Activate() {
        if (!IsInCooldown) {
            TurnOn();
            StartCooldown();
        }
    }

    protected abstract void TurnOn();

    public void StartCooldown() {
        Debug.Log("Starting coroutine");
        IsInCooldown = true;
        StartCoroutine(WaitForTime());
        // StartCoroutine("WaitForTime"); // Also works, but it's less efficient.
    }

    protected IEnumerator WaitForTime() {
        Debug.Log("The wait is starting...");
        yield return new WaitForSeconds(CooldownSeconds);
        IsInCooldown = false;
        Debug.Log("The wait is over!");
    }
}

```

And this `ConcreteClass`:

```
public class ConcreteClass : AbstractClass
{
    override protected string iD { get { return name; } }
    override protected int CooldownSeconds { get { return 1; } }

    protected override void TurnOn() {
        Debug.Log("Turning on");
    }

    private void Start() {
        Activate();
    }
}

```

I get no exceptions, and the console log prints:

* Turning on
* Starting coroutine
* The wait is starting...
* The wait is over!

So apparently the answer to "How to call StartCourotine in abstract class?" is "exactly the way you're already doing it".

Your problem may be coming from somewhere else in your project. Please try to reproduce this problem in a new, empty project containing as few scripts as possible, then edit your question to detail every step we need to follow to cause the problem. This will help narrow down what unseen code/scene configuration is responsible, so we can find solutions for your situation.

---
Tags: unity, coroutines, inheritance, monobehaviour
---


title: How does 3D mesh morphing work?

text:
# Question
Title: How does 3D mesh morphing work?
In the Sims 4, you can drag to reshape the face and body when you create a sim. You can see a similar system implemented in this Body Visualizer.

How can I implement similar geometry morphing in my game?

Related: What are some ways to implement variable body shapes?

# Answer
> 5 votes
> In the Sims 4, you can drag to reshape the face when you create a sim. How is the geometry morphing implemented?

Only guys with access to the code can tell you that.

> In general, how do you code a system that morphs different parts of a mesh?

I don't know if there is any commonly agreed way of doing this, but basically what you are asking is not as complicated as it might seem. You create a basic unmodified mesh. Then you add functions with specific parameters and boundary conditions at local areas of your mesh. To give you a simple 2d example, let's consider the function in the following picture is your base mesh:

You can modify the shape by adding arbitrary y values at any x position. If you want to have a smooth curve you need a mathematical function, that describes your modification or morphing curve. However, this function needs to fulfill the condition that it's gradient and function value is 0 at its interval boundaries, otherwise, you will see some kinks or jumps. One function that fulfills this requirement is the cosine function minus 1 in the interval 0 to 2Pi:

Now all you have to do is to scale the functions intervals and function values to your liking and to the ranges of the mesh area you want to be affected. After some shifting and scaling you might get a morphing function like this:

If you add it to your base mesh, you get this:

Finding the right parameters and their limits for such a function is the job of the artist that creates the mesh. Of course, artists are usually no mathematicians and you can't expect them to have a solid knowledge of suitable functions for this task, especially not in 3d. Luckily, there is a set of universal functions for this task: Splines (search for B-Splines or NURBs). These special functions can easily be "bend" to any shape and artists usually already use them to generate the base meshes.

I have to state here, that I am not an industry professional and not an artist. Just a passionate hobby programmer that works on his own game engine and reads a lot of related literature. But I might not be up to date anymore. So there might be other (smarter) approaches to this. For example, you can probably get more realistic results by using a model based on muscles, bones, etc. and calculate the corresponding skin surface from their sizes and shapes. However, this would just move the problem to another area (shape of muscles and bones).

If you want to understand a little bit better, how the plots above are generated, the Python code I used to generate them is attached below. Modify the 3 parameters that control the position, width, and height to see how they affect the result.

```
import numpy as np
import matplotlib.pyplot as plt

# parameters
morph_height = 0.2
morph_width = 80
morph_shift = 25

# original shape
x = np.arange(-1, 1.001, 0.01)
y_base = -0.5 * x * x + 1

# generate morph function
y_morph = np.zeros(len(x))
for i in range(morph_width + 1):
    # scale function interval
    p = 2 * np.pi * i / morph_width
    # scale height and write to affected area
    y_morph[i + morph_shift] = morph_height * (np.cos(p) - 1) / 2

y_total = y_base + y_morph

plt.plot(x, y_base)
plt.ylim(0, 2)
plt.xlabel("x")
plt.ylabel("y")
plt.title("unmodified shape")

plt.figure()
plt.plot(x, y_morph)
plt.ylim(-1, 1)
plt.xlabel("x")
plt.ylabel("y")
plt.title("morph function")

plt.figure()
plt.plot(x, y_total)
plt.ylim(0, 2)
plt.xlabel("x")
plt.ylabel("y")
plt.title("result")

plt.show()

```

# Answer
> 4 votes
We do not know the details of how they did it… However, there is a modding community for The Sims and they manage.

The idea is as follows: There is one base model for body type. There are series of sliders that can modify the base model. Each one will have a set of vertex they can modify, and a second target model. Then moving the slider is interpolating the vertex between the base model and the target model.

It gets complicated when multiple slider can control the same vertex. I don't know how they do it in the game, probably only the developers know…

---

What follows is how I would tackle the problem. For each vertex, let us work in a coordinate system with origin at the position of the vertex on the base model. In other words, we will work with the offset by which we are going to move the vertex.

Now, each slider will try to move the vertex in a particular direction. That is, each slider, would independently apply a particular offset. We can compute the offset for each slider, and then we just add them.

Why add? Because that way all sliders that are at 0 have no effect.

*I have not implemented this. What I'm saying that I would start there.*

---

My rational for the above approach is to imagine a space of posible inputs. This space would have a dimension for each slider. And we know the offset we want to get at some particular points, which happen to be along the axis. For the rest of the space we want the output to be smooth and continuous. Doing a linear combination of them makes sense. And that is just a weighted sum of the difference between the target model of each slider and the base model, where the value of the slider is the weight.

*I hope that makes sense.*

---

If we wanted to that in GPU, we would do it in a vertex shader… which means we need to upload to the GPU all the coordinates for all the target models too (here is an idea: use textures)… and this computation would be happening all the time. I think that is overkill. Do this computation once, in CPU or GPU, and then just upload the result to the GPU.

# Answer
> 2 votes
There are a several ways to do it, but the general principle is the same:

You can morph between more than 2 meshes, but for this example, let's assume 2; the logic remains exactly the same for more of them.

At the root, each vertex is essentially two vertices (one from the source mesh, and one from the destination mesh) and you interpolate between the two, based on where you are in the morph. So, on one side you have the position of Mesh1, on the other side, the position of Mesh2 and then, anything in between.

This can be trivially done on the GPU.

The main difficulty is how to match vertices from mesh1 to mesh2. If you don't match them properly, your mesh will completely deform and collapse as it undergoes morphing. For example, interpolating between a vertex that is part of the nose and one part of the ear is not going to look very good.

There are multiple ways this can be done and none of them are ideal because you will always encounter edge cases. When there is no trivial solution for those, usually vertices end up manually tagged together by the artist.

If you have a mesh that is mostly convex, it is a lot easier: you can determine the center of both meshes and then, for each vertex compute a line going through the vertex and that center, for both meshes. For each vertex on mesh1, you can match a vertex on mesh2 by comparing the angles between the lines and taking the one with the smallest one. This is how it used to be done a very long time ago.

An improvement to this was eventually developed and instead of looking at vertices, you'd start considering triangles, and the center of each triangle. Using this, you'd match triangles and from there match vertices.

And, many more techniques were developed, but since you're starting with this, these two will give you some quick results you can implement easily and improve upon; there are more advanced methods, but they're not trivial to implement like these and may require work in the tool pipeline.

Now we're been looking only at morphing the meshes, but many effects you see are actually interpolating between multiple bone setups. Morphing the mesh will go from Face A to Face B for example (and you can cross fade textures for example), but body types, facial expressions, etc use exactly the same system but instead of interpolating between vertices, you interpolate between the different bone positions. So each vertex's position is weighted to several bones in your rig and you can interpolate those positions directly and make someone fat, tall, etc. So, keep in mind that many effects are really not the mesh itself morphing. One face with multiple bone setups will give you a very large number of faces for example.

Now, there are plug-ins made for this in 3DSMax and Maya that will allow you to edit the vertex groups so the matching can be done visually. This is the simplest way to do it, but if you begin in this, I wouldn't recommend you spend too much time on the tool side because this can be extremely time consuming and you'll spend a year coding tools and exporters instead of a game (I've seen that happen a lot). To get something going quick, use relatively similar meshes and automatic vertex matching because you'll be able to code that very fast and it may work well enough for your application.

---
Tags: 3d, 3d-meshes, mesh
---


# Question
Title: In Unreal why is it safe to access a UTexture2D's properties from the render thread despite the documentation stating this is not allowed?
I've been trying to implement something that will update textures on the render thread from a background thread. And from what I've read of the unreal engine documentation you should never access a descendant of `UObject` from the render thread since the game thread could deallocate it at any time. Epic describes an example of this situation in their documentation

> Here is a simple example of a race condition / threading bug:
>
> ```
> /** FStaticMeshSceneProxy Actor is called on the game thread when a component is registered to the scene. */
> FStaticMeshSceneProxy::FStaticMeshSceneProxy(UStaticMeshComponent* InComponent):
>     FPrimitiveSceneProxy(...),
>     Owner(InComponent->GetOwner()) <======== Note: AActor pointer is cached
>     ...
>
>    /** DrawDynamicElements is called on the rendering thread when the renderer is doing a pass over the scene. */
>     void FStaticMeshSceneProxy::DrawDynamicElements(...)
>     {
>         if (Owner->AnyProperty) <========== Race condition!  The game thread owns all AActor / UObject state,
>             // and may be writing to it at any time.  The UObject may even have been garbage collected, causing a crash.
>             // This could have been done safely by mirroring the value of AnyProperty in this proxy.
>     }
>
> ```

However the actual code they write violates this rule all of the time. There are numerous examples in `FTexture2DResource` accessing its `Owner` property which is a `UTexture2D*` from the render thread. Just one is

> ```
> /**
>  * Called when the resource is initialized. This is only called by the rendering thread.
>  */
> void FTexture2DResource::InitRHI()
> {
>   FTexture2DScopedDebugInfo ScopedDebugInfo(Owner);
>   INC_DWORD_STAT_BY( STAT_TextureMemory, TextureSize );
>   INC_DWORD_STAT_FNAME_BY( LODGroupStatName, TextureSize );
>
> #if STATS
>   if (Owner->LODGroup == TEXTUREGROUP_UI) <========== Accessing LODGroup from owner should be unsafe
>     {
>         GUITextureMemory += TextureSize;
>     }
> ...
> }
>
> ```

This seems to directly contradict the documentation given by Epic even though this is commonplace in their source code.

From the source it doesn't look like `FTexture2DResource` or any of its ancestors perform any smart pointer magic or add the UTexture2D object to the root set to prevent GC and even then race conditions would still apply.

I'll probably end up answering this one myself, but it would be great if someone happened to know this.

# Answer
> 2 votes
I think I've figured out how it works. I'll edit this answer if I find a definitive answer.

It was actually simpler than I was thinking. `FRenderResource` instances are issued commands solely on behalf of some `UObject` descendant that owns it. So when that `UObject` is marked to be destroyed a final command to destroy the `FRenderResource` it owns is issued to the Render Queue by the `UObject`. Since its a queue the last command issued that uses the `FRenderResource` instance will be the one that destroys it. The `UObject` waits for the destruction of the `FRenderResource` before releasing itself. In specific case `UTexture` has a `ReleaseFence` property of type `FRenderCommandFence` that allows it to check when the command it issued to destroy its `FRenderResource` has been processed.

As for race conditions I think those variables are probably just `private` and not changed internally after initialization of the `UObject`, but this is just conjecture I haven't actually checked.

---
Tags: c++, unreal-4, multithreading
---


# Question
Title: Ordering vertices of a face for correct triangle definition
I'm trying to ascertain the appropriate order of vertices for the face of a mesh that is programmatically created. Currently the face is always a quadrangle, but eventually a face can consist of any number of vertices ≥3. What I have are the `Vector3` of the vertices, the `Vector3` of the normal, and the `Vector3` of both up and left. Because these faces can have any rotation, they are not guaranteed to be (and will rarely be) completely perpendicular to any of the three primary axes.

I've looked at using dot products and matrices to try to remap them to a 2D coordinate system, but I could not quite get it right, and that rotation could also be problematic for faces on the "top" and "bottom" of a mesh.

As it is, I'm trying to find a formula that would use the vertices, the normal, up, and left to (in the case of a quadrangle) start with the upper-leftmost vertex if facing it from the normal direction and work clockwise from there. I could use the ordered vertices to properly build triangles that would suit the normal and display properly.

I'm not bad with math, per se, but vector mathematics are outside of my comfort zone, which is in part why I'm going through this exercise.

**TL;DR**, I have a cube which is transformed and rotated randomly in 3D world space. I've captured each face into an object that contains the vertices, normal, up, and left direction (normal for the face, up and left as far as the `GameObject` itself is concerned) and want to order the vertices for triangle mapping for the mesh.

# Answer
Normally this would be something you handle earlier in your generator function - generating vertices in a known winding by construction, rather than sorting them after the fact.

That said, you can make a function to put the vertices in a winding of your choice like so:

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

public class ProcMesh : MonoBehaviour
{
    struct Sortable<T> : System.IComparable<Sortable<T>> {
        readonly public T value;
        readonly public float key;

        public Sortable(T value, float key) {
            this.value = value;
            this.key = key;
        }

        public int CompareTo(Sortable<T> other) {
            return key.CompareTo(other.key);
        }
    }

    // Cached temporary list we can re-use for each sort, rather than re-allocating.
    List<Sortable<Vector3>> _toSort = new List<Sortable<Vector3>>();

    void SortFaceVertices(List<Vector3> vertices, Vector3 normal) {
        // Find the rough center point of the face.
        Vector3 centroid = Vector3.zero;
        foreach (var vertex in vertices)
            centroid += vertex;
        centroid *= 1f / vertices.Count;

        // Form an orientation that points the z+ axis along the normal.
        Quaternion orientation = Quaternion.LookRotation(normal);
        // Its inverse maps the face into the XY plane.
        Quaternion toXY = Quaternion.Inverse(orientation);

        // Fill our sortable collection with entries for each vertex.
        _toSort.Clear();
        foreach (var vertex in vertices) {
            // Map the vertex into the XYplane, with the face at the origin.
            Vector2 inPlane = toXY * (vertex - centroid);

            // Compute its angle counter-clockwise from the x+ axis.
            float angle = Mathf.Atan2(inPlane.y, inPlane.x);

            // To sort clockwise, multiply the angle by -1.
            _toSort.Add(new Sortable<Vector3>(vertex, angle));
        }

        // Do the actual sorting!
        _toSort.Sort();

        // Fill the list we were provided with vertices in our sorted order.
        for (int i = 0; i < vertices.Count; i++)
            vertices[i] = _toSort[i].value;
    }
}

```
> 1 votes

---
Tags: linear-algebra, dynamic-mesh
---


# Question
Title: Making an object orbit using c# script for Unity+Vuforia
I have written a simple c# script for Unity+Vuforia. I want to create a simple sample project where an object like a sphere is revolving (orbiting) origin (0,0,0) above image target.

The code I have written is here

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

public class Orbit : MonoBehaviour
{
    float angles;
    float radiuss;
    float angleSpeed;

    // Start is called before the first frame update
    void Start()
    {
        angles = 0;
        radiuss = 0.2f;
        angleSpeed = 1;

    }

    // Update is called once per frame
    void Update()
    {
        angles += Time.deltaTime * angleSpeed;

        float x = radiuss * Mathf.Cos(Mathf.Deg2Rad * angles);
        float z = radiuss * Mathf.Sin(Mathf.Deg2Rad * angles);
        float y = 0;

        transform.position = new Vector3(x, y, z);
    }
}

```

It works perfectly fine if I am not using it with Vuforia, but when I attach this script as component to an object in Vuforia, it does not work and acts weird. These are the configurations and hierarchy

Please help me out, I tried a lot of things.

# Answer
> 1 votes
It looks to me like you want to change this line:

```
transform.position = new Vector3(x, y, z);

```

to use `localPosition` instead:

```
transform.localPosition = new Vector3(x, y, z);

```

This says "place me here *relative to my parent's coordinate system*," so as Vuforia moves the parent around, this object will track that motion, while also layering its own motion on top.

---
Tags: unity, c#, augmented-reality, vuforia
---


# Question
Title: How to make a list containing both strings and functions in c#?
Whilst it doesn't neccesarily need to be a list, I just need a variable that I can index, and arrive at either a string or a function. I've tried using List and whilst this works for strings, when I try to store a function I get an error message along the lines of "cannot convert from void to object".

Does anyone know how this might be done?

# Answer
I am not sure for what you'll need this but this should work for you:

```
    private void test()
    {
        IList<object> list = new List<object>();
        list.Add("mystring");
        Func<string, string> anyFunction = AnyFunction;
        list.Add(anyFunction);

        Action voidFunction = AnyVoidFunction;
        list.Add(voidFunction);

        foreach (var item in list)
        {
            if (item is string)
            {
                Debug.WriteLine(item);
            }
            if (item is Func<string,string>)
            {
                var result = (item as Func<string, string>)("Call it");
                Debug.WriteLine("Function result is: "+result);
            }

            if(item is Action)
            {
                //Call method
                (item as Action)();
            }
        }

        //as it is a list you can of course index it
        var indexedItem = list[0];

    }

    private string AnyFunction(string inputString)
    {
        return "Anything "+ inputString;
    }

    private void AnyVoidFunction()
    {
        Debug.WriteLine("AnyVoidFunction called!");
    }

```

The variable 'list' will hold the string "mystring", the function "AnyFunction" and the method "AnyVoidFunction".

Then the list is iterated. The output will be:

```
mystring
Function result is: Anything Call it
AnyVoidFunction called!

```

This will work with all the arrays, lists, dictionaries, stacks, queues and so on in C#.

btw.: As the focus of the question is not really game releated but more of a programming question: https://stackoverflow.com/ will be better to ask.
> 0 votes

# Answer
Do the values need to be ordered in any way? If not this might work:

```
public class StringAndFunctionList
{
    private List<string> _strings = new List<string>();
    private List<Function> _functions = new List<Function>();

    public dynamic this[int index]
    {
        get
        {
            if (index >= 0)
                return _strings[index];
            return _functions[-1-index];
        }
    }

    //Adds a new value and returns its index
    public int Add(dynamic value)
    {
        if(value is string)
        {
            _strings.Add(value);
            return _strings.Count - 1;
        }
        else if(value is Function)
        {
            _functions.Add(value);
            return -_functions.Count;
        }
        throw new ArgumentException();
    }
}

```

Functions have negative indizes, strings have positive indizes.
> 0 votes

# Answer
```
using System;
using System.Collections.Generic;

class StringOrFunction
{
    public string String;
    public Delegate Func;
    public readonly bool IsFunc;

    public StringOrFunction(string str)
    {
        String = str;
    }
    public StringOrFunction(Delegate func)
    {
        IsFunc = true;
        Func = func;
    }
    public static implicit operator StringOrFunction(string str)
    {
        return new StringOrFunction(str);
    }
    public static implicit operator StringOrFunction(Delegate func)
    {
        return new StringOrFunction(func);
    }
}
class Program
{
    static void Main(string[] args)
    {
        void world()
        {
            Console.Write("world");
        }

        var list = new List<StringOrFunction>
        {
            "Hello ",
            (Action) (world),
            (Action) (() => Console.WriteLine("!"))
        };

        foreach (var stringOrFunction in list)
        {
            if (stringOrFunction.IsFunc)
            {
                stringOrFunction.Func.DynamicInvoke();
            }
            else
            {
                Console.Write(stringOrFunction.String);
            }
        }
    }
}

```
> 0 votes

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


title: Calculate UV sphere vertices (altitude)

text:
# Question
Title: Calculate UV sphere vertices (altitude)
There is an fantastic answer by DMGregory here where he explains how to calculate and generate the vertices of an UV Sphere: OpenGL calculate UV sphere vertices

Based on his code, how can we change the "altitude" of each individual vertex?

To create something like this:

# Answer
As DMGregory said, I just had to vary the `radius` variable.

```
// You simply have to multiply radius by any kind of random value
// I'm using perlin noise in this example
positions[v] = vec3(
                  c * cos(theta),
                  sin(phi),
                  c * sin(theta)
               ) * radius * noiseValue(latitude, longitude)

```
> 1 votes

---
Tags: 3d, vertex, sphere
---


# Question
Title: How to write from shader to a texture to a PNG in Unity?
I want to write the information from my shader into a texture and save it in a png.

I found this:

http://forum-old.unity3d.com/threads/save-texture-generated-by-a-shader.326561/

and this

```
System.IO.File.WriteAllBytes(Application.dataPath + "/"+"picture5886.png", texture2.EncodeToPNG());    //app path n1!

```

But currently it seems to be unsolved.

Lets say I do `Graphics.Blit(src,temp,mat)` into a "tempTexture". I would have the temp texture then somewhere in my world, right?. How can I save that into a png?

# Answer
> 8 votes
First you need to get your shader's output into a Texture2D, so create one of the appropriate size. You'll commonly want ARGB32 format and no mipmaps:

```
Texture2D outputTex = new Texture2D(width, height, TextureFormat.ARGB32, false)

```

If the content you want to save has already been rendered by a camera in the scene, you can skip ahead (although in this case Unity's screenshot features may be a shorter route to your goal if you don't need anything fancy)

If you want to use an off-screen buffer instead, we'll need to create a RenderTexture to write it into.

```
RenderTexture buffer = new RenderTexture(
                               width,
                               height,
                               0,                            // No depth/stencil buffer
                               RenderTextureFormat.ARGB32,   // Standard colour format
                               RenderTextureReadWrite.Linear // No sRGB conversions
                           );

```

(Assuming you don't need a depth/stencil buffer and don't want to work in sRGB - otherwise, use the parameters that are right for your use case)

Now we bind our RenderTexture and material/shader pass, and run our shader across every pixel.

```
Graphics.Blit(sourceTexture, buffer, material, passIndex);

```

If your shader doesn't require texture input, you might need to supply a dummy texture for `sourceTexture` \- I haven't tested how it handles null there. ;)

Now we need to copy the data out of the current render target (whether it was the buffer we created above, or one used internally by a scene camera) and into our `outputTex`:

```
RenderTexture.active = buffer;           // If not using a scene camera
outputTex.ReadPixels(
          new Rect(0, 0, width, height), // Capture the whole texture
          0, 0,                          // Write starting at the top-left texel
          false                          // No mipmaps
);

```

Now you can use `outputTex.EncodeToPNG()` and write the results to a file as described in the question. You should use persistentDataPath rather than dataPath if this is something you're doing at runtime though - dataPath is not guaranteed to be a writeable location in a release build.

# Answer
> 1 votes
copy this：

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveShaderTexture : MonoBehaviour
{
    public int TextureLength =1024;

    public Texture2D texture;
    public void Save()
    {
        RenderTexture buffer = new RenderTexture(
                               TextureLength,
                               TextureLength,
                               0,                            // No depth/stencil buffer
                               RenderTextureFormat.ARGB32,   // Standard colour format
 RenderTexture buffer = new RenderTexture(
                               TextureLength,
                               TextureLength,
                               0,                            // No depth/stencil buffer
                               RenderTextureFormat.ARGB32,   // Standard colour format
                               RenderTextureReadWrite.sRGB // No sRGB conversions
                           );

        texture = new Texture2D(TextureLength,TextureLength,TextureFormat.ARGB32,true);

        MeshRenderer render = GetComponent<MeshRenderer>();
        //texture = render.sharedMaterial.GetTexture("_MainTex") as Texture2D;
        Material material = render.sharedMaterial;

        Graphics.Blit(null, buffer, material);
        RenderTexture.active = buffer;           // If not using a scene camera

        texture.ReadPixels(
          new Rect(0, 0, TextureLength, TextureLength), // Capture the whole texture
          0, 0,                          // Write starting at the top-left texel
          false);                          // No mipmaps

        System.IO.File.WriteAllBytes(Application.dataPath + "/"+"SkinLut.png", texture.EncodeToPNG());
        // texture.Save();

    }

    // Start is called before the first frame update
    void Start()
    {
        // Save();
    }

    // Update is called once per frame
    void Update()
    {
        // Save();
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Save();
        }
    }
}

```

---
Tags: unity, shaders, png
---


# Question
Title: Why don't we assign a class for each gameobject type in unity?
I used to create games from scratch with C++. There, people would create a "class Bullet", and add functionality to that class so that we can instantiate objects of class Bullet at runtime.

However, in Unity (which I'm new to), we need to create a Bullet GameObject in the editor, and then assign "class BulletBehaviourA : MonoBehaviour" to the Bullet GameObject. I don't really grasp this logic. Why don't we have a class for the Bullet in Unity?

# Answer
> 2 votes
Unity follows a principle called Composition over Inheritance.

When you have multiple entities in the game which have some behaviours in common and other behaviours which are unique to them, then there are three possible options:

* One stand-alone class for each entity type. But if you have multiple entity types in your game which all move `n` pixels forward per tick, you have to write that movement code in every single one. So you will end up with lots and lots of duplicate code. This can become a lot of work to write and really difficult to maintain.
* Inheritance. Extract common behavior into a common base-class and let every class that share this behavior inherit from it. So in this case you would create an abstract base-class `Mover` and every class which is supposed to share that behavior inherits from it. But if you use inheritance a lot, then you can encounter lots of design problems. For example, there is no good solution for multiple inheritance if multiple base-classes have a method with the same name. You can also end up with really confusing and unintuitive inheritance chains. This post-mortem of Starcraft 1 includes a paragraph "Game engine architecture" which shows just what a mess you can end up with if you follow the inheritance principle without taking the time to constantly review and refactor your class hierarchy. They ended up with an inheritance chain `CUnit < CDoodad < CFlingy < CThingy` with each of these things being something that could be instantiated and appear as an entity in the game world. What is the difference between a "Doodad", a "Flingy" and a "Thingy" you ask? Well, *someone* at *some* point certainly had a pretty solid idea of the distinction. Perhaps. Or not. If they had, they no longer remember.
* Composition. Each entity is a collection of components. Each component is a class which implements one feature of the entity. You can add any component to any entity, so you can mix and match them at will. Unity also follows this principle. Note that the `MonoBehaviour`s you create are not the only component on a game object. It always has at least a `Transform` and often a `Collider`, `Rigidbody`, `MeshRenderer`, `MeshFilter` and many more. These all implement features of your Bullet entity which your `BulletBehaviourA` class doesn't need to care about (unless it explicitly interacts with these components). By the way, having a component `BulletBehaviour` is often not the recommended solution in Unity. Usually you would break down all the things a bullet does into reusable components you can also use on other objects. In case of a Bullet, that could be

+ a `MoveForward` component, which you could reuse for anything that moves forward with a constant velocity.
    + a `DamageOnImpact` component, which you can put on anything which is supposed to remove hit points from any object it comes into contact with and has a `HitPoints` component.
    + a `DestroyOnImpact` component, which you can put on anything which is supposed to disapper after it comes into contact with something.

If you add all three components to a gameObject, then you have a complete bullet. And what if you want to test how your game would play if bullets also had hit points? Easy. You just add the `HitPoints` component to the Bullet prefab and suddenly all bullets have hit points. Or you want a bullet which doesn't do damage but stuns enemies? Replace the `DamageOnImpact` with `StunOnImpact` for that one bullet. Or a bullet which seeks targets? Replace `MoveForward` with `MoveTowardsClosestEnemy`. Bullet that explodes? Bullet that shoots smaller bullets? All very easy and non-destructive experiments you can do in a composition-over-inheritance architecture.

---

Which one of these solutions is the superior one? That's a matter of personal opinion. But Unity has chosen the third option of componsition over inheritance.

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


# Question
Title: Phaser 3 - How to trigger an event every 1 second?
I have just started learning Phaser 3 and making a simple idle game, where you would gain x resources per second. What is the best/recommended way to do something like this?

The two main ways I have found so far are:

delayedCall - `this.time.delayedCall(1000, onEvent, null, this);`

addEvent - `this.time.addEvent({ delay: 1000, callback: onEvent, callbackScope: this });`

But I read that Phaser update/rendering is in lockstep and runs at 60fps. So if the game were to drop in FPS, then other things like movement, physics etc. would slow down, but would the timers still fire every second? ie you could end up gaining more resources then you should have as the game is running.

Would it not be better to do a `modulus 60` frame count, and invoke any per second logic in that manner?

# Answer
> 3 votes
In your scene's update method you receive both the current timestamp, and the delta since the last update call (see https://photonstorm.github.io/phaser3-docs/Phaser.Scene.html#update\__anchor)

You could use the delta to keep track of the amount of time that has actually passed between frames. As soon as the total exceeds 1 second, subtract a second from the total and add the resources.

Even if a single update takes multiple seconds due to the user's CPU being very busy, switching tabs, or other worst case scenarios, you could still allocate the correct amount of resources as your timer will be say 2304 ms and you can run your resource update function multiple times, subtracting a second from the timer for each call.

```
this.resources = 0;
this.timer = 0;

update(time, delta) {
    this.timer += delta;
    while (this.timer > 1000) {
        this.resources += 1;
        this.timer -= 1000;
    }

    // Rest of your update loop.
}

```

---
Tags: javascript, timer, phaser
---


# Question
Title: 2D Tile based game Texture Atlas combining
I am new to OpenGL and game dev, I have been to courses and trying to learing everything about this. My task is to implement a Texture Atlas in a 2D tile based game (very similar to Tibia) using OpenGL.

Now the game have the sprite sheet loaded into memory and on each tile the program generates an image, load to a texture, bind and make a draw call. You can imagine how ineficcient it is. So what I have to do is to load this sprite sheet as a Texture Atlas and get the advantage that it has.

The problem is that in the first step while generating an image, the program makes some combinations on the sprites. For example, the character has an outfit and player changes its colors (boots, pants, t-shirt, hair) to do this there is a sprite for the base outfit, and a sprite for each element of the outfit, so the program apply a mask on color for each element and combine this five sprites into an image, then make the process that I mentioned above. This is an example that happens with outfit, but it happens to other things too, so this is not a special case with outfit only.

My question is: is there any way to make this combinations using OpenGL elements? Combining this multiple textures in my Texture Atlas into one draft and do it in a single draw call?

# Answer
> 1 votes
I personally would simply not include stuff like your character sprite into your texture atlas. There is no need to actually go so far and combine you whole game art into a single atlas. If you look at what the big 3D Engines do, they also have unique textures(even multiple ones) for each Mesh and are still able to render quite a significant amount of them. And they need to render a whole 3D-Model instead of a single rectangle for a sprite.

What shreds your performance is having a seperate texture for each tile. Depending on your tilesize that number can get actually get pretty insane. For a simple 100x100 map you would already end up with 10.000 unique draw calls.

On the game i am currently working on we have one texture atlas that contains every possible tile. We then create our vertices with the corresponding texture coordinates based on the output of our procedural map generator and store them into a single vertex buffer. That way we are able to render the entire tilemap with a single texture bind and draw call.

The actual actors like your player character or the enemies each have their own texture and are then rendered on top of the tilemap afterwards. For everything that appears more than once on the screen (for example a background tree) we use instanced drawing.

This basicly boils down to one draw + texture bind call for the map and one for each unique game object in your scene. Unless you need to have a gigantic amount of different objects in your scene that are not part of the tilemap your performance will fine. A somewhat modern GPU should be easily able to handle at least a few hundred drawcalls before you start running into problems.

---
Tags: opengl, 2d, textures, tilemap
---


# Question
Title: Unity UI's Image component renders without anti-aliasing?
I tried the sprite's import settings with **point filtering**, with **billinear filtering**, I also tried changing my canvas' UI Scale mode to **Screen Space - Camera**, but nothing seems to fix it.

I also tried scaling it up and down, but it rendered with these edges all the time.

How could I smoothen it? Thanks in advance.

# Answer
> 3 votes
As DMGregory pointed it out, in the **asset's import settings** I have to

* enable **Generate Mip Maps**,
* and have a **Filter Mode** at least **Bilinear**.

The result with **Mip Maps and Bilinear** filtering:

With **Mip Maps and Point** filtering:

With **only Point** filtering:

And with **only Bilinear** filtering:

---
Tags: unity, gui, antialiasing
---


# Question
Title: Change item rotation axis in inventory item visualization
I'm learning unity and i'm trying now make an inventory, i made a simple interface, and now i'm trying to make a item visualization. I look for some codes from web and i found this one:

```
using UnityEngine;

public class TurnObject : MonoBehaviour
{
    protected Vector3 posLastFame;
    public Camera UICam;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0)) {
            posLastFame = Input.mousePosition;
        }

        if (Input.GetMouseButton(0)) {
            var delta = Input.mousePosition - posLastFame;
            posLastFame = Input.mousePosition;

            var axis = Quaternion.AngleAxis(-90f, Vector3.forward) * delta;
            transform.rotation = Quaternion.AngleAxis(delta.magnitude * 0.1f, axis) * transform.rotation;
        }
    }
}

```

I know some code, but I'm not good with geometrics. In this code when I move my mouse horizontal way, my object turn in the Y axis. And that's good. But when I move my mouse vertical the object move in the X axis instead of Z axis.

Is there a way in this code for change this? I really have difficulty to understanding geometrics in Unity.

# Answer
> 1 votes
This line:

```
var axis = Quaternion.AngleAxis(-90f, Vector3.forward) * delta;

```

Takes your mouse delta X & Y, and maps them to the world axes -Y and +X, respectively.

To change the mapping to use the Z axis instead of X, just use a different Quaternion, say...

```
var axis = Quaternion.LookRotation(Vector3.left, Vector3.forward) * delta;

```

This takes your X & Y to -Y and +Z respectively.

Just beware of creeping roll when you compound these rotations over many frames. For more intuitive controls, you might want to track yaw & pitch angle variables instead.

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


# Question
Title: GameObject.Find() finds objects in the old scene
I'm trying to create a simple scene transition. On entering a collider, there is a black canvas that's slowly faded in over the duration of 3 seconds. Then, a new scene is loaded, and the scene slowly fades from black to invisible. Now, I've almost finished it. However, I'm running into a small problem I cannot seem to fix.

The animation consists out of two text elements and one image. The hierarchy looks like this:

`SceneLoader` is an empty object, `SceneFader` is a canvas. `Image` is a black image stretched across the screen, and `RegionName` and `RegionSubtext` are two text elements that are filled as soon as the transition begins.

The code I'm using to load the scene is this:

```
private IEnumerator _loadSceneWithTransition(string sceneToLoad, Vector3 spawnCoordinates, string regionName, string regionSubtext) {
    this.screenFade.SetTrigger(SceneLoader.AnimatorTrigger);

    GameObject.Find("SceneLoader/SceneFader/Image/RegionName").GetComponent<Text>().text = regionName;
    GameObject.Find("SceneLoader/SceneFader/Image/RegionSubtext").GetComponent<Text>().text = regionSubtext;

    yield return new WaitForSeconds(4f);

    SceneManager.LoadScene(sceneToLoad);

    GameObject.Find("SceneLoader/SceneFader/Image/RegionName").GetComponent<Text>().text = regionName;
    GameObject.Find("SceneLoader/SceneFader/Image/RegionSubtext").GetComponent<Text>().text = regionSubtext;

    GameObject.Find("Player").GetComponent<PlayerMovementController>().spawnCharacterToLocation(spawnCoordinates);
}

```

Now, this doesn't work as I'd expect it to. The first part runs perfectly fine: The animation is started, the text is displayed and the scene changes. However, that's the part where everything breaks. As soon as the scene loads, there is no text. Also, the player position is not set to where it should be.

I really do not know why, the only reason I could think of was that the script was called in the first scene, and therefore, the `GameObject.Find()` calls return the elements in that scene, not in the currently used one (actually, I'm fairly sure of that because `GetInstanceID()` returns the same for both calls). Now, the problem at this part is that I do not know how to make that work properly. One idea I had was to do try and fetch a new instance of the script with something like: `GameObject.Find("SceneLoader").GetComponent<BaseSceneLoader>()` and work with that, but then I remembered I still need `GameObject.Find()` for this, which would probably yield the result of the old scene, so it's not helping at all. On top of that, I'm not even sure if that is the actual problem.

I'm kinda out of ideas here. I also do not know what's the best practice in that situation, and I couldn't find anything meaningful on DDG either.

Lastly, I've created a small video clip showing off the problem. I hope this helps in identifying the issue.

https://i.stack.imgur.com/eds9b.jpg

# Answer
The reason this happens is due to a few factors:

* Scene loads in Unity are really just a shorthand for "destroy all the objects in the old scene I'm unloading, and instantiate all the objects in the new scene I'm loading"
* Destroying an object in Unity doesn't delete it instantaneously or put it into an invalid state (that could make systems blow up if they're still trying to use it this frame), instead it just marks the object to-be-destroyed, then actually removes it at the end of the frame to make a clean break.
* Unity callback methods and coroutines without a yield in-between will run all the way to completion in the frame they're called, even if there's a major/time-consuming operation in the middle of them (that will just delay the frame rendering until after the method finishes its work)
* `Find()` methods search through the open scenes in order, and return the first match they find.

Bringing that all together: when you call `SceneManager.LoadScene()`, you mark all objects in the current scene to be destroyed, then instantiate all the items for the new scene. Immediately after that, without waiting a frame, you ask `GameObject.Find()` to give you the first object it finds with a particular name - *which is still the object from the previous scene*, because we haven't reached the end of the frame yet when all those marked objects *actually* get removed, and all the new objects have spawned *after them* in the hierarchy.

A quick and dirty fix you can try is to just wait a frame between loading the scene and wiring up your new references. Then the old scene's objects have actually been destroyed, and won't pollute your `Find()` search. That can be accomplished with a simple `yield` statement (assuming this script itself survives across the scene load - it's not clear to me which object it's sitting on), something like this:

```
// ...

yield return new WaitForSeconds(4f);

SceneManager.LoadScene(sceneToLoad);

// Wait one frame for the junk from the old scene to be cleared away.
yield return null;

// From here on in, only the new scene is present!
GameObject.Find("SceneLoader/SceneFader/Image/RegionName").GetComponent<Text>().text = regionName;
GameObject.Find("SceneLoader/SceneFader/Image/RegionSubtext").GetComponent<Text>().text = regionSubtext;

GameObject.Find("Player").GetComponent<PlayerMovementController>().spawnCharacterToLocation(spawnCoordinates);

```

But this is pretty brittle.

A better solution is to not destroy and recreate things when you could just keep them around!

For example, we can set aside a separate scene for loading. We'll put our scene loader script and its fade-in/out UI elements there. The script can hold a direct reference to the UI elements it needs, that you wire up ahead of time in the Inspector, so it doesn't need to search for them at runtime. Something like this:

```
public class SceneLoader : MonoBehaviour {

    // Quick & dirty singleton pattern, to make it easy for other scripts to find this one.
    public static SceneLoader instance { get; private set; }

    void Awake() {
        if (instance != null && instance != this) {
            Debug.LogError("You have two scene loaders present when there should be only one!");
        }
        instance = this;
    }

    // Inspector fields - way better than searching!
    public Text regionNameField;
    public Text regionSubtextField;

    public Animator screenFade;
    public string animatorTrigger;

    // Keep track of the last scene we loaded, so we know which one to unload later.
    Scene _currentScene;

    public static void LoadScene(string sceneToLoad, Vector3 spawnCoordinates,
                                 string regionName, string regionSubtext) {
        Scene scene = SceneManager.GetSceneByName(sceneToLoad);
        instance.StartCoroutine(instance.LoadScene(scene, spawnCoordinates,
                                                   regionName, regionSubtext));
    }

    IEnumerator LoadScene(Scene nextScene, Vector3 spawnCoordinates,
                          string regionName, string regionSubtext) {
        screenFade.SetTrigger(animatorTrigger);

        yield return new WaitForSeconds(4f);

        if(_currentScene != null)
            SceneManager.UnloadSceneAsync(_currentScene);

        yield return null;

        SceneManager.Load(nextScene, LoadSceneMode.Additive);
        _currentScene = nextScene;

        // No searching! Since we always keep the same ones, we can just use our cached references.
        regionNameField.text = regionName;
        regionSubtextField.name = regionSubtext;

        // One little search, but at least it's not by name. ;)
        // Or, as an alternative, PlayerMovementController's Awake/Start
        // can ask for SceneLoader.instance.GetSpawnCoordinates();
        FindObjectOfType<PlayerMovementController>().SpawnCharacterToLocation(spawnCoordinates);
    }
}

```

Notice that by using additive scene loading, we don't automatically remove all the current loaded scenes. That gives us the power to pick and choose what we want to unload when. Here, we unload `_currentScene`, but crucially, not the loader scene that this script and all its UI elements live in. That helps with efficiency - we're not destroying and recreating - Reduce Reuse Recycle! And it also keeps our Inspector references stable, so we don't have to scramble to find our new dependencies in the new scene.
> 2 votes

---
Tags: unity, scene
---


# Question
Title: What is the purpose of the beginning of HL1, from the perspective of game design?
At the beginning of Half Life 1, player is locked into watching an introductory film that can't be skipped and doesn't teach anything about game mechanics. Player can only move their camera around. A similar technique was applied in Deus Ex 4. Given that it's irritating not to be able to skip it on subsequent gameplays, what is the purpose of those?

# Answer
> 3 votes
First of all, remember that Half Life 1 was released back in 1998. It did a lot of things nobody ever tried before in the first person shooter genre, both in technology and narrative.

Yes, I know it's hard to believe if you look at HL1 from a 2020 perspective. But back then the graphics *were* a revolution. The standard back then was Quake (one).

But perhaps the most innovative part was to tell the story using ingame graphics and mechanics. Most games from that time broke the medium when they wanted to tell their story. They stopped the game and played a video, animated sequence or text. Telling the story while the player was in full control of their character was something entirely new. I remember reading various reviews back then where the first time they played the game they did not even realize at first that the train ride was *not* a pre-rendered video cutscene but in fact rendered in real-time.

So this train ride fulfilled various purposes

* Introducing the player to the new graphical capabilities.
* Introducing the player to the scenario. It told the player that they were in an underground science complex somewhere in the desert, all the various activities that went on it it and just how huge that complex was.
* But most importantly, getting the player accustomed to this new style of telling the story . It immediately told the player:

> "There will be phases like this in the game where we will just show you things. This is not Quake. You are not supposed to shoot anything that moves. Observe, think and then act".

---
Tags: game-design
---