#archived-code-advanced

1 messages · Page 83 of 1

untold moth
#

Honestly, it's not really an advanced level problem.🤔

boreal grotto
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(InputHandler))]
public class TopDownCharacterMover : MonoBehaviour
{
    private InputHandler _input;

    [SerializeField]
    private bool RotateTowardMouse;

    [SerializeField]
    private float MovementSpeed;
    [SerializeField]
    private float RotationSpeed;

    [SerializeField]
    private float LookSpeed = 180f;

    [SerializeField]
    private Camera Camera;

    private void Awake()
    {
        _input = GetComponent<InputHandler>();
    }

    // Update is called once per frame
    void Update()
    {
        
        var targetVector = new Vector3(_input.InputVector.x, 0, _input.InputVector.y);
        var movementVector = MoveTowardTarget(targetVector);


        if (Input.GetKey(KeyCode.Mouse1))
        {
            RotateTowardMouse = true;
        }
        else
        {
            RotateTowardMouse = false;
        }

        
        if (!RotateTowardMouse)
        {
            RotateTowardMovementVector(movementVector);
        }
        else if (RotateTowardMouse)
        {
            RotateFromMouseVector();
        }

    }

    private void RotateFromMouseVector()
    {
        Ray ray = Camera.ScreenPointToRay(_input.MousePosition);

        if (Physics.Raycast(ray, out RaycastHit hitInfo, maxDistance: 300f))
        {
            var mouseTarget = hitInfo.point;
            mouseTarget.y = transform.position.y;
            //transform.LookAt(mouseTarget); //Using this works great, but I am trying to add a rotation speed/lerp so I tried Quaternion.RotateTowards below

            //This rotates over time as expected, but as soon as I use horizontal/vertical WASD input it throws everything off...
            var rot = Quaternion.LookRotation(transform.position + mouseTarget);
            //rotate towards mouse hitpoint over time
            transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, LookSpeed * Time.deltaTime);
        }
    }

    private Vector3 MoveTowardTarget(Vector3 targetVector)
    {
        var speed = MovementSpeed * Time.deltaTime;

        targetVector = Quaternion.Euler(0, Camera.gameObject.transform.rotation.eulerAngles.y, 0) * targetVector;
        var targetPosition = transform.position + targetVector * speed;
        transform.position = targetPosition;
        return targetVector;
    }

    private void RotateTowardMovementVector(Vector3 movementDirection)
    {
        if(movementDirection.magnitude == 0) { return; }
        var rotation = Quaternion.LookRotation(movementDirection);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, RotationSpeed);
    }
}

• I used transform.LookAt(mouseTarget); and this worked great, but I wanted to add a LookRotationSpeed.
• So I switched to using a Quaternion.RotateTowards method and it works... just as long as I dont press WASD to move.
• Once I press WASD the Quaternion.RotateTowards gets thrown off... and I can't figure out why.

While the bool RotateTowardMouse = false, I want the WASD to manage rotation. When it's true, I want the player to look at the mouse location. And I would like to be able to use WASD and MouseLookRotation at the same time, but when I let go of Mouse1 it switches back to WASD Rotation and vica versa.

Anybody notice what's causing the rotation to be off when pressing WASD?

boreal grotto
#

It took about an hour of back and forth with ChatGPT, it didn't solve it as simply as you would expect an AI to do it, but I finally resolved the issue. 🙂

boreal grotto
sly grove
#

it is not. If you are a beginner, stick to the beginner channel to get the best answers

fossil girder
stuck plinth
modest sinew
#

i have a theoretical question for my multi scene tools package. ive talked to people who say i should be using cancellation tokens for async loading. but unity doesnt support that by default. so my question is:

Is cancellation tokens even usefull in async loading? should i bother finding a workaround and implement it?

flint sage
#

Sure it's a good practice to cancel when e.g. the user cancels an operation or does an incompatible thing, but if the api you use doesn't support it then you don't have much of a choice

#

You can wait until that's done and then cancel

modest sinew
#

thing is, once an async loading operation is started with the SceneManager, it cant be cancelled. it must be loaded in or unloaded. if loaded then a loaded, but not enabled scene cant be removed without being enabled, and then unloaded (as far as i know). which is why im questioning if i should find a workaround. I know i can add cancellation tokens if i use UniTask, but i dont know if that enables me to remove half loaded scenes which is the main issue

#

if i have to wait until its done anyway then it kinda defeats the purpose of a cancellation token right?

flint sage
#

that's funny

#

Just don't bother lol

native beacon
#

Under what circumstances will a disabled monobehavior on a gameobject still run (without being enabled)?

lament salmon
#

Other code inside the MB will run normally if you call it

#

Also OnCollisionEnter runs on disabled MB

Collision events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.

native beacon
#

Ugh. So how DO you disable a script with OnCollisionEnter in it if you WANT to disable it?

#

Short of removing it?

stuck plinth
#

if (!enabled) return; in OnCollisionEnter?

native beacon
#

Ah.

#

Thanks 😄

limber snow
#

sorry if this is not the best channel to ask, i know how ot populate in my code a dropdown with values from some list, but how can ii save this dropdown in the editor to avoid filling this dropdown everytime?

regal lava
limber snow
#

I have a list inside an scriptable

#

And when I press play if my drop-down option are empty then it populates with the option’s inside the scriptable

#

But is not better to save after this the options inside the drop-down to avoid doing this every time I press play ? How can I do it ?

regal lava
#

So the list should always contain the information of your scriptable object?

#

and that you've got it populating from Start() or some assignment method?

#

If that's the case, sounds like you shouldn't expose the list on the editor.

limber snow
#

Why ?

sly grove
limber snow
#

Anyway, let me explain better sorry for my English, I have an empty drop-down with 0 options, then I press play and is populated or filled with the content of one list saved in one scriptable gameobject

#

How can I avoid do that in every play and save the content of the scriptable in the drop-down in unity editor ?

sly grove
#

oops sorry @regal lava I replied to the wrong person

echo kestrel
undone coral
novel plinth
#

Task.Yield is not the same as 1 frame in Unity, you'd need a custom wrapper on top of CustomYieldInstruction to be able to properly awaiting frames in Unity. Async/await in c# does not respect Unity's frame timing/gameloop at all thus they made the new Awaitable api.

vale zenith
#

Hi, I'm caching WaitForSeconds to avoid GC allocation, but thing is, I don't know the time delays in advance. They will be determined by gameplay.

Might be a matter of syntax, but I can't figure out how to set the time delay in my coroutines when referencing a cached WaitForSeconds.

Anyone know how to do this?
yield return myWaitForSeconds(5) - for example - throws an error "Method name expected"

sly grove
#

not without reflection

#

we literally had this discussion in here earlier today

vale zenith
vale zenith
#

dang, i actually started with a timer but tried the waitforseconds method thinking it'd be easier. 20-30 minutes wasted!

sly grove
#

well it's easier but not if you care about garbage collection 😉

vale zenith
#

right exactly

#

I also have the 'infinite coroutine' thing going on like the other poster, so I do care

#

which i realize may be a stupid thing to do in general, but i'm just trying to get my prototype done

vale zenith
#

If you simply wanna "get" a reference each frame, is there a significant performance diff between looking it up in a Dictionary vs. an Array?

My lookup "keys" are ints that increment linearly throughout gameplay. I just prefer dictionaries for convenience. I heard dictionaries are quite fast, but not sure in this case..

sly grove
#

Whether that difference is significant depends on how many times you do it, your hardware, the hashcode and equals implementation of the key, the occurrence of hash collisions, etc.

craggy bronze
sly grove
craggy bronze
#

Are you saying you can't set this by script?

wooden egret
#

I wanted to know 2 things. I just can't seem to find much info online about this stuff and I don't know how it's done. So, I assume it's a more advanced question but not sure.

#

How do I edit multiple terrains in c# in Unity, without making a seam? Like, basically how the terrains behave through the editor when you use a brush. If you edit them it treats them as as 1.

#

I'm working on a City generator. That modifies the terrain so that buildings and roads can sit on the terrain without making it totally flat. I can edit them already and I can put them together but when I put them together sometimes it leaves a little hump.

#

Currently I depend on an Asset called GeNa Pro to do it and I can do it well with that. But I want to learn how on my own. Also, I know how to make the roads as single segments but I don't know how to put them together so it looks good. Basically it's just a bunch of straight lines for the roads and they are disconnected segments.

untold moth
# novel plinth *Task.Yield* is not the same as 1 frame in Unity, you'd need a custom wrapper on...

It does though. I don't know if they changed anything recently when they introduced the CustomYieldInstruction, but for a long time Task.Yield was the way to do async(on the main thread) in unity.

If you look at the task yield docs in C# docs, it yields to the synchronization context. And unity overrides it:

Unity overwrites the default SynchronizationContext with a custom UnitySynchronizationContext and runs all the tasks on the main thread in both Edit and Play modes. To utilize async tasks, you must manually create and handle your own threads with a TaskFactory, as well as use the default SynchronizationContext instead of the Unity version. To listen for enter and exit play mode events to stop the tasks manually, use EditorApplication.playModeStateChanged. However, if you take this approach, most of the Unity scripting APIs are not available to use because you are not using the UnitySynchronizationContext.

https://docs.unity3d.com/2019.4/Documentation/Manual/overview-of-dot-net-in-unity.html

I couldn't find anywhere explicitly saying that the unity synchronization context waits for the next frame and the source code seems to be interlinked with the C++ side, so it's not quite clear.
But I've been using Task.Yield in the same way as coroutines yield return for a very long time now and never noticed any difference.

brisk pasture
#

so would assume Task.yield is the same deal

#

though i find i only use tasks when waiting on a long operation and stick to coroutines when i want to do stuff over time or frames

untold moth
#

Yeah, it's mainly a matter of preference I guess.

brisk pasture
#

yeah we got pathfinding on its own threadpool and and a bunch of network io stuff like rest api calls that we await

#

and that is about it

nova bolt
#
private void OnAnimatorMove()
        {
            if (player.applyRootMotion)
            {
                Vector3 velocity = player.animator.deltaPosition;
                player.characterController.Move(velocity);
                player.transform.rotation *= player.animator.deltaRotation;
            }
        }

Anyone have a clue why this might be keeping my root motion animation in place

#

The bool does indeed return true correctly

untold moth
nova bolt
nova bolt
#

Nvm i figured it out

#

i did player.applyRootMotion instead of player.animator.applyRootMotion

earnest hamlet
#

Hello, I'm currently creating custom Timeline track. How do I rename this.... string text using code? I don't know what is that thing called.
I just realized I accidentally posted it in code-advanced.

icy smelt
#

Guys. I'm trying to convert an existing C void* pointer to a NativeArray using NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray, but I'm getting an exception from Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckReadAndThrow even when using an Invalid allocator. How am I supposed to do that?

tiny pewter
icy smelt
#

Can't we disable the AtomicSafetyHandle for a specific NativeArray or even disable it entirely?

tiny pewter
#

i think no (i use unsafe list so doesnt know much on native collections) since this is required for job system to lock the collections

flat nexus
#

Anyone know if there's an easy way to sign in through existing microsoft account details in unity?

In other words you just enter your email and password and it checks if the details match an account

sly grove
lament briar
#

Hi! I'm creating a procedural 3d world. I've alreay done most of the things and I'm looking for improving my biome systems. I currently have both perlin noise for plains and forests (and the sea), and I'm implementing voronoi noise to add more biomes. The world is infinitely procedural so voronoi is made with a grid, in which the point inside the box depends on the grid's coordinates (via a seed in the random number generator). I'm looking for ways to create: 1) biome size: how many close points in the voronoi grid are the same biome. The points should be spread in an "organic" way, not just squares inside the grid. 2) Frequency of the biomes. And blocking biomes of the same type to form close so they can't "merge" into a single huge one.

I think I'm looking at something similar to ore generation in terraira or in any 2d grid. Anyone has any tips on how to do that?

#

currently the map looks a bit like this (it's a texture map that uses the same generator engine as the in-game world). The world is created with perlin and the gray areas (rocky biome) are random points in the grid, with borders squared with the voronoi's technique (I still need to make borders "organic")

#

I was thinking about using perlin noise for voronoi generation too, but this would be a problem because ores can have an average size but can still be only one voronoi's box (minimum is 1) and two zones can still merge together creatinga big one. Also, I'd have to do perlin noise for every biome, using one above another, potentially overwriting previous biomes

#

I'd like to have something that can ideally have a minimum quantity of zones packed together (a minimum biome size) and a maximum one, without overlapping zones together with other biomes

flat nexus
vernal furnace
#

All my analytics events go to the default "production" environment and refuse to send gameStart or custom events to my "betatesting" environment.

shrewd fable
#

Hey, so i made a a* pathfinding algoritm using heap data structure, on simple paths it works well, but on complex ones, i have extra nodes, any hints on what i should change?

tiny pewter
#

look like heuristic function is incorrect

#

and the backtrack function

shrewd fable
#

I found out that when getting the neighbors again they didn't had the prev cost and that was one cause, and that fixed it, but some points are wierd. In this image is the one from the older message

#

but i have no idea how to handle this point

tiny pewter
#

you dont need some special logic to handle the vertex, just explore until reach the target

shrewd fable
#

yes, but the path shouldn't be correct, is not the shortest blobthinkingdown

tiny pewter
#

wrong heuristic

#

it looks like "avoiding" some vertex when exploring, have you reset all setted vertex in previous search?

#

I suggest you dont draw the vertex, instead draw the edge (though successful search should not be ambiguous)

dusty wigeon
shrewd fable
#

this is how i do it:

        const newMoveCost =
          currentNode.gCost + this.getDistance(currentNode, neighbor);

        if (newMoveCost < neighbor.gCost || !openSet.contains(neighbor)) {
          neighbor.gCost = newMoveCost;
          neighbor.hCost = this.getDistance(neighbor, targetNode);
          neighbor.parent = currentNode;

          if (!openSet.contains(neighbor)) {
            openSet.add(neighbor);
          } else {
            openSet.updateItem(neighbor);
          }
        }
getDistance(first: Node, second: Node) {
    const disX = Math.abs(first.x - second.x);
    const disY = Math.abs(first.y - second.y);

    if (disX > disY) {
      return 14 * disY + 10 * (disX - disY);
    }

    return 14 * disX + 10 * (disY - disX);
  }
tiny pewter
#

Typescript?

#

Btw it use integer for faster computation but i wont suggest it, it may loss precision then produces wrong result

dusty wigeon
#

What is the getDistance... ?

shrewd fable
#

Yeah, i know is not Unity 😅 , the positions are not floats, as i use grid position and than i have a diff method which gets the real position based on that

#

i sent it as the second snippet

dusty wigeon
#

I mean, what are you doing there.

#

why 14 and 10

tiny pewter
#

(No return type, bad)

#

dx+dy-1.41* min dx,dy

#

Or root 2* min dx dy

dusty wigeon
#

Normaly, you use Manathan distance for grid base a*.

shrewd fable
#

to get the distance from the current selected node towards the target

#

i tried manthan, but i get way worse paths

dusty wigeon
#

Then, you have an issue somewhere else

tiny pewter
#

Yes since manthan distance not work if diagonal movement allowed

dusty wigeon
#

Then use the magnitude

#

At least, you will be sure that it is admissible

tiny pewter
#

Oh, the get distance should return the distance between neighbour and target

#

But it returns current to neighbour now

dusty wigeon
#

It does both...

#

lol

#

That is the issue isnt ?

tiny pewter
#

I misread (since my a star is slightly different from standard one) and i have to sleep now

#

The heuristic looks correct though this is not the heuristic i use

shrewd fable
#

For get distance

#

i switched to this method

#
private getChebyshevDistance(first: Node, second: Node) {
  const disX = Math.abs(first.x - second.x);
  const disY = Math.abs(first.y - second.y);

  return 10 * Math.max(disX, disY);
}
#

and the result seems better

#

the path is not that long for the wierd nodes

#

Only this i find it a bit wierd

#

maybe adding a moving penalty for zig zag moves?

sly grove
#

this seems definitively not Unity related

shrewd fable
#

Yes 😅 but i have no idea how to ask about this kind of stuff

neon wraith
#

Has anyone here done OAuth 2.0 in Unity with Azure? I have a .NET Core backend. How do I retrieve the token from the redirect URI to microsoft?

dusty wigeon
#

Also, you can simply debug your code. (Code Trace, Isolation, Simplification, etc.)

compact ingot
dusty wigeon
# neon wraith Has anyone here done OAuth 2.0 in Unity with Azure? I have a .NET Core backend. ...

The same way any other application would do I would guess. The last time I had to setup something similar, I did the authentication process with a server than use it as an intermediate. (server-server communication instead of client-server) The first step is to make it works with Postman.

There is extensive docs on the subject: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow (and yes, it is complex)

undone coral
#

this lets you POST a username and password to a URL. the response will be a token

undone coral
undone coral
#

can you show the snippet of the plugin side and the unity side?

#

a C# void* isn't the same thing as a C void*

#

even in unsafe

icy smelt
#

I just had to add the Editor collection checks instance:

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArrayWrapper.NativeArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
#

But I guess this could be considered a Unity bug, bc instead of simply alerting the user or giving a more specific erro,r when the NativeArray m_Safety value is null, it throws a NullReferenceException without much details

undone coral
#

you can use AtomicSafetyHandle.Create() instead, if you want a real handle

icy smelt
#

Why would I use a handle on a data allocated externally (on a native dll)?

undone coral
#

AtomicSafetyHandle.GetTempMemoryHandle() is for temp allocated

icy smelt
#

And it is a read-only data, in theory, I don't need it

undone coral
#

it would help to see the snippet

icy smelt
#
public static unsafe NativeArrayWrapper<T> ConvertExistingDataToNativeArray(
  IntPtr data,
  int length)
{
  NativeArrayWrapper<T> nativeArray = new NativeArrayWrapper<T>(NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(data.ToPointer(), length, Allocator.Invalid));
  NativeArrayUtils<T>.SetupNativeArray(nativeArray);
  return nativeArray;
}
undone coral
#

And it is a read-only data, in theory, I don't need it
it might be read only, but it might need to be moved

icy smelt
undone coral
#

also Allocator.None might be the better option

icy smelt
#

The idea of the Temp allocator is that it will be Disposed at the end of the frame

#

And I don't think it doesn't do anything when allocator is None or Invalid, but I'm just guessing...

undone coral
#

yes but you're not allocating anything

#

yeah

#

i don't really know either i am just following the docs

icy smelt
#

I guess Unity needs a method like ConvertExistingDataToReadOnlyNativeArray

undone coral
#

the only thing atomic safety handle does is ensure jobs are written against the data correctly

#

it doesn't enforce anything when those editor checks are disabled

#

so it's "just" a feature of "hpc#" aka the burstable jobs code

#

best to just make one correctly

#

no consequence to it

#

go ahead and make it and enforce your belief that it is read only, at least in editor

undone coral
#

like in C++?

#

or something like

int length = 5;
int* data = stackalloc int[length] { 1, 2, 3, 4, 5 };

which you can do in C#

#

almost everyone always wants to allocate in C#, then pass a marshalled pointer to C++

#

because allocating in C++ for use in a managed language is like buying all the rope in the rope store, then fastooning it around your house in various hoops, loops and what have yous, and then jumping on a floor made of trampolines

icy smelt
undone coral
#

anyway

#

i think you know what you're doing and you're just trying to make something work in unity

icy smelt
#

My struct arrays can become quite big, I don't think it would be safe to allocate them on C# stack anyway

undone coral
#

i would allocate an ordinary NativeArray (or Span) on C# side then pass it to the DLL

#

if possible

#

if you didn't write this library

#

don't sweat it

#

it's a video game

icy smelt
#

Yes. I'm experimentating with NativeArrays now, the native libraries might wait a bit

icy smelt
undone coral
icy smelt
undone coral
#

or are you trying to use pixar's subdiv library

#

lol

icy smelt
#

I've added FBX SDK support to it

undone coral
#

you'd think they'd have a C# binding for it already

icy smelt
#

But I'm trying to squeeze more memory with the current approach as well

#

They do, but I don't recommend using it, not bc I've made TriLib, but bc there is some overhead on converting FBX SDK data to DOM

undone coral
#

the more burst the better

icy smelt
#

So I've created a backend system for it that allows using external libraries like FBX SDK, Assimp, etc

undone coral
#

that's cool

#

have you looked at the alembic package and how it does things?

#

alembic is a much simpler format

icy smelt
#

Not yet

undone coral
#

but sometimes very high data rate, and it uses burst

icy smelt
#

Yes, things like data array processing can benefit from multi-threading

#

And another backend alternative I'm adding to it does uses multi-threading internally to parse such things

undone coral
#

i mention it because of all the mesh formats i've used, this is the only one where it does realtime playback correctly of stream-of-meshes

icy smelt
#

Interesting. I don't know much about the format, but maybe it is the most suitable to do such things

undone coral
icy smelt
#

Imported at runtime?

undone coral
#

yes

#

from streaming assets

icy smelt
#

Pretty fast

undone coral
#

yeah when you toggle between the outfits

icy smelt
#

Ah, so it is not runtime Alembric loading, rather a pre-processed Alembric file?

undone coral
#

no it's runtime alembic

#

not preprocessed

icy smelt
#

Oh, StreamingAssets, got it

#

Nice

undone coral
icy smelt
#

Pretty impressive for a WebGL app

undone coral
#

it's streamed not webgl

#

that's why it loaded instantly lol

icy smelt
#

And yes, formats like FBX are pretty tricky to insta-load at runtime

#

Not made for that purpose

undone coral
#

the virtual runway assets are 8GB

#

also you can't do HDRP in webgl. you can barely do shadows

icy smelt
#

Yep

undone coral
#

in this platform you can load into trilib at runtime, from a drag and drop. it would just be imported in a multithreaded, very powerful computer.

shrewd fable
#

@dusty wigeon i found the issue in my code, i had to clone the first item when removing the first from the heap 😂

neon wraith
# compact ingot Many have probably tried and decided to rather go for an extended walk and hope ...

That's unfortunate to hear. I think I may have found an existing solution, without having to use ROPC like @undone coral is suggesting. ROPC seems to be what AWS Cognito does though so maybe it's not too bad, but it's definitely less secure as stated in the doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc.

The solution I found seems to facilitate this flow (authorization code flow) @dusty wigeon: https://github.com/cdmvision/authentication-unity. I'm trying it out now, but haven't gotten it to work. Trying to figure out the deeplink portion.

Edit: Goddamn it, deeplinks don't work for standalone PC builds.

distant wedge
#

any idea about this error ? Unity Web request failed to load from cache. The cached AssetBundle will be cleared from the cache and re-downloaded. Retrying...

#

retrying is never be successfull. i take various errors

olive cipher
#

Fixed it for me last time

earnest heron
#

Hey guys,
I have a question about VContainer.

I have a Player gameObject that Instantiate a Character prefab which contains LifetimeScope.
Instantiated Character gameObject has CharacterController facade which Instantiate a few ScriptableObjects.
These ScriptableObjects have a Constructor method (Method Injection). One of the classes which should be injected is already registered by Character LifetimeScope.

The issue is, it can't find registration of that type. My first guess is, I should specify the LifetimeScope parent which is Character LifetimeScope for these ScriptableObjects but no idea how and even I don't know if it is a right guess.

hidden onyx
#

could someone help me remake the effect in stardew valley where a player walks thru crops they move.

or just break down how to do it.
I know how to code but got no idea whether to do it with animations, or a lerp

copper tiger
#

Bit if an advanced topic but how would you guys implement asset loading for mods?
I don't want the files to be in Assets/Ressources so have to come up with a different solution
One I came across might he assetBundles
What do you people here think and how would you tackle this?

dusty wigeon
# copper tiger Bit if an advanced topic but how would you guys implement asset loading for mods...

My advice would to NOT directly support in your game. Game can be modded without any support. Unity games are particularly easy to mod as they are realy popular. https://wiki.nexusmods.com/index.php/How_to_create_mod_for_unity_game

If you truly want to do that, and want to support user content without access to Unity you can use: https://docs.unity3d.com/Manual/StreamingAssets.html. Alternatively, you can use AssetBundle/Adressable but that would require the use of Unity.

copper tiger
#

I sctually think that using unity for asset creation would be a good idea. I just want them to be actually loadable eithout being in the asset directory
My current layout is this and it would be nice to keep it
BaseFolder:
-Game.exe
-Databases/
-Mods/
-... (All the build unity stuff)

#

Just reading the ressource of the given filepath is what I want

glass hill
#

Does anyone have a lot of experience with DataContractSerializer?

#

I've been making updates to the class I'm seralizing and deserializing, and I want to future proof it by allowing it to deserialize only parts of the class, if say, one element has been changed or is now deleted.

#

I'm getting some errors with existing account and I want to make sure that any updated I make to the account profile files in the future don't break or require me to delete and remake the profiles, since progression is linked to them.

#

I've been scouring the documentation but I haven't been able to find any concrete examples of partial deserializiation.

hidden onyx
#

why partial tho

#

dont think it is beneficiary

royal raft
#

i am trying to use the burst compiler with the jobs system and right now i am getting an error that it doesn't support multi dimensional arrays is there a simple fix for this Ex: Float[,,] this doesnt work

untold moth
#

Btw, you should probably be using native array anyway.

sly grove
#

Yes, use NativeArray

tiny pewter
#

I never tried use pointer of managed array in job, idk if it works

rugged radish
#

I'm pretty sure it does, but kills the performance
and you can't pass them to or from jobs, can only make allocations inside

untold moth
#

According to the docs, only statically allocated C# arrays are allowed, since they're allocated at compile time.

stoic otter
#

I want to track the total time of a player in my game.
what is the best variable type to track this?
i thought of a long?

verbal temple
#

I dont think you would need a long if you are just tracking seconds

#

int would be fine

flint sage
#

Time span..?

tiny pewter
#

uint is enough even if you measure in seconds (4*10^9/10^5=4*10^4 days)
but you may need long if you are measuring in millisecond

#

or other readable data type

sly grove
stoic otter
sly grove
#

double or long is fine

#

You could also serialize a TimeSpan if you want

neon wraith
#

Hi everyone, can someone give me comments on my tenant/app and auth setup for Azure?

I have a B2C tenant. I have a Unity frontend with an app registered in this tenant. This app has no scopes defined, and supports All users. I also have a Web API that will access resources from Azure on behalf of the user/Unity frontend. This app has the scope access_as_user defined, and only supports internal users (within the tenant).

  1. Server authenticates itself with Azure with some daemon authentication scheme. So the web app is now authorized to retrieve/post resources from/to azure.
  2. Unity proves to server that it is real by sending certificate/secret?
  3. User registers by clicking a link in Unity which will prompt them to register on a browser.
  4. User enters credentials in Unity which will be sent to my Web API. I know this is frowned upon but as I mentioned, extracting the token from an external browser to Unity is a pain in the ass. Anyways, the server will then request the token on behalf of Unity. Server passes token back to Unity.
  5. User is now logged in on Unity and use token for ever request thereafter.

Any comments/suggestions on this setup?

undone coral
#

Hi everyone, can someone give me

undone coral
glass hill
#

No more deserialization errors as far as I can see

fickle mango
#

These two function are inside the TileData struct, is one of them 'better' than the other one?

sly grove
regal lava
#

my guess is the first compares both if they are neighbors

#

and bottom uh

#

oh is the neightbour local to the tiledata

#

then it compares that to another tiledata

#

the static method is a general utility function

fickle mango
#

the top one would be called like:
TileData.IsNeighbour(someTileData, someOtherTileData);and the bottom one:
someTileData.IsNeighbour(someOtherTileData);The question is, is there an advantage to one of these over the other?

regal lava
#

it's just how you want to call it. Use the local data, or use both references

elfin tundra
#

are there any collider options that allow you to set a series of points (like edge collider) but update the collider without resetting every single point? i need to frequently redefine the collider but i'm only adding or removing one point at a time and it gets really slow to reset every single point.

sly grove
#

Are you reusing a list or array?

#

or creating new ones all the time?

elfin tundra
#

i have a set of the points stored in my class, and i add and remove points to it as necessary

#

how it works now, in order to ensure the correctness of the collider, every time i add or remove a point from the set i have to reset the edge collider points

#

and that mega lags

#

@sly grove

icy smelt
#

Guys, when calling the Mesh.SetIndexBufferData method using a List<int> as the data argument, Unity is crashing, and the only thing I can find in the log file is:

Assertion failed on expression: '(int)lastVertex < data.GetVertexCount()'

I'm making sure I'm not referencing vertices out of the vertex buffer data range, and it doesn't seem to be the cause.

sage radish
sage radish
icy smelt
#
Mesh.SetVertexBufferParams(VerticesDataCount, attributes);
var streamIndex = 0;
if (VerticesData.Stream1 != null)
{
    VerticesData.Stream1.SetVertexBufferData(Mesh, ref streamIndex);
}
if (VerticesData.Stream2 != null)
{
    VerticesData.Stream2.SetVertexBufferData(Mesh, ref streamIndex);
}
if (VerticesData.Stream3 != null)
{
    VerticesData.Stream3.SetVertexBufferData(Mesh, ref streamIndex);
}
Mesh.SetIndexBufferParams(IndexCount, IndexFormat.UInt32);
Mesh.subMeshCount = GeometriesData.Count;
var indexStart = 0;
var subMeshIndex = 0;
foreach (var geometry in GeometriesData.Values)
{
    if (geometry != null)
    {
        var descriptor = geometry.GetDescriptor(indexStart);
        geometry.VertexDataIndices.SetIndexBufferData(Mesh, 0, ref indexStart);
        Mesh.SetSubMesh(subMeshIndex++, descriptor);
        geometry.VertexDataIndices.TryToDispose<IIndicesList>();
        geometry.OriginalVertexIndices.TryToDispose<IndicesListWrapper>();
    }
}
#

SetIndexBufferData and SetVertexBufferData are located inside the lists generic methods, and they call Mesh.SetVertexBufferData and Mesh.SetIndexBufferData internally

sage radish
sly grove
elfin tundra
#

on average this happens very infrequently but when it happens, it happens many times in a few seconds

#

i tried using a list instead of a set so i wouldn't have to convert to a list, but that just moved the lag to a different part of the script that used the set as an optimization

edgy adder
#

i was asking about this in the other code channel but had no luck, I have a prefab with a script that has an array on it, when I try to change the size of the array using the inspector, the array disappears completely and I'm getting this wall of text pop up in the console. It’s a recent thing that started happening and it happened right after I tried to see if I could use nested arrays and put an array with [,] in the code, when that didn’t work I tried [][]. That didn’t work either so I went back to just []. Nothing sticks out to me as the cause for it to happen, can someone take a look to see if you can figure it out?

elfin tundra
#

@sly grove nevermind, i think i found an alternate solution, no more massive colliders lol

icy smelt
#

@sage radish strangely, SetTriangles works using the same input index list

old hollow
#

What algorithm would I have to use, or how would I place rooms and paths like this?

regal lava
#

Really it's just a statemachine with a bunch of conditions.

sly grove
#

Oh sorry missed the other part

old hollow
regal lava
#

Roguebasin probably has a lot of info for this stuff if you dig around

elfin tundra
regal lava
old hollow
#

Thank you!

austere jewel
steel snow
#

for the unity asset database how do you set the search filter to search by type and a name? i tried:
string filter = "t:TestScriptableObject " + name;

but it never finds anything

small latch
#

t:PieceConfig Battle with the .FindAssets gives me the 6 entries that the project view gives me. So it works fine on my end.

fast breach
#

*Script Error Loading* Theres a roller coaster script

flint sage
coral reef
#

in scene view edit we can scale UI Image on just one side, but when i looking at the method available its just size delta, and scale that one, will scale its on two side, i realize during test on scene view, the width AND the pos x are changed simultaneously, can anyone direct me how to code so i can scale just on one side??, either only left, right or only up etc...thanks

tiny pewter
#

offset max or offset min of rect tf

clever widget
#

I'm facing a very weird issue regarding Firebase Cloud Messaging and AppsFlyer SDKs in my multiplayer game. I initially had only FCM plugin and Firebase.Messaging.FirebaseMessaging.MessageReceived was fired whenever a player clicks on a push notification and the game is started. I used to get the payload data from the event's listener method.

Then I've integrated AppsFlyer SDK for analytics purposes. Then the update went live. Now I've decided to remove the AppsFlyer plugin. But after doing that, weirdly the event Firebase.Messaging.FirebaseMessaging.MessageReceived is not firing now. The push notification is showing up, but when I click it and open the game, I'm not able to get any payload data since the event is not fired. Did anyone face this issue before? Why is AppsFlyer changing something of FCM?

#

Btw this is happening in iOS

#

I've checked the Unity settings, Xcode settings, plist files but I can't see any changes between the versions (with AppsFlyer and w/o AppsFlyer)

#

If I just reimport AppsFlyer SDK into my Unity project (without integrating into the game in any way) and run it then FCM will also work properly.

cerulean wasp
#

I think I might have my answer to all my physics issues, and it super sucks. Basically, I need to write my own physics engine almost. Make everything static/kinematic, and then do things similar to the KCC package.

#

The plan is basically:

  1. Al kinematic/dynamic RBs are moved via a different class which tracks pos, rotation, vel… It’s like an RB api on top. Then everything is kinematic. Call this class physicsMover.
  2. To move, AddForce/moveposition etc requests are passed to the PhysicsMover : Monobehaviour on the object.
  3. PhysicsMovers all list themselves to a singleton KinematicCharacterSystem, with a given order.
  4. Kinematic character system, right before physics simulation step, collects all the info from all the physics movers, and does its own physics calculation. It casts kinematic RBs, while pushing simulated dynamic RBs out of the way. Force will not transfer from simDynamic-simDynamic RBs in this system.
  5. Then KinematicCharacterSystem goes through all simDynamic RBs, and casts them based on velocity etc. It will use the collide and slide algorithm to find its next position.
#
  1. Call MovePosition on all RBs, and physics step will move them to where they need to go, and generate collisions and callbacks.
#

Does this sound like a solid idea?

#

I’m just so frustrated with the physics2D system. It’s closed, so I can’t do shit when I need to modify anything. I can’t program joints/effectors, I can’t change how contacts work etc…

verbal temple
#

yeah its a huge pain but that's the only way to have full control

#

I have extended KCC because I didn't really like the architecture too much but the core system is good

#

it gives a lot of control

#

I have not gotten around to making a 2D version yet as I am working on 3D projects but I would definitely do it if I was working on a 2D project

#

so, solid idea I think

#

many of Unity's systems are very closed 😢

undone coral
#

I'm facing a very weird issue regarding

#

I think I might have my answer to all my

cerulean wasp
cerulean wasp
#

i am basically looking for mario physics

#

imagine POW blocks on moving platforms.

dusty wigeon
#

... You do not need to rewrite a whole physics engine for that ?

cerulean wasp
#

POW blocks can get: 1) thrown around and appear to follow gravity/momentum/other forces, 2) get stopped by solids (including any POW block), and 3) Can stably ride other surfaces (like POW blocks or platforms), and 4) can be ridden by other things (player, blocks, etc)

#

explain to me how to make that work in a simpler way

dusty wigeon
#

Sure, use kinematic + sphere cast

cerulean wasp
#

the whole system I proposed is a bunch of kinematic RBs casting in a specific order to calculate collisions and where they are going

dusty wigeon
#

You also use non kinematic if you want it to rebound and act like a physics bject

cerulean wasp
#

I have blocks right now that are dynamic, and work fine until you have blocks trying to ride blocks, as you need to translate transform to do that for a dynamic RB

#

Q: How do you get the block to rebound and get pushed by other physics objects, while also riding other blocks, without affecting the trajectory of the block it is riding?

dusty wigeon
#

Transform.Translate + Raycast

cerulean wasp
#

tried that. the moment you use transform.Translate, you move the colliders in a way that doesn’t respect physics

dusty wigeon
#

You use Raycast to respect the said physics

cerulean wasp
#

and if you cast to clear the way, you run into contradictions in what is supposed to happen

#

if block 3 rides 2 rides 1, and 1 moves left, 2 has velocity going up, and 2 hits an obstacle in the way, then where is 3 supposed to go? It would need to raycast n-1 times to move with everything

dusty wigeon
#

The other option, is to set the velocity

#

If block is riding, then add the velocity to the given block

cerulean wasp
#

tried setting velocity. It accumulates. If block 2 hits an obstacle, and then the obstacle disappears, it is difficult to get block 2 back on track synced to block 1 by setting velocity

dusty wigeon
cerulean wasp
#

if you try to remember the old velocity, and calculate the difference before/after physics calculation, then if you have block 2 hit an obstacle, then during physics simulation, blocks 3+ were all given velocity assuming 2 didn’t hit anything, which is wrong

dusty wigeon
#

You do not calculate any velocity ?

#

You just set/increment

cerulean wasp
#

then what do you do if block 1 has constant x velocity

dusty wigeon
#

If block is on Ride, then add the velocity of the ride

cerulean wasp
#

if I add velocity of ride every frame, that is also wrong

#

velocity increases without bound with const velocity platform

dusty wigeon
#

Obviously, you do not add it every frame

cerulean wasp
#

then how do you make block 2 track properly if an obstacle gets in its way, then disappears?

#

block 1 moving at const velocity

#

static terrain shears block 2 to the side for a bit, then is out of the way

#

i would use acceletation, but the physics simulation is like a closed system

cerulean wasp
#

so if terrain is shearing off block 2, the joint would actually halt block 1, which is wrong

cerulean wasp
#

you need to calculate that before physics step, right? to apply force?

#

moving the top block onto the green is not right

#

Just for reference, what I have tried:
-Transform.Translate based on delta position OR with casting => janky collision and overlapping
-Joints => upper blocks pull lower blocks, wrong
-Friction => doesn’t sync motion well enough.
-Two colliders (so I can make lower block independent of top) => still can’t apply assymmetric force to upper block to track.
-Change velocity => Can’t reconcile collisions during physic step
-SurfaceEffector2D => incompatible with platform effectors, which are mandatory. Also I can’t track vertical pos.

unique ermine
#

can someone explain to me why I should use Dependency injection instead of Singletons for managers to keep track of certain game data?

sly grove
#

More formalized control of the object lifecycles I guess? The standard Singleton pattern is just a low-sophistication DI implementation.

#

serialized fields are also a form of DI

sage radish
sly grove
#

better unit testing support too I suppose (going along with the "more easily replace the implementation of any feature/system/manager" part)

unique ermine
#

@sage radish @sly grove
fair. I want to fit my code for unit tests anyways which would make that part easier.

However I'm having trouble implementing DI using Zenject
Any good resources you can recommend? The examples I saw in the official docs didn't seem to work and It was a bit weird having to manually asign how the DI should work for each objects.

tawdry ferry
#

its really easy

cerulean wasp
sly grove
#

also i think you replied to the wrong person

cerulean wasp
#

singletons give you really clean and fast access to something you need frequently and everywhere. But isn’t a static class

tawdry ferry
#

yup sorry but ok

cerulean wasp
#

dependency injection is a way to decouple code by making both sides link to one thing in the middle

unique ermine
thin mesa
thin mesa
# unique ermine you know the difference?

the difference between extenject and zenject is that extenject was updated more recently. it's literally just a fork of zenject with the intention of keeping it maintained (which they seemingly failed to do since their latest release which wasn't even a full release is well over a year old now)

unique ermine
#

guess I'll give it a try again.

#

@thin mesa hope I'm not annoying you but I can't seem to understand how to make this specific case work:

I have a manager for handling scene changes which is a MonoBehavior rn.

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

public class SceneManager : MonoBehaviour
{
    private void Start()
    {
        LoadSceneWithLoadingScreen("Menu");
    }

    public void LoadSceneWithLoadingScreen(string sceneName)
    {
        // start an asynchronous operation to load the target scene.
        StartCoroutine(LoadSceneAsync(sceneName));
    }

    private IEnumerator LoadSceneAsync(string sceneName)
    {
        // create an asynchronous operation to load the scene.
        AsyncOperation asyncLoad = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName);

        // while loading
        while (!asyncLoad.isDone)
        {
            Debug.Log($"Loading Scene: {sceneName} - {asyncLoad.progress.ToString("P0")}");
            yield return null;
        }

        Debug.Log($"Loading Scene: {sceneName} - 100 %");
        Debug.Log($"Successfully loaded {sceneName}");
    }
}

is it even possible to use this in my other script?

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

public class NavigationController
{
    public void NewGame()
    {
        // Call the sceneManager here to load a new scene
        Debug.Log("Pressed new game");
    }

    public void LoadGame()
    {
        Debug.Log("Pressed load game");
    }
}

or am I missunderstanding smth?

#

what's important to note is that my SceneManager is present in a persistant scene at the start
while the other script is located in a menu scene.

thin mesa
#

whatever object creates the instance of NavigationController just needs to get a reference to SceneManager and pass it to NavigationController. or you can use something like the singleton pattern to get a reference to it. this is far from advanced though. you should check out this resource for learning how to refer to other unity objects

sly grove
unique ermine
#

I'm trying to avoid singleton pattern right here, thats what this is all about.

fickle mango
#

Wouldn't it be better to inherit SceneManager from NavigationController?

unique ermine
sly grove
unique ermine
#

I know how to do references etc.

fickle mango
unique ermine
#

I only use inheritance for things that are similar yet have differences like
sword and gun inheriting from weapon

or truck and jeep inheriting from vehicle

fickle mango
#

Gun and Jeep are also both inheriting the same class, MonoBehaviour

unique ermine
#

that's true

#

in theory

#

those were just inheritance examples, nothing I did in unity.

fickle mango
#

tbh I don't exactly know what you mean with view UI controller, but for me it sounds like SceneManager is a script that handles loading any scenes, NavigationController is a script that handles loading specific scenes.

unique ermine
#

NavigationController is attached to a UI panel handling starting a new game and loading the game

#

so it handles UI actions.

mint pond
#

I have a weird issue, where the perlin noise that i generate, takes account on the Offset, when the game is started and its awake method is called, but not when the player moves, and those same methods within are called again. However when i use my mouse for moving it, within unity editor, it does work as intended... (I will send a video of my problem in a moment)

#

So as shown on this video, when my player moves to the side, and its supposed to push the perlin noise texture on the quad to the side, it doesent, it simply changes the offsetX value in the editor, but when I with my mouse change the value it the editor, then the noise moves as it should... This is such a weird issue, i hope someone can shed some light on what is going on here... i have quadruple checked my scripts, and they are all fine, so i am out of ideas of what to do to solve this.

long ivy
#

I mean, that's a silly thing to say because obviously something is wrong with your scripts

#

you're going to have to show the PerlinNoise script but my guess is it's updating the texture based on OnValidate or something from the inspector, and you aren't triggering any changes when your character is moving

mint pond
#

normally i have the myRenderer.material.mainTexture = GenerateTexture(); line in the update method, commented out

#

im guessing you need all the 2 scripts connected to this, right?

#

I have the random object spawner, which spawns my tree objects, and my infinite world script, which moves the squares or "Chunks" of background

long ivy
#

nope, this one is horrific enough. What happens if you copy-paste the sequence of values offset gets set to instead of the tiny increments? maybe you just happen to be snapping to integer coordinates, so it's generating the same noise map every time

bleak citrus
#

Perlin noise repeats on integer intervals, iirc

long ivy
#

yes, that's what I think the problem is

mint pond
#

oh, so how would you suggest i fix it?

#

And if you can find some references on the exact thing which is causing this, then please also send them, i would love to read up on it. thanks:)

long ivy
#

well one easy way is to normalize the values using the dimensions of your map, or whatever size you're fine where the pattern will repeat at

mint pond
#

how would you go about that?

#

or, first of all, how can i make the noise visibly update when player is walking?

long ivy
#

you're already doing that in the above script, every frame spewing garbage everywhere

mint pond
#

it seems that changing the number in which the offsetX value is incrementing with, to a much smaller value, makes it move as intended.

mint pond
bleak citrus
#

I'm not sure if simplex noise behaves the same way or not. I should probably check that.

low monolith
#

Discussion: Multiple Scenes or Single Scene for Game State

novel plinth
#

Reviving the thread from the dead.

Want to confirm that PolySharp works just fine in Unity, you need to update the outdated roslyn that comes with Unity

#

(sorry for the ping, Burrito 😅 )

scenic forge
#

I have not personally tried it, but it should at least work for C# 9 features that are not supported because of missing compiler stuffs

#

Eg init properties, which Unity manual just tells you to make your own IsExternalInit, and PolySharp would source generate it for you instead.

novel plinth
scenic forge
#

Oh wow that's cool, good to know.

#

Maybe I'll mess around with it some day, some C# 10/11 features look pretty juicy 🤔

#

How would you go about updating Roslyn in Unity?

novel plinth
scenic forge
#

Thanks.

solar iron
#

Hi guys

#

How can I make the points in my shader dynamic ??

novel meteor
#

is there a way using OnValidate() to make a value show in the inspector if bool is ticked?
just want to show/hide the value depending if the bool = true / false

novel plinth
scenic forge
#

Though I guess there's not really another way to do it.

limber snow
#

good morning people 😉

#

trying to improve my code using task, i just learn i need to manage the toke to be closed if app crashes or unity editor stopped

#

is this code fine?

#

when i launch the task i create the source cancellation token and managed this ?

fresh salmon
#

Usually your method should take a CancellationToken parameter, and operate on that to see whether the task was cancelled

#

And generate a token from the source: await MethodAsync(source.Token)

#

Note: if you're on Unity 2022 or above, you can access destroyCancellationToken, available on all MonoBehaviour inheritors, token that gets cancelled when the object this script is attached to is destroyed.

novel meteor
# novel meteor is there a way using OnValidate() to make a value show in the inspector if bool ...

I might as well share this, since its the solution.

using UnityEditor;

[CustomEditor(typeof(YOUR_SCRIPT_HERE))]
public class EDITOR_SCRIPT_NAME_HERE: Editor
{
    public override void OnInspectorGUI()
    {
        YOUR_SCRIPT_HERE theScript = (YOUR_SCRIPT_HERE)target;

        if (theScript.boolToCheck)
        {
            EditorGUILayout.PropertyField(serializedObject.FindProperty("boolToCheck"), true); // make sure to keep this one visable
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ANY_PUBLIC_PROPERTY_HERE"), true);
        }
        else if (!theScript.boolToCheck) // show other stuff if our boolToCheck isn't true.
        {
            EditorGUILayout.PropertyField(serializedObject.FindProperty("boolToCheck"), true); // make sure to keep this one visable
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ANY_OTHER_PUBLIC_PROPERTY_HERE"), true);
        }

        serializedObject.ApplyModifiedProperties();
    }
}

Thanks @novel plinth

novel plinth
scenic forge
#

The dream.

novel plinth
#

also you can do TimeSpan.FromSeconds(value) instead of miliseconds there for the delay

limber snow
fresh salmon
#

What?

#

Take the source in the end?

limber snow
#

im calling this task from another class , so how can i call the task with the token?

fresh salmon
#

The source can be declared in the other class

limber snow
#

i cannot find an example like this

fresh salmon
#
class A
{
  private CancellationTokenSource cts;
  public B classB;

  void Awake()
  {
    cts = new CancellationTokenSource();
  }

  async Task Sample()
  {
    await classB.MethodAsync(cts.Token);
  }
}
limber snow
#

but must be async task sample(cancellationtoken toke)?

fresh salmon
#
// in class B
public async Task MethodAsync(CancellationToken token)
{
  // do stuff...
  if (token.IsCancellationRquested)
    // handle cancellation
}
#

A CTS produces linked tokens, so you can see from the token whether the cancellation has occurred. Don't pass the CTS everywhere, it's not its job

limber snow
#

what class so check in OnDisable destroy the task?

#

class A really?

fresh salmon
#

Yes

#

If you need to cancel the task when B gets destroyed, then it's B's responsibility to signal A to cancel the tasks using the CTS

#

Using an event, preferably

limber snow
#

hmm

fresh salmon
#

Or, you can add some code in B that will just return from the async method when OnDestroy gets ran, using a boolean variable

#

CTS allows you to cancel tasks that the caller (the method that invokes the async method, passing the token) is not in control of

limber snow
#

thanks for explanation

#

i can use profiler to check everything is going fine?

#

just reading in unity 2022 there is some changes

novel plinth
limber snow
fresh salmon
ivory swan
#

Guys, is it possible to insert the JOB System in my game (a classic 2D mobile project) to multithread a couple of algorithms here and there without changing it fundamentally?

For example, if I convert my project to DOTS, then I would definitely need to start over because of ECS. But afaik the jobs system is more malleable. I wouldn't need to run my entire project multithreaded, right?

tiny pewter
#

yes, but you may need to change your collections to be job compatible

cerulean wasp
#

I'm going to be building a 2D physics engine (kind of) on top of box2D. The plan is:

  1. No rotation. Rotations can be set, but never changed during simulation,
  2. All objects are kinematic, and have different settings for how they are allowed to be simulated (can slide, can push, true kinematic,....).
  3. All objects get a monobehaviour (physicsMover) as an alternate to the rigidbody API to communicate with the custom physics system. This monobehaviour holds those settings, as well as current position/velocity/etc. Also has a physics check order.
  4. During fixed update, right before Box2D physics simulation, we go through all those physicsMovers in the specified order, and evaluate by casting a single collider (called the main collider) which is used for force/physics calculations. Physics step goes as follows:
    --Foreach physicsMover, cast it from its current position by a vector (velocity += force / m * deltaT, cast vector = velocity * deltaT)
    --If we hit something, logic depends on physics mover settings. Kinematic objects push pushable things forward if possible. pseudo-dynamic objects may or may not collide and slide. If the object get pinched in an overlap, then we need to call other logic to know what to do (kill object, let it pass though, etc).
    --Update all positions and sync.

Does this sound like a non-terrible idea?

dusty wigeon
indigo citrus
#

Is there a com.google.games:gpgs-plugin-support for UPM?

regal lava
#

Is there an advantage of using the vertex buffer methods from the Mesh class, or can I just focus on writing logic inside of my own compute shader script, then setting the mesh data directly from the output?

**Actually I'd still compute the logic via gpu program regardless, but Mesh has two different APIs and I was wondering the advantages of both.

regal lava
#

If anyone can answer some general mesh manipulation and optimization questions through unity's API, do ping me ;)

dusty wigeon
# regal lava If anyone can answer some general mesh manipulation and optimization questions t...

For advanced use cases that require maximum performance, you can use the advanced API, which has functions like SetSubMesh, SetIndexBufferParams, SetIndexBufferData, and SetVertexBufferParams. This advanced API gives access to the underlying mesh data structures that primarily work on raw index buffers, vertex buffers and mesh subset data.

https://docs.unity3d.com/ScriptReference/Mesh.SetVertexBufferData.html

regal lava
#

What would be needed to validate? Like if you had more UVs than general vertices?

#

I would be fine with just using SetColors, SetIndices, SetNormals, SetTangents, SetTriangles, SetUVs, SetVertices, and such. But I've no clue if it's like passing through all vertices every time.

#

There's really no single Mesh method to take in this type of vertex info, so maybe that's the idea of using the other API.

dusty wigeon
regal lava
#

Ah, ok yeah. Lot of extra logic I'd probably don't need.

dusty wigeon
#

Most of it is C++, so cannot really see what it really is

#

Except if you have a 80k laying around and some notoriety.

regal lava
#

Haha, yeah. Eventually ;)

regal lava
#

Seems like a strange concept that maybe I'm not understanding, but a lot of code I see is just throwing what's available into a single dimension.

#

I mean, each thread should be doing work independently anyway, so why would subdividing them help with the results?

regal lava
hoary plinth
#

From what I understand reading the documentation, Unity's .Net Standard 2.1 framework should be compatible with .Net 6.0, Correct? I wrote some class libraries using .Net6.0 but after integrating and writing a unit test, I'm getting an error about System.Runtime version missmatch. '''TypeLoadException: Could not resolve type with token 01000039 from typeref (expected class 'System.IAsyncDisposable' in assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')'''

flint sage
#

Probably need to target 2.1 instead of 6

#

or both

hoary plinth
#

How does one do that? Accordion to the Microsoft docs there is no .net Standard 2.1 SDK your just suppose to use various versions of .Net. ".NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET implementations. To target .NET Standard in your projects, install one of the SDKs from the .NET/.NET Core table. For more information, see the .NET Standard article."

#

The spot were it's erroring out is when I'm trying to setup DI for the backend libraries, perhaps it's not the framework but the Microsoft DI libraries.

hoary plinth
#

I did have an error when I was importing the Dependency Injection assemblies. I excluded them from the Editor seems to resolve the issues. I couldn't find any clear answers on the errors: Unloading broken assembly Assets/GuildLegendsPrototype/Unity/References/Microsoft.Extensions.DependencyInjection.dll, this assembly can cause crashes in the runtime

hoary plinth
#

Ok so apparently when using nuget there are multiple versions of the assembly downloaded, There is a specific standard2.1 folder with compiled dlls. removing the previously imported dlls, and importing the ones from the standard2.1 folder, its no longer erroring on the DI call.

lament salmon
#

Has anyone done occlusion culling for procedural levels?
If you got any resources or even open source solutions you can point me to, please do

#

The levels are fully generated on start, so that's when the occlusion data generation would happen

indigo citrus
#

Why would this happen in android (error doesnt happen while in the editor)?

#
2023/10/22 16:20:40.483 530 702 Error Unity NullReferenceException: Object reference not set to an instance of an object.
2023/10/22 16:20:40.483 530 702 Error Unity   at UnityEngine.Object+MarshalledUnityObject.ThrowNullExceptionObjectImpl (System.Object obj) [0x00001] in \home\bokken\build\output\unity\unity\Runtime\Export\Scripting\UnityEngineObject.bindings.cs:737 
2023/10/22 16:20:40.483 530 702 Error Unity   at UnityEngine.Object+MarshalledUnityObject.MarshalNullCheck[T] (T obj) [0x0001d] in \home\bokken\build\output\unity\unity\Runtime\Export\Scripting\UnityEngineObject.bindings.cs:620 
2023/10/22 16:20:40.483 530 702 Error Unity   at UnityEngine.Collider2D.OverlapPoint (UnityEngine.Vector2 point) [0x00000] in <00000000000000000000000000000000>:0 
2023/10/22 16:20:40.483 530 702 Error Unity   at ClickScript.Update () [0x00059] in E:\Games\Franks-Pizzeria\Assets\Scripts\Principal\Clicks\ClickScript.cs:73```
#
void Update() {
        foreach(Touch touch in Input.touches) {
            if(touch.phase == TouchPhase.Began) {
                Vector3 wp = Camera.main.ScreenToWorldPoint(touch.position);
                Vector2 touchPos = new Vector2(wp.x, wp.y);
                
                if(boxCollider2D.OverlapPoint(touchPos)) {
                    ItemClicked(Camera.main.ScreenToWorldPoint(touch.position));
                }           
            }   
        }
    }```
indigo citrus
#

this one

#

if(boxCollider2D.OverlapPoint(touchPos)) {

fickle mango
#

looks like the boxCollider is null

slender prairie
half swan
#

You need to break it into multiple meshes

slender prairie
#

Oh man... that's why he made it a chunk system lmao

#

Thank you!

flint sage
slender prairie
#

Is that so? Would that be a bad choice for performance? Although I am trying to bust out this project as quickly as possible.

flint sage
#

Probably doesn't mater much

slender prairie
flint sage
#

I forgot to link that lol

slender prairie
#

Nw

#

Yeah that solved the problem. Thanks for your help!

novel plinth
flint sage
#

Just don't support old phones then

shut surge
#

Hey folks, anyone know what course of action I could take when trying to squeeze as much performance out of MonoBehaviour Unity as possible?

I'm unable to adopt DOTS as a stack due to my project's requirements (a core part of the project has dynamic, hierarchical structures that rely a ton on interfaces + delegates) and unfortunately I won't be able to make architectural changes to make it compatible

I've tried to get as much as I can out of things like Jobs, leaning on the right data structures, and so forth - but I've hit a dead end and haven't been able to reduce the work my game needs to perform. Anyone know where I might be able to look at this point to help improve perf?

misty glade
#

Deep Profiler/Profiler to start - figure out where your bottleneck is

#

Are you CPU bound?

shut surge
# misty glade Are you CPU bound?

Absolutely, I've been building out the core systems and haven't made a start on anything graphical yet - everything's a cube at this point

sly grove
#

Yep the profiler obviously is the place to start

#

anything else is a waste of time

misty glade
#

there's probably some low hanging fruit you could improve your performance drastically, depending on your expertise with unity.. but .. yeah, unfortunately the question is kind of broad and hard to answer easily

shut surge
#

I've run Deep Profile on my project and most of the CPU time is being spread across a lot of dictionary reads/writes across the codebase. Unfortunately, there aren't any stand-out large bottlenecks to tackle at this point

misty glade
#

is your project public? I wouldn't mind having a peek while watching football 🙂

shut surge
#

That + some calls needed to get/set values on things like Transforms, though I've tried to keep those to a minimum

sly grove
shut surge
misty glade
#

get/sets and dictionary access likely aren't your issues unless your dictionaries are really huge

sly grove
#

right not the operations themselves but the sheer number of them needs to be reduced

misty glade
#

cache your monobehaviours, minimize instantiates, minimize update work, don't traverse the heirarchy with GetComponent or GetComponentInChildren calls

#

what magnitude of MBs are we talking about here? 1000s/100ks/1Ms?

#

you mentioned DOTS so I imagine it's large

compact ingot
#

could be that your whole architecture makes no sense, impossible to tell

misty glade
#

yeah.. i mean, if you can't share your entire codebase to peruse (no worries on that, btw), it's hard to give general guidance on optimization.. but if you've narrowed it down to something more specific that'd enable better feedback from this channel

compact ingot
#

if you use a lot of interfaces and abstraction actual optimization on the data/cache level is likely out of the realm of possibility anyway, so your focus is on algorithms, structures and design

shut surge
#

I can't share the whole architecture, which is a shame, though there are some problematic parts that I can give a share real quick

#

I'll get a gdl/hatebin/something set up for some things that have been causing a ton of trouble, hold on a sec

misty glade
#

also we don't know your expertise.. like.. maybe you have something like

void Update()
{
  MyMB newMb = Instantiate(myMBprefab);
  Vector2 speed = newMb.GetComponent<MyOtherMB>().GetSpeedFromHugeDictionaryThatIsntCached();
  this.transform.position += speed;
}

and if you had even as few as a few hundred objects this would likely kill your app

#

ie - instantiating in update, get component-ing every update, etc

#

this gives me an idea for a cursed unity code youtube channel or something lol

misty glade
#

because i give the little patience i was blessed with for my kids :p

compact ingot
#

hehe, good choice

misty glade
#

"hey i have this problem with X but I won't do the obvious solution Y because I'm involved in a holy war can ne1 help"

#

"hey can anyone help me decompile minecraft"

compact ingot
#

you can also join the group of people who never ask anyone for notes on their work

#

bet you'll find some gems there

misty glade
#

while I wait for quote's hatebin paste.. thought problem...

I have a "level map" (ie, candy crush, vertical scroll) where I want a background, a parallax layer, and a UI layer (on top).

Should I just orchestrate all 3 layers with one scrollrect? Or is there maybe a better solution

misty glade
#

stars move 1:1 with scrollrect, planet will move in parallax, and UI levels will move 1:1 with background but appear above parallax layer

compact ingot
#

i'd aim to not use UI if i can help it for the BGs

misty glade
#

unfortunately i'm in a UI world since.. that's how I roll 😉

compact ingot
#

just because UI likes to redraw a ton of stuff all the time

misty glade
#

yeah, i probably ought to reevaluate it at some point, I've got this app running in 60 fps and my phone gets a little warm

compact ingot
#

maybe make your own parallax component based on the UI API

shut surge
compact ingot
#

a stripped down version of the scrollview

misty glade
#

don't allocate lists in update (twice)

#

and your hashset

misty glade
#

good gosh, all these allocations in Update are bad

#

and a bunch of disposes? eep

shut surge
#

Scheduling the Boxcast + the part at the end where I end up getting the components, the allocations + other jobs barely make a dent based on profiling info

misty glade
#

fair but you're going to experience this thing where you play for 30 seconds then suddely the GC has to do a bunch of work and the app hangs for a few hundred ms or

#

are you able to show Looker.cs?

#

yeah this chunk of code is a pretty good candidate for profiling

compact ingot
shut surge
#
public class Looker : IObjectiveComponent {
    // A Looker is an object that tracks what our characters
    // can see when they're moving about the world

    //--------------------------------------------

    // The eyes that are being used by this looker
    public Transform eyes { get; set; }

    // The visual range of this looker - used to determine how
    // far this character can see
    public Vector3 visualRange { get; set; }

    //--------------------------------------------

    public Looker(Transform eyes, Vector3 visualRange) {
        this.eyes = eyes;
        this.visualRange = visualRange;
    }

    //--------------------------------------------

    // Runs when this component is added to an item
    public void OnCreate((Component) obj) {
        // Register this looker inside of our manager
        LookerManager.instance.Register(this);
    }

    // Runs when the object is destroyed OR the component is removed
    public void OnDestroy((Component) obj) {
        // De-register this looker inside of our manager
        LookerManager.instance.Deregister(this);
    }

    //--------------------------------------------

    // Clones this object, returning a deep copy
    public IObjective Clone() {
        throw new System.NotImplementedException();
    }
}```

Had to roll my own component system to get more perf  ![atwhatcost](https://cdn.discordapp.com/emojis/1068114091987718204.webp?size=128 "atwhatcost") @misty glade
compact ingot
#

they are actually free if you pick the right one

shut surge
compact ingot
#

you need to get those down by a factor of 10-100 depending on the importance of the system

#

or run them in the background at a lower frequency

shut surge
#

I've tried to spread the work across frames by making the Lookers only activate every second or so + trying to stagger them so that they don't all get checked on the same frame. The thing I've put in to make that work hasn't been very successful, though

compact ingot
#

why do you need so many?

#

what are they?

shut surge
#

The lookers are all attached to characters in the game, the fact that there are so many is a fundamental design requirement so the only way through is to increase performance

Do you know any good ways to spread work evenly across frames? Giving each looker a time and trying to spread those out with Math.Random() probably isn't the best approach - but I'm not sure what would be better

misty glade
#

You could queue looker "look requests" and only pop requests as long as the render time for this frame hasn't exceeded some amount of ms

#

(and keep an eye on the queue size, decide what to do if it exceeds some cap etc)

sly grove
#

also is it possible to only process "lookers" that are near the player or camera?

#

and cull the rest?

compact ingot
shut surge
sly grove
misty glade
shut surge
#

These all look like good roads to take, will give them a try and see how things go - thanks all 🙏

compact ingot
misty glade
#

😛

#

i could probably even add and expose the parallax coefficient to the designers but.. maybe that's complexity for the sake of complexity and not really useful

compact ingot
shut surge
#

Again though, thanks for the help everyone - I appreciate it

misty glade
heavy saddle
#

I'm trying to retrieve domain name of the webpage the webgl client is running on from javascript to unity. Here's what my .jslib file looks like js mergeInto(LibraryManager.library, { GetTeamName: function () { let teamName = document.location.hostname.split('.')[0]; if (teamName === 'play' || teamName === '127') { teamName = 'blitzchampz'; } console.log('Host Name: ' +document.location.hostname); console.log('Team Name: ' + teamName); return teamName; } }); My GameManager looks like this ```cs
public class GameManager : MonoBehaviour
{
[DllImport("__Internal")]
private static extern string GetTeamName();
private string teamName;
private void Start()
{
teamName = GetTeamName();
Debug.Log("Team name: " + teamName);
}
}

Here's the output:
sly grove
#

To return a string value, call _malloc to allocate some memory and the stringToUTF8 helper function to write a JavaScript string to it. If the string is a return value, then the IL2CPP
runtime automatically frees up the memory for you.

#
  StringReturnValueFunction: function () {
    var returnStr = "bla";
    var bufferSize = lengthBytesUTF8(returnStr) + 1;
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
  },```
heavy saddle
#

facepalm thanks lmao... ive been stuck for an hour lool

#

i just read the int part and assumed it'd be same KEK

timber flame
#

Hey, I have implemented cellular based water simulation in a compute shader. It is OK but there is some issues there.
When I hole (dig a small just one voxel hole), stored water in the storage/tank, only some portion of water can leak then it stops. Do you know the reason?
It seems the voxels are settled

sly grove
twilit grove
#

is there a way to require all of the methods of a specific interface, but not allowed that interfaced to be found by other objects with GetComponent<Interface>()?

austere jewel
twilit grove
#

Im currently coding a networked game, and certain things the player can react to, like being slowed, damaged, thrown ect. To prevent duplicat code, i have a script which has the code to handle all of these things, and I dont want these to be called directly, rather a separate script to call these, because when in online mode, I need to tell the server to do these things, while in offline mode, i can simply just call them basically.

#

im new to this stuff so if theres a better way id like that lol

#

hmmm.... maybe i could split every interface into a grabbable and ungrabbable ver? then if i wanted to require certain methods I could inherit from the ungrabbable ver???? would that work?

#

would that be practical?

long ivy
#

I'm no networked game expert, but personally I think I would try to make it the same code path. Why can't you run a local "server"? Your way sounds horrible to me

dusty wigeon
# twilit grove Im currently coding a networked game, and certain things the player can react to...

Usually, you still use the network library in Offline. If you really want, you could try to use Precompiled, Reflection, Partial and/or Code Generation. You would probably be able to do something that is mostly transparent. However, that would definitely cost you implementation time and, depending on the implementation, performance at runtime.

Also, if you have reusable Network Code, you can opt for the usage of MonoBehavior (By example, sync Transform), the usage of utility function to reduce the boilerplate code down or even the usage of Composition with something like a NetworkVariable.

gloomy mica
#

In this documentation, what does it mean to "Never have Unity serialize duplicate data or cached data"? Can anyone gives an example?

flint sage
#

It's just syncing problems

#

If you change the type it might not deserialize anymore and thus cause errors

limber snow
#

good morning

#

where can i ask something releated to using mysql inside my unity project?

#

i can get working update, insert get etc... but im trying to manage case then but something is wrong

#

i want to check if player make cheats and set player.score to higher number then set to 0

devout hare
#

Why are you trying to do the check in the query? Check the score before running it

limber snow
#

yes, i have the code before

#

but if i know before to run the query, my score is differnt from 9999 then how can i exclude to update player score or what is the best approach?

devout hare
#

I don't understand what you're saying and I don't know what programming language you're using there but the idea is this:

if(dtplayer.score == 99999) {
  score = 0
} else {
  score = dtplayer.score
}

"UPDATE players SET player_score = " + score
limber snow
#

Awesome yea sorry this example was fixed

#

but i got another case, where i need to set a column to null if this score is 9999

#

i cannot set to 0, its hard to explan, then i need to use "case" sintax

devout hare
#

Even harder to advice if you can't explain the problem

limber snow
#

I will try to make an example inside the code, thanks so much

sly grove
limber snow
#

Because I need to set to null the value no to 0

limber snow
scenic forge
#

Btw, you should parameterize your query to protect against SQL injection.

gloomy mica
limber snow
#

I cannot find an example to do it inside my unity class

#

I can manage update get etc but using a long sql query

#

ok i have to go thanks anyway i will show you later my full code to check if my sintax is fine, at this is not lol

scenic forge
#

I would strongly suggest you to get comfortable with navigating documentation and not rely on ChatGPT.

limber snow
#

thanks so much

wispy rose
#

Does anyone know of a ShaderLab parser library that would be good for writing a converter? An HLSL parser with include support might also do the trick.

heady void
#

I don't remember now, there was an issue with ?? operator not working with NULLS properly but i dont remember the details. Does this work 100% of the time?

combinations[i] = combinations[i].Zip(cellCorners, (combinationCorner, cellCorner) => cellCorner ?? combinationCorner).ToArray();
#

(cellcorner and combinationcorner are monobehaviours)

sage radish
#

So this will only work if cellCorner is actually null, like if you set it to null or it's unassigned. Note that an unassigned serialized field will still have a fake object assigned to it, at least in the editor.

undone coral
#

is there a pre-existing package which wraps the native collections like NativeArrays into ordinary C# classes, such that they are disposed when the C# class would ordinarily be finalized / garbage collected?

    private class OrdinaryByteNativeArray
    {
      public NativeArray<byte> bytes { get; }

      public OrdinaryByteNativeArray(NativeArray<byte> bytes)
      {
        this.bytes = bytes;
      }

      ~OrdinaryByteNativeArray()
      {
        bytes.Dispose();
      }
    }```
is this a sufficient implementation?
#

supposing the bytes were always persistent allocated

sly grove
# undone coral is there a pre-existing package which wraps the native collections like NativeAr...

I would use IDisposable and using statements rather than a deconstructor. You have very little control over when an object is garbage collected, it's not recommended: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers#explicit-release-of-resources

#

you could use a finalizer still as a backstop but IDisposable and using are much more predictable

tiny pewter
#

Why not put it in ondestroy? Unless your class is runtimeinitializeonload then your monbehavior creates native array in awake or start (or other class that use native array) then free it in OnDestroy (or dispose the class)
Warp a native array can result on heap use after free, though unlikely to happen

#

Just for native array, if you wrap other dynamic buffer (hashmap, list, etc) then you will get an additional double free error in your implementation (only get but no set)

regal jasper
#

Hey guys,

I'm working on a JSLIB and am wanting to return a string after awaiting my JS function, however it only returns null as I assume Unity C# doesn't work async with the JSLIB?

JSLIB:

ConnectAccount: async function() {
    
  if (window.ethereum) {
    const accounts = await window.ethereum
      .request({ method: 'eth_requestAccounts' });
        var TestString = accounts[0];
        var bufferSize = lengthBytesUTF8(TestString) + 1;
        var buffer = _malloc(bufferSize);
        stringToUTF8(TestString, buffer, bufferSize);
        return buffer;

  } else {
    console.error('MetaMask not found. Please install MetaMask or enable it in your browser.');
  }
}```

This should return a string of '0xSomeAccount'

**C#:**

```csharp
    [DllImport("__Internal")]
    private static extern string ConnectAccount();

    public void RequestAccount()
    {
        string test = ConnectAccount();
        Debug.Log(test); // Returns 'Null' instead of '0xSomeWallet'
    }

Does anyone have experience with this and am willing to point me in the right direction?

regal olive
#
    {
        bossHealthBar = FindObjectOfType<BossHealthBar>();
        switch (scriptType)
        {
            case ScriptType.First:
                if (firstScript != null)
                    firstScript.bossBarUpdate += bossHealthBar.UpdateFillers;
                break;
            case ScriptType.Second:
                if (secondScript != null)
                    secondScript.bossBarUpdate += bossHealthBar.UpdateFillers;
                
                break;
        }
    } ```
So, this is a script that is kind of an interface class between 3 scripts, BossHealthBar, firstScript that handles a type of enemies, and secondScript that handles another type. 
It's giving me the following exception upon construction:
` ArgumentException: Value does not fall within the expected range. `
Knowing that first and second scripts can be turned off when this gets constructed, what could be a solution to it?
#

Note: the exception is given on the line where the events subscribe.

tiny pewter
#

I remember this error is due to no case is matching the variable in switch

regal olive
untold moth
fiery light
#

i have a question about ml agents if anyone has time for that

regal olive
tiny pewter
#

Maybe i am wrong

regal olive
untold moth
#

What's bossBarUpdate and UpdateFillers. Can you share the implementation?

regal olive
#

Currently no. But I can share a description.
bossBarUpdate is an event instance of a delegate BossBarUpdate, that takes one integer as an argument and returns nothing.
UpdateFiller is a function in the BossBarHealth script, that also returns nothing and takes one integer.

#

I'm sorry. On my way to university, and don't have access to my laptop.

untold moth
#

Does it work of you change the UpdateFiller type to BossBarUpdate?

regal olive
#

You mean the return type of the function?

#

1 sec. I'll try to write the whole thing down from memory.

untold moth
#

Ah sorry, assumed that UpdateFiller is a delegate too

#

Check if your delegate signature matches the method in terms of accessor(public/private)

regal olive
#

Here's an outline of the scripts:

{
    FirstScript,
    SecondScript
}

public class BossHandler
{
    public delegate void BossBarUpdate(int hitPower);

    public ScriptType scriptType;
    public FirstScript firstScript;
    public SecondScript secondScript;

    private void Start()
    {
        bossHealthBar = FindObjectOfType<BossHealthBar>();
        switch (scriptType)
        {
            case ScriptType.First:
                if (firstScript != null)
                    firstScript.bossBarUpdate += bossHealthBar.UpdateFillers;
                break;
            case ScriptType.Second:
                if (secondScript != null)
                    secondScript.bossBarUpdate += bossHealthBar.UpdateFillers;
                
                break;
        }
    }
}

public class FirstScript
{
    public event BossHandler.BossBarUpdate bossBarUpdate;

    public void HurtInAWay(int hitpower) 
    {
        bossBarUpdate.Invoke();
    }
}

public class SecondScript
{
    public event BossHandler.BossBarUpdate bossBarUpdate;

    public void HurtInAnotherWay(int hitpower) 
    {
        bossBarUpdate.Invoke();
    }
}

public class BossHealthBar
{
    public void UpdateFillers(int hitPower) 
    {
        // Updates health bar fillers. 
    }
} ```
regal jasper
untold moth
regal jasper
#

I tried, but Unity C# has no chill haha.

So what happens when you call the function in WebGL is this:

  1. MetaMask extension pops-up and asks you to select an account to connect to the current window.

  2. Once connected, it returns the connected address or address[0].

The problem though is that for some reason, Unity immediately returns the buffer instead of waiting for the response from the JS.

untold moth
#
window.ethereum
  .request({
    method: 'eth_sendTransaction',
    params,
  })
  .then((result) => {
    // The result varies by RPC method.
    // For example, this method returns a transaction hash hexadecimal string upon success.
  })
  .catch((error) => {
    // If the request fails, the Promise rejects with an error.
  });
#

Ah, maybe not

undone coral
#

well there it is

untold moth
regal jasper
#

Iiiinteresting!

#

So I could essentially add the account to a variable in JS 😮

#

Lads thanks for the help! I'll have a go at these recommendations 🍻

untold moth
#

Not sure about that. But you wouldn't need it as long as you call the unity script from within that same js function(after awaiting/within the then/catch)

regal jasper
#

Will give it a go 🙂

sleek lantern
#

I'm trying to make a map renderer thing, whats the best way to do this? I have a big 2d array, and some lights that have a point, radius, intensity 0-1, and I want to cast some rays to set lighting values, then put it into a channel (lets say red) so I can use that later. image included for a bit of explanation.

#

should I go thru every pixel and check lights? Im assuming just shooting rays from every light would be fastest but wouldn't they spread out and miss?

tiny pewter
#

Ray tracing…

sleek lantern
#

yeah im crazy

tiny pewter
#

In 3D computer graphics, Potentially Visible Sets are used to accelerate the rendering of 3D environments. They are a form of occlusion culling, whereby a candidate set of potentially visible polygons are pre-computed, then indexed at run-time in order to quickly obtain an estimate of the visible geometry. The term PVS is sometimes used to ref...

sleek lantern
#

thats 3d though is it not, I just need to raycast my 2d grid of pixels

#

this only needs to run once btw, so I'm not too worried about performance or computation time

tiny pewter
#

2d is just 3d without one axis, but the algorithm should be similar (even much faster/easier then 3d version)

#

I think it can be computed by fragments shader using z buffer at real time but i have no clue how to write it

sleek lantern
#

would that be able to compute it then give data back so I could write to an image?

#

i know compute shaders can do stuff like that right (not that i've ever used them)

tiny pewter
#

There should be some ways to retrieve the frame buffer back to cpu

flint sage
#

If there is, that is really not recommended

tiny pewter
#

just an brute force way to pre compute the pixels

#

ofc another way is to find out all triangles visible to light source->rasterizer->compute all the pixels, but still look like gpu stuff

flint sage
#

I mean I would probably just precompute a bunch of cells in the level then only check whether those cells are visible

#

Rather than trying to find every pixel

tiny pewter
#

it depends on whether the cells is "small" enough for sampling etc ('L'=light source, 'A'=air, "W'=wall)
LAAAAAAW
AAAAAWAW <--
the "top" of rightmost wall in second row should be lighted up by light source but if you just line cast you may get wrong result, better solution is still treat it as mesh and continuously value in 2d plane

flint sage
#

Minor errors are often fine in these kinds of systems

#

Even in competitive multiplayer systems

#

Better to have high performance rather than perfection

deep socket
#

I am now testing the ability to send Json data to the AWS DynamoDB via the Lambda function to POST, and the error Error: HTTP/1.1500 Internal Server Error keeps occurring. What is the cause?

flint sage
#

Internal server error
Check AWS logs

deep socket
nova summit
#

Any best practices for using fonts (w.r.t prefabs) in Text Mesh Pro?
Consider I need to use multiple fonts with different sizes. Do I need to

  1. Create prefabs for each different size? (or this is a overkill)
  2. Create prefab for each different font?

Size of the font and rect transform size are variable in most cases. So linking those to prefabs sounds odd. But would like to know how usually the fonts and prefabs are handled.

dusty wigeon
sly palm
#

Wow Unity. Why is UnityEditor.BuildTarget not compatible with UnityEngine.RuntimePlatform? I want to store some information about my build, and I can into the problem that UnityEditor.EditorUserBuildSettings.activeBuildTarget returns a value that cannot be properly mapped to UnityEngine.Application.platform.

rugged radish
#

if I have a long running blocking task that uses Unity API, and I want to spread it across multiple frames, there is no other choice other than unity coroutines, right ?
I can't make it an async task in this case ?

lament salmon
#

Or are you saying you cant use Task here?

rugged radish
#

from what I see it doesn't
awaiting a Task that uses blocking unity calls blocks the unity thread for the whole duration of the task, Task.Delay or Task.Yield between the work batches don't suspend the task

sly grove
#

Well wdym by "blocking unity calls" exactly?

rugged radish
#

but I checked with something simple, like 2 loops with a dummy calculation, with a Task.Yield in between

sly grove
#

Those are blocking main thread operations

#

Typical async in Unity is not running on a background thread

rugged radish
#

I expect loops to be blocking, I want to render a frame in between them, so work is spread between 2 frames
as far as I understand It will work with a coroutine, right ?

#

yep, just tested with a coro instead and it does render a frame between the loops

fiery vine
#

I'm working with some deep-linking between two full-screen mac apps.
Deep-link from App 1 to App 2 works fine when app 2 is closed and it steals focus appropriately.
When either I try to link back to App 1 or try to go from 1 to 2 again, it fires the link, but doesn't take the focus off whatever app is currently shown.

Is there a way I can force steal focus or something?

thin mesa
rugged radish
rugged radish
sly grove
#

yeah box hooked you up

novel plinth
novel plinth
stuck plinth
#

why would Task.Yield not work there?

lament salmon
novel plinth
#

or frame timing

stuck plinth
novel plinth
lament salmon
#

If you need to wait just 1 frame you don't necessarily need anything fancy

novel plinth
#

wat?

lament salmon
#

I'm saying that an async Task with 'Task.Delay(1)' will work just fine for waiting 1 frame

novel plinth
stuck plinth
lament salmon
rugged radish
lament salmon
#

Anyway yeah with 2023 might as well use awaitable

hushed fable
rugged radish
#

while it did work for the test case, it didn't help with the actual use case, but I'll keep digging

stuck plinth
novel plinth
hushed fable
#

UniTask is a safer alternative for this

novel plinth
#

it should be noted, you can still use Task.Run or threadPools but the caveat here you must use ConfigureAwait(true) which may cause deadLock

stuck plinth
#

continuing on the current context is the default regardless of platform anyway

novel plinth
stuck plinth
novel plinth
#

it should affect it, I mean, you're not in Unity's lala-land anymore, so how can you get back? 😅 ...

stuck plinth
#

Task.Run runs something on a worker thread, if you await anything inside the method you're running there, it'll just continue on the same worker thread unless you use ConfigureAwait(false)

novel plinth
stuck plinth
#

well i asked if that was about webgl still?

novel plinth
#

oh yeah, I meant Task.Run in general in Unity was not specifically to WebGl

#

so you're correct here

#

webGl will just nope out

fiery vine
#

Deep Link Mac OS Between Two Apps

novel plinth
#

Need to run this test couple of times to successfully reproduce the issue

#

see the almost identical code between async and coroutine on the inspector

#

tagging @untold moth as we had the same argument regarding this the other day iirc (sorry for the ping!)

untold moth
#

Lol, I was just trying to understand what the argument is about.

untold moth
novel plinth
#

Just don't use Task.Yield if you don't want a buggy code..

untold moth
#

Damn I was using it for several years and never noticed.

stuck plinth
#

FWIW Task.Yield doesn't really "do" anything unlike Task.Delay, it's more about how the unity synchronization context behaves

#

i guess it runs twice in the first frame because the synchronization context updates after Update in the player loop? otherwise i think you can count on it to run at a 1 frame interval on every subsequent frame because unity doesn't update the synchronization context more often than that

novel plinth
#

Task.Yield was originally made so when you do longrunning ops in UI thread (Winforms/wpf ) it will not block the thread. Just that

stuck plinth
#

sure, it doesn't actually do anything specific to winforms or wpf though, and you can observe that it works fine with the unity context

novel plinth
#

Another neat trick with Task.Yield is that it you can avoid StackOverflow exception on a recursive function.

    {
        await Task.Yield();
        await Foo();
    }
#

Meanwhile await Task.Delay(1) will still throw StackOverflow exception

#

(I've seen this used in production with my own eyes notlikethis )

sly grove
#

seems like a bad idea in either case

nova summit
dusty wigeon
rugged radish
#

I decided to rewrite that long Task into a chunked processing from the Update
because Awaitable.NextFrameAsync also couldn't yield to the render thread, it runs the whole thing to completion
in a test case NextFrameAsync does work though
maybe something to do with compute shader dispatches preventing any yielding behavior

nova summit
#

Text mesh pro best practices for font prefabs

wispy kraken
#

anyone here got ever mouse control working on a nintendo switch?...

misty glade
#

I have a scroll rect with a content panel that I'm plopping down icons for each level.

I know the y location of the icon in the scroll rect.

I want to add a "back to the current level" button that "punches" the scroll rect and makes it land near the current level, accounting for inertia.

Anyone have an ideas how to accomplish this? I didn't see any API in the scrollrect component itself that would handle it.

misty glade
#

I mean, I can do that, that's what I'm already doing.. but I was hoping to get a nice animated effect

#

it feels a little janky to just snap it to the current location

#

(I suppose I'll just tween it there and disable all my parallax stuff while the tween is running)

fickle mango
#

use Vector2.Lerp()

misty glade
#

or..... tween it. :p

dusty wigeon
dire viper
#

Hello guys, quick question is anyone already used the facepunch.steamworks dll for Unity ? And if so did you used the leaderboard features ?

small lava
#

I think this is more on the advanced side, I'm making a note taking app and I want it to be able to have features like list making (like you've seen in apps like Word) or like adding shortcuts and just generally changing the text input field that comes with Unity to have more complex functionality

#

I have no idea where to start and every single thing I think of seems inefficient and dirty, like checking if a user presses enter and manually adding those dots for the user and manually adding spaces it just seems weird

dusty wigeon
small lava
#

I'm so scared to go back to anything that is not Unity 😭

#

Welp thank you anyway

scenic forge
#

Regardless of framework, unless you are using a component that has these features built in, you are going to have to write low level logic like "when enter is pressed, insert - with the correct amount of leading tabs/spaces"

#

They aren't "dirty," you just don't tend to work that low level in most projects (and especially not in a Unity project)

#

There are also software like Obsidian that solves note taking already.

#

But yes Unity is a game engine, you'd have much better time using something else.

sleek lantern
#

I want to figure out how to turn a big 2d array of pixels into a polygon collider 2d for my map editor (its a dev map editor btw), I could just use a tilemap collider and read from image manually but I want it to be a little bit smoothed (to ease physics, so the player can walk up a slope instead of it being jagged). I think I would need some kind of triangulation algorithm but I'm not entirely sure where to start (i also don't need internal points because polygon collider handles that already)

#

I know Noita did like exactly the same thing where they get a group of pixels as some triangles for collision

flint sage
#

So what have you done?

sleek lantern
#

well i have my 2d array of pixels sorted

#

the issue is they can in seperate 'groups' which might complicate things

tiny pewter
#

i think it is some variations on convex hull but i am not sure

sleek lantern
#

i think no matter what algo i would have to separate into groups somehow

#

I’ll rewatch that one Noita talk and see if i can find out what they used

sleek lantern
tiny pewter
#

no way

#

since you cannot define concave hull...............

#

there can be many

sleek lantern
#

Yeah

#

I might have to like

#

Split it up

#

Or find all exposed tiles and use those maybe to find all outlines?

#

If i find all exposed outline things could I just like line-of-best-fit it and have my points be those

#

Wait does polygon collider 2d even support like donut shapes uh oh

#

I would have to use line colliders then

tiny pewter
#

each tile can be treated as 2d rect in 2d plane, so you can directly get the x y coordinates, four for each tile

violet depot
#

Yo so I am doing some networking stuff and every fixed update the clients sends it position and reads all inbound packets. What would be the best way to use lerp so that the player has been smoothly moved to the correct location in time for the next one? The time step is 0.2.

tiny pewter
#

i think you can introduce some parameter and modify convex hull algorithm, lets say if the angle between two edges fall in some specific ranges then reconnect to make them one edge eg:
A A
X X
X X
XAX
give up the A in the middle and use two A on top

#

but you need to scan all vertices in each iteration

#

or compare the result with the actual convex hull, i think this should be better

novel plinth
# small lava I think this is more on the advanced side, I'm making a note taking app and I wa...

If you're planning to publish this for mobiles, you may out of luck.

Any games/apps that are made with Unity can't be used as background service on mobiles, meanwhile note-taking app ideally should be able to run as background service, so when a user put your app running in the background while doing something else, your note-taking app will still be running normally hogging lots of resources.

#

it's a bad idea

inland jacinth
#

im trying to displace vertices on a mesh with perlin noise to generate a "planet like surface". but i don't know how to make the noise align with the "shape" of the circle if that makes sense. currently it's just in this weird 45 degree angle.

code: https://paste.ofcode.org/xgiWiSTewsJgw3Qy6aqGVP

sly grove
#

Though what you have now would make a cool comet ☄️

inland jacinth
#

yeah i was thinking of something like that

cerulean minnow
#

Anyone know How I can get this script to picka random point to spawn in a sphere shape? right now it spawns randomly but the spawned objects are horizontal line
https://pastebin.com/7RwJrhNw

sly grove
#

Your code should make something like a circle shape on the x/z axis right now

tiny pewter
#

you set position.y=0.....

sly grove
#

but viewed from a certain angle that might look like a horizontal line

cerulean minnow
#

Basically all objects are on the x axis

sly grove
#

that's a circle on the x/z plane

#

which is kinda exactly what you are asking for with y = 0

tiny pewter
#

horizontal "plane"

cerulean minnow
sly grove
#

what exactly do you want if not this?

#

if you want in a sphere just get rid of the y = 0 part

#
        // Ensure objects spawn at ground level.
        randomPosition.y = 0.0f;```
#

this

cerulean minnow
sly grove
#

so you want a sphere, but just the top half of the sphere?

#

or you want an arc

#

(a circle, but only the top half of it)?

tiny pewter
#

top hemisphere?

sly grove
# cerulean minnow correct

Then instead of:

        // Ensure objects spawn at ground level.
        randomPosition.y = 0.0f;```
Do:
```cs
        // Ensure objects spawn in the top hemisphere
        randomPosition.y = Mathf.Abs(randomPosition.y);```
#

also do you want them all on the edge of the sphere or is inside the sphere also ok?

cerulean minnow
sly grove
#

no right now it allows inside

#

so you're good

cerulean minnow
#

i have a min distance so they arnt too close to the camera and a max disatance

cerulean minnow
rancid swift
#

anyone know why roslyn source generators must depend on Microsoft.CodeAnalysis 3.8 und must target netstandard 2.0 in 2022.3? using generators for netstandard 2.1 works fine in 2022.2 ...

sturdy comet
#

how to detect through code if a vfx is finished?

inland jacinth
sly grove
inland jacinth
#

i'm pretty certain that the cluster on the left should be at the center

small lava
sly grove
vital fossil
#

Respected,
i have applied force on a gameObject with rigidbody.
But when I applied force in z-axis then automatically force applied on x-axis even there are no force can seen on x-axis in rigidbody component and even still force applied when I freeze the position x..
can someone please guide me how can i resolve the issue.
Thanks

polar orchid
#

Anyone know how I would go about building a headless unity build, with special compiler definitions? I already build unity as a headless instance for a server, but I need 2 different "types" of headless instances

#

the second being a special type of player

dusty wigeon
polar orchid
#

yea, but specifically trying to conditionally define these based on a cli argument

polar orchid
strong harbor
#

Was wondering if anyone had some advice on an issue I'm having (might be a memory problem). I have an isometric tilemap. And the function that is giving me trouble is the following situation: I have a button that takes in some data, and then calculates and updates the isometric tilemap. The issue I am finding is that there are 4 of these buttons, and the intent is that you can click one, itll clear the tilemap, re-evalute then display the new info.

My issue is that after about 4 button presses, the game slows to a crawl and basically crashes.

Any thoughts? I have checked that the tilemap is being cleared and updated properly

regal lava
#

My thoughts can be anything when there's very little to go off of assuming this is all custom code.

sly grove
dusty wigeon
strong harbor
#

sadly i am not familiar with viewing the profiler

#

like i know how to open it up

#

but viewing it is something entirely different

untold moth
strong harbor
#

Found the issue lol

#

but no clue how to solve it

#

its some memory issue

#

when i press the buttons and get up there, the memory on my computer went all the way up

untold moth
#

What does the profiler say?

strong harbor
#

lets see if i can get a screen shot before unity crashes

#

ok i saved it after i pressed it enough to not crash but is like

#

feeling the burn

#

is there anything specific that would help you help me

untold moth
#

I mean, what exactly made you think it's a memory issue..?

strong harbor
#

the fact that when unity was frozen

#

i had to go to task manager

#

and saw my memory at 95%

untold moth
#

Ok, well, with profiler you can see the memory allocations. Select a frame with most allocations and take a screenshot of the hierarchy mode in profiler.

strong harbor
#

i think you are referring to this

#

i apologize, this is one of the sections of unity ive never dabbled in

untold moth
# strong harbor

I don't see any abnormality on this frame. The last frame in the graph seems to go up the processing time, so might want to look at it instead.
As for working with the profiler, look at the documentation. It's not that complicated.

strong harbor
#

see i dont see why the processing time would increase with each button call

#

unless im doing something very wrong

#

wait dumb high level question

#

the brain is firing

#

if i create an onClick listener

sly grove
strong harbor
#

does it create a thread that needs to be closed?

sly grove
#

no

strong harbor
#

like returned

#

hm

#

ok well that was one idea

untold moth
strong harbor
#

the code in question btw, at least what the button invokes is the following:

#

it just takes in a scriptable object from a class, and then the show___Range is just a function that edits the tilemap

sly grove
strong harbor
#

but i figured clearing the tilemap would destroy the objects

sly grove
#

You do seem to be allocating new Lists all the time at the very least

strong harbor
#

show___Range basically does some cacluations in a loop

#

to determine what the tiles that are in range of the weapon, spell or ability are

sly grove
#

a loop over what?

#

maybe show that code

#

also how are you storing these tiles etc

#

and what does ClearAllTiles() do

strong harbor
#

this is the longest and the shortest because it depends on the scriptable object

strong harbor
strong harbor
sly grove
#

didn't knwo that was a Unity Tilemap

thorn flintBOT
strong harbor
#

sure i can use that

#

This is the self spell version, since the only tile it needs to highlight is the one that the character is standing on since its the only valid target

public override List<GridTile> showSpellRange(List<GridTile> movementTiles, GridTile start, int movementRange)
    {
        List<GridTile> attackTiles = new List<GridTile>();
        attackTiles.Add(start);

        CursorMovement.instance.attackRangeTilemap.SetTile(start.gridPosition, CursorMovement.instance.friendlyTile);
        return attackTiles;
    }
sly grove
#

I can see that you are creating new lists constantly

#

this is really bad for performance

strong harbor
#

that could be it then