#archived-code-advanced

1 messages · Page 25 of 1

fresh salmon
#

They're not made to work with each other

abstract hill
#

I understand its not really used together, but I want to be able to run code, but have it not hold the frame.
The coroutines aspect I'm using to allow for multi-frame processing while Async I was just trying to use for semi-parallelisation.

undone coral
#
Task loadTrackingData = Task.Run((() =>
{
    _trackingDataContainer = (inputTrackingData == null) ? null : JsonUtility.FromJson<SessionTrajectoryDataContainer>(inputTrackingData.text);
}));

for example, here you try to use inputTrackingData.text on what you think is a background thread. if it's not the main thread, this will throw an exception

#

but you didn't od it right, so you ate exceptions

#

and you don't see them

#

so there are multiple cascading errors @abstract hill i am sorry

abstract hill
#

Ah okay, so it is throwing errors then. Will UniTask solve this for the purpose I am trying to do? (This being to start the code running but not hold the frame?)

undone coral
#
void Start() {
 ProcessInputs().Forget();
}

public async UniTask ProcessInputs() {
 var inputTrackingDataText = inputTrackingData.text;
 var inputEventDatatext = inputEventData.text;
 await UniTask.SwitchToThreadPool();
 // tasks are not threads.
 _trackingDataContainer = JsonUtility.FromJson<SessionTrajectoryDataContainer>(inputTrackingDataText);
 _eventDataContainer = JsonUtility.FromJson<SessionEventDataContainer>(inputEventDataText);
 await UniTask.SwitchToMainThread();
 Save();
}
undone coral
#

imo, you shouldn't read and write to plain object fields from other threads, but you can

#

@abstract hill is this hlepful?

undone coral
abstract hill
#

Ill have a quick read, thank you

undone coral
#

plain async on unity is flawed

#

it won't do what you expect it to do

#

the way you were using coroutines is also flawed

abstract hill
#

I'm not sure I understand exactly what is happening in the code, is the await UniTask.SwitchingToThreadPool(); a stand in for the block of code below it as a task?

undone coral
#

it is a real method in UniTask

#

because as the comment says

#

@abstract hill "tasks are not threads"

#

@abstract hill does that make sense?

#

it does exactly what it says

#

it really will "switch to the thread pool"

#

and then the code below it will execute on the thread pool

#

isn't that nice?

abstract hill
#

Oh, okay, that makes more sense then. I assume it will automatically assign the work from the JsonUtility code to a new thread and run that in parrallel then?

undone coral
#

sort of yes

#

it doesn't create a new thread, and the C# thread pool threads, like most threads, runs in parallel to the main thread

abstract hill
#

Gotcha

#

Does the pool seperate the work evenily, or is all that is below the Switch function get processed on one thread?

undone coral
#

the two deserializations will happen one after another on that thread pool thread. if you want to deserialize in parallel, use UniTask.WhenAll, and author a deserialize async method. however, it is best to leave it the way it is.

undone coral
#

trust me, if you couldn't do this right the first time

abstract hill
#

I am, sorry I just want to make sure I understand is all xD

undone coral
#

you will not do both deserializations on separate threads correctly either

#

it is indeed running one after another, exactly like it is written

#

it isn't syntactic sugar

#

the reason it works the way it does is because Tasks Are Not Threads

abstract hill
#

Yeah

undone coral
#

tasks can run on any thread, parts of tasks can run on other threads, or many threads, or no threads at all.

abstract hill
#

Last question then, since the await returns below it returns back to main, I assume this is all still happening inside a single frame still though? I can see on the git repo that there are functions to yeild and move to the nextframe, this is kind of what I am after, what would you suggest to be the way to do this?

undone coral
#

the code after the switch to the thread pool runs on the thread pool

#

i think you are trying to translate what you are reading into Task.Run

#

forget about Task.Run

#

forget it ever existed

#

just read exactly what it does

#

it's like english

abstract hill
#

The assumption comes from the await, SwitchToMain. since its awaiting, I am imageining that the main thread is haulting waiting for the code from the ThreadPool to run, if that is not the case then this works fine for me

undone coral
#

why would it do that

#

you are on the thread pool, it deserializes, time has past

#

you could have rendered 1, or 100, or 0 frames since beginning to deserialize

#

why would the main thread halt? you didn't ask it to anywhere

#

someday you will understand. Tasks Are Not Threads.

#

you asked to switch to the main thread. await is sort of syntactic sugar

abstract hill
#

Okay thank you, this sounds like it is the solution I will just need to get my head around it a bit better.
Ill give it a go to get this working, sorry for if I'm being a bit dense xD

#

Thank you

undone coral
#

you don't want to use yield

#

or wait for frame

#

you don't need to

#

do you see why?

#

i am calling SwitchToMainThread because Save() accesses data on unity objects

#

which you should only do on the main thread

#

not because i'm trying to wait

abstract hill
#

So final question then, just to make sure I have my head around this. Does the entire function operate outside of the frame or only the part below SwitchingToThreadPool?

#

Again sorry if I'm being a bit dense, just tyring to get my head around what you are saying and the syntax of ti

undone coral
#

everything that is not on the main thread runs "outside of the frame"

#

await UniTask.SwitchToMainThread() itself waits on the thread it is being executed on, which happens to be the thread pool.

#

the way it actually works is, it schedules the next part of the task to run on some other queue, and the thread that deals with SwitchToMainThread is the main thread. there is a monobehaviour that reads that queue in a "pre" Update that runs on the main thread (as any unity player loop code does)

upper hinge
#

I can't seem to build my game into a standalone player; when I try, I get a linker error (Fatal error in Unity CIL Linker). Details in this forum thread. https://forum.unity.com/threads/fatal-error-in-unity-cil-linker-failed-to-resolve-assembly-nunit-framework.1354511/ Any suggestions?

undone coral
#

await doesn't necessarily mean there is a thread being blocked

undone coral
#

however, based on this error

#

you accidentally referenced a test assembly / editor assembly in your runtime assemblies

abstract hill
upper hinge
upper hinge
timber flame
#

What do you suggest?
I want to create a procedural map like oxygen not included but it is 3d.
3d dungeon generator? room generator?
Delaunay triangulation graph ( Bowyer-Watson algorithm), minimum spanning tree (MST)
Suppose only place items and materials in voxels under the ground

compact ingot
timber flame
#

3d voxel game

#

and I would like to put some items and materials under the ground

#

Oxygen not included only uses 2d tile to check if an object (buildings, engines, etc.) can be placed or not in the environment, right?

#

It is not a tile game?

compact ingot
#

I don’t know a readymade asset/package that does it out of the box

#

If you do it without unity’s tilemap you probably need to make a level editor too

timber flame
#

marching cubes, OK, thanks

compact ingot
#

The way they are connected together is called marching squares, it uses a few predefined tiles and makes somewhat smooth looking connections based on a few simple rules

#

almost all 2d games use that in some way or other

timber flame
#

Yes, I know marching square algorithm

compact ingot
#

but mind you it’s not pure marching squares, there is rng and some UV trickery involved too

timber flame
#

and about Bowyer-Watson algorithm, can I ask here?

#

about the implementation

compact ingot
#

that’s just a triangulation method

timber flame
#

yes

#

The problem is how the first triangle is gotten

compact ingot
compact ingot
timber flame
#

Elaborate it

#

No, it can cause problems.

#

If some points inside and the triangle vertices are collinear or close to collinear

compact ingot
# timber flame If some points inside and the triangle vertices are collinear or close to collin...

a really nice implementation of it is rather complex, you can look at this one that is quite good: https://github.com/wo80/Triangle.NET/blob/f70be6a937c4c447b4cee05505d7ee2b75d68e62/src/Triangle/Mesh.cs#L548

GitHub

C# / .NET version of Jonathan Shewchuk's Triangle mesh generator. - Triangle.NET/Mesh.cs at f70be6a937c4c447b4cee05505d7ee2b75d68e62 · wo80/Triangle.NET

timber flame
#

@compact ingot thanks

#

To implement Tile-Based Atmospherics spreading like what exists in ONI, it is not as simple as spreading some fraction of it to adjacent tiles
Fluid simulation in Tiles

#

Because, each tile has a capacity

compact ingot
# timber flame Because, each tile has a capacity

its still some sort of cellular automaton (not fluid simulation at all), it just takes molecular mass + pressure (gas), conductivity (heat/germs(?)) and capacity (fluids) into account when it decides where to spread

timber flame
#

I thought max flow algorithm

compact ingot
#

yes, very simple, but the devil is in implementing that in a way that it runs at 60fps

#

you probably don't need to update the sim every frame

#

just put it into a coroutine and update 64 x 64 tile blocks at a time... or whatever suits your game

timber flame
#

ONI is awesome. I love it

hearty arch
#

Hi, is there a way to AddComponent in an editor script? I can't believe how hard it is to just have a button that'll add a specific component for you OnInspectorGUI.

sage radish
viral pilot
#

Hi guys,
I'm looking to do some CI around my project.

Here's the goal (manual steps I'm currently doing):
-Building unity project
-Use the generated DLLs
-create a unity package with those dll and a demo scene.

What's the best way to automate this process ? I don't think Unity Cloud Build has enough flexibility (I might be wrong).

sage radish
viral pilot
light falcon
#

is it possible to create a UI padding script like the ones seen in the layoutgroup components?
if so, how could it be done?

compact ingot
light falcon
teal bone
#

I've been getting into fluid simulations recently and I'm interested in the different approaches to solving the simulations. I'm aware of particle based solutions as well as some other "group" of solutions that use fourier transforms/trochoidal waves to simulate fluids (via mesh deformation?) just wondering what the latter version would be called, and what other solutions are out there in terms of fluid simulation

compact ingot
teal bone
#

either, I'm interested in all of it pretty much

#

probably the latter moreso though

compact ingot
#

those would be very different

#

you need to define the goal of the sim

#

its way too expensive to do generically

#

so any approach is really about trickery to achieve a specific goal in a specific use case, for generic sim there are plenty of research papers but those are useless in a game

#

for surfaces the gerstner wave (trochoidal) is a very good approach

#

for fast sim of surface water flow you can use cellular automata, works in 3d too but it gets expesive quickly if you go too deep into 3d voxels

teal bone
compact ingot
#

do you know what a celluar automaton is?

teal bone
#

my understanding is that cells have rules based on how many adjacent cells are "alive", like the game of life?

#

but outside of that I know close to nothing

compact ingot
#

more or less, yes

#

so you define a rule that makes a cell behave like a water flow

#

it doesnt have to be binary, you can implement all kinds of stuff like viscosity, surface gradient or pressure

#

and if you run that sim you get something that looks similar to a liquid flowing over a surface

#

water in minecraft or oxygen not included works that way (probably every other game with flowing water also works like this)

teal bone
#

I can't tell you how fascinating that is

#

wow

#

thank you

compact ingot
quartz atlas
#

Anyone can help me with Netcode? I am working on inventory system and I used ScriptableObject for individual items. So my inventory is basically List of SO. After making everything work I struggle with syncing that list with clients. I know that NetworkVariable and NetworkList exists but those don't work with SO. Is there a way to sync List of SO or do I need to switch from using SO to structs?

#

Yeah, I could just use List that has id and amount. But still hoped that I could use SO directly

#

So is there a way to sync stuff without it being NetworkVariable or NetworkList?

jolly token
#

Your problem is having "mutable SO"

#

They are asset and they are static, it does not make sense to send then and replicate over wire

quartz atlas
#

I used them as item database so if there is itemdrop I can just drag it into inspector and it has every info about that drop. But I guess that's excessive through network.

hazy roost
#

Does anyone know if the api AudioSampleProvider.ConsumeSampleFrames provides samples array for multiple channels in sequential(00001111) or alternate(01010101) order?

rapid osprey
hazy roost
rapid osprey
#

On how to use AudioSampleProvider or ConsumeSampleFrames?

hazy roost
#

@rapid osprey On ConsumeSampleFrames please

rapid osprey
#

The frame will be buffer inside the SampleProvider at the decoder speed. So it is possible there is no samples in the SampleProvider.

velvet reef
#

Can anyone help me convert URP shader code to HDRP? Specifically I want to use TransformWorldToShadowCoord(float3) from URP - which is now EvalShadow_WorldToShadow(HDShadowData, float3, bool) but I'm not sure how I set the HDShadowData

tawny otter
#

Hi all! I have an issue I would appreciate some input on.

For our project I'm trying to improve our process in how we are dealing with/setting up dependencies between objects. For example, for our event bus / messaging system I'd like to:

  • decouple the objects processing events from those objects/systems generating them (i.e.: event processors don't need to know how to register themselves, that is done for them)
  • remove the burden of managing these dependencies from whoever sets these objects up in the editor (again, dependencies should be connected automatically)
  • do as much of that as I can at edit/build time, not at runtime / on initialisation

As a solution I was thinking about either generating one or more ScriptableObjects per scene, or a GameObject in the scene, that serialises those dependencies between objects and automatically updates whenever something changes. However, I don't know if that would be best done from an Editor script, some kind of validation pass (like Odin Validator) or just a GameObject in the scene that updates in the editor and reacts to EditorSceneManager.sceneSaving.

Has anybody done something like this before or has some input?

obsidian glade
tawny otter
compact ingot
# tawny otter Hi all! I have an issue I would appreciate some input on. For our project I'm t...
  • the decoupling of processors from event sources is done by your message bus, if not, why are you using a message bus?
  • dependencies can be discovered automatically by components via suitable architecture, DI frameworks is one approach. A FindObject or OnValidate can do similar things too, odin validator can check for correct setup

It all depends on how much of that stuff is facing editor users vs code users

#

i'd be careful with DI frameworks as they can easily solve the original problem but cause new ones (hidden complexity) that is very hard to trace and manage

#

in any case if you build a complex system on top of a framework all notions of stuff remaining easy to replace/change go out the window if that change isnt specifically supported by that framework

tawny otter
# compact ingot - the decoupling of processors from event sources is done by your message bus, i...
  • the decoupling of processors from event sources is done by your message bus, if not, why are you using a message bus?

Yes, exactly. But additionally, I feel like processors also don't really need to know how to register themselves with the message bus. If something else collects them and adds them to a list to emit events to, that should work fine enough.

  • dependencies can be discovered automatically by components via suitable architecture
    Do you have a suggestion about concrete implementation starting points there? That's the one I'm leaning towards
compact ingot
#

generally patterns and frameworks that fix issues in OOP are often worse than switching to a less OOP style of coding

compact ingot
tawny otter
sage radish
compact ingot
obsidian glade
# tawny otter Hmm, interesting, I'll have a look at it. Though I'm not sure if I want to intro...

yes, though what's your reason for opposing dependency resolution at runtime?
you can certainly write your own editor scripts to bake these and assign references, but in practice it will be largely treading the same ground and writing your own DI framework on top of the Unity serialization framework and wouldn't be without its own complexities and issues

the benefit is you get to write exactly for your use-case and keep it truly simple and intuitive for your purpose, which may be preferable for your project

compact ingot
#

if you work in a large team with predictable workflows and certain issues in that workflow that are predictable, i'd maybe build the whole thing with a focus on that, facilitating that workflow better, provide checks and automation that eliminates errors (top down)... this may be easier to change than a complicated/implicit approach based on resolver/discovery logic (bottom up)

tawny otter
compact ingot
#

tbh, if you want a perfectly safe system that "fixes user error" you eventually end up with the realization that you need an interpreted language and/or sacrifice all performance

#

it might be good to make the system simple, accept mistakes, make them easy and quick to discover and easy to fix because the system is simple enough, the API is clear and error messages are helpful

#

if you have a complex system that only a few people in the team understand you will potentially create a dependency on those people for simple fixes and for improvements of the system

#

also if that system doesn't work close to perfectly or is a bit finnicky to set up and use, then people will hate it 😄

tawny otter
#

Hmm, you're right. I guess I'll just start simple and improve it when needed.

#

Thx all for the input!

compact ingot
tawny otter
# compact ingot can i ask what specifically you perceive as the constraint/bottleneck to your te...

We are quite a small indie team and are just now coming out of the prototyping phase. So, things are still very scrappy. What I noticed is that too much time gets wasted during the setup of objects/prefabs in the editor, because there are still too many things that one needs to remember to connect correctly. We already try to alleviate some of that with validation, but are not too far yet with automating setting up object structures or connections between dependencies. Main goal is to up the speed at which we are able to create content.

gaunt zinc
#

Is there a way to minimize the effect of lag during a coroutine? As operations sometimes go out-of-sync when fps drops, especially in an unoptimized editor scenario

#

I tried to use math a predict such behaviour to avoid several operations that supposed to stagger a bit gets fired during the same frame but that adds strain to the system and ripple further

sly grove
#

And by "lag" I assume you mean framerate hitches/drops?

gaunt zinc
#

Like spawn something then yield return wait for seconds 0.05 and spawn another

#

When fps drops, two of then might be spawned without the interval

#

Right now I have to write another script that handles delayed spawn which interpolates the behavior on a mirrored instance, but that just makes it lag more

undone coral
# tawny otter We are quite a small indie team and are just now coming out of the prototyping p...

I noticed is that too much time gets wasted during the setup of objects/prefabs in the editor, because there are still too many things that one needs to remember to connect correctly.
you can take an approach like

class Patrol : MonoBehaviour {
 public Transform[] patrolPoints = new Transform[0];
 public CharacterController characterController;

 void Start() {
  if (patrolPoints.length == 0) {
   // setup default patrol points
   var point1 = new GameObject();
   var point2 = new GameObject();
   point2.transform.position = transform.position + Vector3.right;
   patrolPoints = new [] {point1, point2};
  }
  if (!characterController) {
   // find component
   characterController = GetComponent<CharacterController>();
  }

  StartCoroutine(Patrol());
 }

 IEnumerator Patrol() {
  while (gameObject) {
   // implement a patrol
   characterController.Move ...
   yield return null;
  }
 }
}

in other words do a bunch of setup in the component

undone coral
undone coral
undone coral
undone coral
undone coral
fresh salmon
#

Whoa there, you've pinged them 6 times already

#

Either use one long message or turn it off after the first

undone coral
#

@tawny otter it sounds like you are suffering from scenitis. everything you are describing sounds like "We have a bajillion scenes and it sucks." the simplest solution is do not use scenes. use prefabs instead wherever you are using scenes, and author the light 20 lines of code you need to do level loading with prefabs

fresh salmon
#

And that makes 7

obsidian glade
undone coral
#

you cannot decouple your game the way you think you can. WaitForSeconds isn't going to "sync" ever

obsidian glade
#

sounded like he's trying to do the opposite, make calls that don't happen at the same time, but will run in order with sufficient space between them

gaunt zinc
#

Thats what I tried to do as an alternative, as yeah, waitforseconds never comes out exact. But if theres a way to ensure it does, having the extremely computational expensive interpolation won't be needed

gaunt zinc
#

Which might result in something worse than waitforseconds. I will try that out though. Also the script1 script2 method, but that means breaking the coroutine into a lot of fragments, i tried it and its very confusing

undone coral
#

it sounds like you have two spawners you want to spawn "at the same time"

#

in some kind of tower defense or ARPG sort of game

#

is that correct?

gaunt zinc
#

Actually no, lets say i want to spawn like 10 things 0.05s after another

undone coral
#

computational expensive interpolation
of what exactly?

#

what is your game real quick

gaunt zinc
#

Given a really laggy scenario, you will see different gap between each ball

undone coral
#

do you mean, "Summon 10 Skeletons over 0.5s"

sly grove
undone coral
#

"Summon 10 balls over 0.5s"

gaunt zinc
#

If i do fixed update method it will be even more hard code

undone coral
#

let's try expressing what you want more accurately

sly grove
#

There's a fun little thought experiment about how do you make a machine gun that shoots 100 bullets per second when you only have 10 frames per second.
The answer is you need to spawn 10 bullets per frame, and space them out positionally within the frame as though they were spawned 10 ms apart

gaunt zinc
#

So basically, I just want wait 0.05s actually be 0.05s regardless of frame drop

undone coral
#

because right now you are doing
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05
wait for seconds 0.05

which has the chance of being off from 0.5s by time of frame*10, which is a lot if it's, e.g. 20 fps, or a whole half second

undone coral
#

is that the user screwed up his Gamese

sly grove
#

this is what you need:

float timer = 0;
float interval = 0.05f;

void Update() {
  timer += Time.deltaTime;
  while (timer < interval) {
    timer -= interval;
    SpawnASkeleton();
  }
}```
undone coral
#

"Shoot 100 bullets per second" is a lot better than "Shoot 1 bullet every 1/100th of a second"

gaunt zinc
undone coral
#

do you see @gaunt zinc ?

sly grove
#

Which means in my while loop above, you'd need to track the sub frame timing. it's not that bad

#

just some simple math

#

it's already kinda being tracked by timer

undone coral
#

it was killer for my car driving thing

sly grove
#

Yeah! I've done the same for VFX graph as well

gaunt zinc
#

When it comes to bezier and AI, moving it gets pretty bad

sly grove
#

I did a graph without it and got weird fixed timestep artifacts

undone coral
#

even at 60 fps, spawning something moving 40 m/s is going to have huge gaps

undone coral
#

you are just feeding the t into a bezier function

#

don't overthink it!

gaunt zinc
#

To get the time difference

undone coral
#

no

#

if you want things to keep working as coroutines

#

you will have to create a custom yield instruction, a replacement for Time.time and Time.deltaTime, and follow a lot of rules about what context you are in - like how to coordinate this across multiple coroutines

#

subframe timing decoupled, implemented as a coroutine yield instruction, is very hard

#

much harder than what PraetorBlue is showing you

#

however i see that you want to keep your very expressive coroutines

gaunt zinc
#

I am only giving a very simple example, in reality, there will be different intervals, different calls, different events which is almost impossible to do inside a update or fixed update

#

aimConstraint.weight = 0f; StartCoroutine(StunLock()); StartCoroutine(SpearStorm()); animator.SetTrigger(triggerHashes[8]); animator.SetTrigger(triggerHashes[0]); yield return new WaitForSeconds(7f); animator.SetTrigger(triggerHashes[6]); animator.SetTrigger(triggerHashes[0]); animator.SetBool(triggerHashes[7], true); yield return new WaitForSeconds(0.7f); GameObject[] newImpactEffect = { impacteffectsDatabase.Items[1] }; Vector3[] newTR = { Vector3.zero }; Vector3[] newScale = { new Vector3(0.8f, 0.8f, 0.8f) }; int[] noPool = { -1 }; AdvancedWarning warningScriptAim = SpawnWarning(effectsDatabase.Items[9], textureDatabase.Items[0], textureDatabase.Items[1], textureDatabase.Items[3], 15f, 30f, 4, 4, 0.8f, baseHeight); warningScriptAim.LockToObject(transform, true, true, false, false, Vector3.zero, Vector3.zero); warningScriptAim.SetAutoFlip(0, true, true); warningScriptAim.SetAim(playerHeading, true); warningScriptAim.ShowIndication(); yield return new WaitForSeconds(0.4f); AdvancedWarning warningScript = SpawnWarning(effectsDatabase.Items[11], textureDatabase.Items[4], textureDatabase.Items[5], textureDatabase.Items[6], 15f, 30f, 4, 3, 1.5f, baseHeight); warningScript.LockToObject(playerHeading.transform, true, true, false, false, Vector3.zero, Vector3.zero); warningScript.QueueFlipBoth(0, 0.12f, 0.12f, 0.2f); warningScript.transform.localScale = new Vector3(6, 6, 6); warningScript.ShowIndication(); warningScript.SetImpactEffect(newImpactEffect, noPool, newTR, newTR, newScale); yield return new WaitForSeconds(0.3f);

#

the real method is probably 10 times longer than this

gaunt zinc
jolly token
#

Magic numbers everywhere

gaunt zinc
#

xd true spagetti

sharp lake
#

this should be in code beginner or something tho

gaunt zinc
#

im just giving example of what is there to come

obsidian glade
gaunt zinc
#

i am not using interpolation of any sort but all things inside are desynced when it gets laggy

gaunt zinc
#

or a structure where coroutine calls for events for something else to spawn on the same frame

#

I will try each of the steps you all suggested and see which one works best

#

Thanks again!

gaunt zinc
livid zephyr
#

Hey guys! I have a coroutine set up that turns objects red when the ray from the camera is within distance and the object is standing still, but currently the objects turn red and then return to normal after the ray is no longer pointing towards it

#

I just want the object to stay red once it has faded to red completely

#

here's my code

#

Can anyone assist me?

obsidian glade
livid zephyr
#

Here is the code for the Zone object

#

The color is not for the zone, thats just the color of the ray line

obsidian glade
#

on line 78?

#

if (_currentHitZone) _currentHitZone.IsHit = false;
why set this to false again if it only matters once it's been hit?

#

perhaps the error is somewhere else, but it looks strange to me

undone coral
#

it's unavoidable

#

the core problem is you are expressing it wrong

#

you want to have a certain number N per long unit of time

#

that's how you should be thinking about this

gaunt zinc
#

It's an example saying how complex each step can get so it's not ideal to put inside an update loop.

#

A better example would be like one of those space shooter game, but the bullet is going to make like a flower pattern

#

When not laggy, and each bullet is fired evenly, it will make the flower alright, but when laggy, the flower comes out distorted

#

Whats happening in my game, is the character will play an recorded animation clip, and it will do some sort of attacks when lets say, when it raise it's hand

#

When the clips get long, the attacks comes out late

#

Also yeah it needs to also make a pattern

undone coral
#

you can keep doing this in a coroutine

livid zephyr
undone coral
#

it's pretty complicated though

gaunt zinc
#

Yeah i forgot you can add event in animation clip...

#

Might try that instead

#

And see how good is it

timber flame
#

I have a question. When there are multiple sources in path finding algorithm (A star), I start from a source point and if I reach another one, set g cost to zero (reset) for this node, is it enough to find the optimal path from multi source point?

 private int ComputeWeight(int g, Node node, Vector3Int direction)
        {
            var p = node.Point + direction;  // p is a neighbor of current node
       
            if (_sourcePointSet.Contains(p))
            {
               return 0;
            }
            //...
        }
  var gCost = weightFunc(currentNode.GCost, currentNode, direction);
  if (_openSet.TryGetValue(neighborPoint, out var neighbor))
  {
    if (gCost < neighbor.GCost)
    { 
         neighbor.GCost = gCost;
         neighbor.Parent = currentNode;
         _openList.UpdatePriority(neighbor, neighbor.Priority);
    }
  }
  else
  {
  
rough sky
#

I'm making a custom property drawer (a lil rusty at it), and I can get the scriptable object to render, but I cannot get its name underneath, it says it is a null property

#

am I doing something wrong?

#

Top is the classes, middle is output, bottom is rendering code

#

and the custom property drawer is for the colourSchemeSelection class

#

nope, doesn't seem like you can access scriptable object properties in this way

undone coral
#

is there some kind of special affordance for multiple cameras in Built in Render Pipeline that isn't available in URP or HDRP? specifically related to how much more performant realtime reflection probes are - if i do not use the "scriptable" features of built in render pipeline, can the same (or a lot of the same) CPU work be reused for all the cameras? clearly this is not the case for HDRP, based on the timeline, and clearly there is some CPU work done for the reflection probe, but not nearly as much as HDRP or even apparently URP

#

my goal is to author a local multiplayer game with split screen

#

i would want to use URP, and i would want to reuse all the CPU work between cameras that isn't view dependent

#

or, even prevent using view dependent features (like depth mapping)

rough sky
#

Makes sense

regal olive
#

does burst work with multidimensional arrays like array[,,,] read and write. no resize

sly grove
regal olive
#

thank you

sly grove
#

multidimensional arrays are just syntax sugar for single dimensional arrays anyway, so you can accomplish what you need with NativeArray

regal olive
#

i use multidimensional arrays as maps within maps so if i convert them array[x,y,n,d] would be really hard to do operations on and would introduce more complex math.

regal olive
#

thanks.

honest frost
#

Is there a guide for what kinda questions belong in #💻┃code-beginner and what kinda questions belong here

jolly token
honest frost
#

are render textures considered a beginner or an advanced topic

#

guessing beginner

kindred wyvern
honest frost
#

okay, so this is sorta for uncharted territory

#

gotcha 👍

kindred wyvern
#

In theory, anyway.

honest frost
#

ty for the info

gusty talon
#

but I think it's a pretty common thought

gritty nacelle
#

Hey there, not sure where else to post this, but Unity appears to freeze on Reloading script assemblies about one out of four times. Since Unity does that step 2 times for each code change, that means I can on average change two lines of code before I have to force quit and reload Unity. I do not think this is acceptable, and I'm wondering if there are any good debugging steps to figure out WHY it does that (that don't involve just deleting packages and seeing if it's better).

#

Like, since it freezes ( not crashes), I can't even get to a crash log, yknow?

narrow hearth
#

Hey

I have a scriptable object, where I want to be able to put a script in the inspector, I found the MonoScript type which works for the inspector.

The script I put in that slot, will always inherit from an interface 'Card_Behavior'.

Problem is that when I later, in another script, reference it, I want to call a function under the Card_Behavior interface, but it isnt marked as inheriting from Card_Behavior.

Ive tried casting the variable as Card_Behavior, but that didnt work.

I once followed a Sebastian Lauge tutorial where you could make sure, in that case, T inherited from IHeapItem.
Can you do the same for the MonoScript type in the scriptable object script?

Something like the last image.

sly grove
#

You want to use an abstract class or interface as your field type

narrow hearth
sly grove
#

Just use Card_Behavior as the field type.

sly grove
#

did you try it?

narrow hearth
#

ye

sly grove
#

what did you try?

#

interfaces show up just fine

#

as do abstract classes

narrow hearth
sly grove
#

code

narrow hearth
sly grove
#

(btw C# uses PascalCase for classes by convention)

narrow hearth
sly grove
#

Sure you don't have compile errors?

#

Interfaces work fine for me

narrow hearth
#

Yea i think i do

#

nothing pops up in the unity console

sly grove
#

Oh you know what I'm thinking of? GetComponent

#

which works fine with interfaces

jolly token
sly grove
#

You can use an abstract class

jolly token
# narrow hearth

Unity inspector does not support interface serialization out of box afaik
Field type has to be derived from UnityEngine.Object class to drag-drop
You can use MonoBehaviour or UnityEngine.Object to accept any type, but then you need to drag-drop exact component

#

So maybe use GameObject reference with GetComponent

#

Or abstract class derived from MonoBehaviour as Praetor suggested, whichever works better

sly grove
#

Eh I'd never use a GameObject reference with GetComponent

#

always reference the component directly 😉

#

especially if you want type enforcement in the editor

warm mica
#

^

jolly token
#

True 😌

narrow hearth
sly grove
narrow hearth
#

Im gonna go to bed now, Ill look at it tomorrow, but thanks for the help so far

potent shoal
#

There is a game I played 12 years ago, and they had a really cool cross hair

#

The blue circle is where my mouse is

#

The + is where my gun is aiming.

#

It helps guide you, and I want to create something like this

#

Does anyone know anything about how this is done?

sly grove
#

Which part are you not sure about?

#

There's a lot of pieces to this

potent shoal
#

I don't know how to make that circle

sly grove
#

Use a LineRenderer

potent shoal
sly grove
#

generate points on an Arc between the two points using the equation for a circle

#

ok we get it...

potent shoal
#

i see

#

oh....!

#

So determine the distance from ship to mouse pos, then determine the position in front of the gun the same distance, and then draw a circle line between the two points

#

I get it, that's what I needed

#

Thank you!!

sly grove
potent shoal
#

I see!!

#

Thank you so much @sly grove

drifting vessel
#

Suppose I have an environment similar to Minecraft. And in this environment, I have a room made of blocks. How would I determine if this room is airtight?

#

Is there an algo for that?

sly grove
#

BFS/DFS

#

it's just a graph

drifting vessel
# sly grove BFS/DFS

Will this work for rooms of an unknown size? Players are allowed to build their own stuff, so..

sly grove
#

Why wouldn't it?

drifting vessel
#

Dunno, just asking. Good jumping off point for googling, thank you.

drifting vessel
# sly grove Why wouldn't it?

Right, so I think the term I'm curious about is the "queue". If the room is an unknown size, the effectively the queue is potentially infinite. Say I have a hollow sphere, and I need to know if said sphere is airtight. How long should it continue to scan before it determines that it's not airtight?

#

There has to be a limit to how made nodes I check, right?

sly grove
#

in computing

#

but yes if the room is extremely large, you may end up using a lot of memory to do the search.

#

For practical purposes you should set a limit on maximum room size

drifting vessel
#

I could jobify this

#

Although this doesn't seem speed-limited. By what you're saying, this is memory-limited

sly grove
#

perhaps - it would require large modifications to the algorithm - perhaps some kind of spatial partitioning

#

well it's both

#

but in a practical sense you should be able to do a DFS of a few hundred to a few thousand nodes without much trouble.

drifting vessel
#

Yeah, the player would be able to partition the space by using airlocks or something.

#

This helps a lot. Appreciate you.

undone coral
drifting vessel
gaunt zinc
#

Start from somewhere thats air and see if it can reach all other airblocks

onyx violet
#

Hi there
does anyone know a way to calculate the angle of an area corner (let's say its a 2D plane) that's facing inside the area?

#

like, how do I determine if the angle is facing inside or outside an area

shadow orchid
#

if angle is less than x == true, else false?

#

gonna need to be more specific

fervent sage
#

What is best practice for conditions in a while loop in a coroutine you will be wanting to go indefinitely unless canceled externally?

#

Anything like checking if your application is quitting?

regal lava
#

If you're going to check for multiple different conditions you might as well just cache the reference to stop, or assign a bool.

narrow hearth
plush elk
#

hey guys I am using this to setup the position of a tranform to use it as shooing point, I am having a problem that when the camera starts moving or when it stops it makes a jerky movement

if(Physics.Raycast(ray,out RaycastHit raycastHit, 999f,aimColliderMask)){
  Vector3 CursorAimPosition = Vector3.zero;
  screenCenterPoint = new Vector2(Screen.width/2f, Screen.height/2f);

        Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
            CursorAimPosition = raycastHit.point;
        }
boreal agate
#

Anyone know about SQLite4Unity plugin?

abstract hill
#

Hi everyone, does anyone know if the Unity JsonUntility serialiser has a file size limit?

I am using Unity to generate a large file (over several gigs), this takes just over an hour to generate. Once I try to serilaise and save it however it the editor crashes completely.

The logs give this error:

=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries 
used by your application.
=================================================================

I this is potentially could be something to do with threading (I was saving on a serpate thread in the first place, but this worked for smaller files), but I have since removed the threading functions this. While I am generating a new file to test without this threading code, I just wanted to check incase there is a file size limit

regal lava
#

Ya try it with newtonsoft?

compact ingot
#

json is certainly not supposed to be several gigabytes in size

#

if you need to serialize really large data sets you need to make sure your serializer and data format can be constructed incrementally

abstract hill
#

Ill look into seperating the file up then into chunks. And saving them that way.

flint sage
#

You should really just look into different data formats

abstract hill
#

I'd rather not have to write my own file converter as the project isn't really my roll to develop, though if there is another way to save and load files while having them convert to C# classes on load then I would be intrested to see

compact ingot
#

first it'd try if Newtonsoft JSON (also called Json.NET) has the same issue

#

if it does you could look at LiteDB or SQLlite to store your data in a robust way (the database file is your serialized data)

#

alternatively try MessagePack (essentially binary json) that could reduce the file size overall and be a lot faster

#

do NOT use Binary Formatter (unless you like huge files, insecure code and slowness)

abstract hill
#

Ah thank you, Ill have a look into each! ^-^

undone coral
#

maybe we can talk about how to store the data for how it makes sense for you

#

sqlite is good but it might be too slow if this is e.g. some kind of motion capture data you are saving at 100hz

#

or if you are going to run out of memory trying to buffer it and write it later

livid zephyr
#

Hey Guys! Im trying to find the distances between one camera and multiple objects and want the camera to turn on once the object the camera is attached to is within a certain distance between it and the any one of the multiple objects

#

I know we can use Vector3.Distance

sly grove
livid zephyr
#

🤔

abstract hill
# undone coral what is your application?

The application is about the playback of player movements of a football game using AI (its for a research project) real time playback usign the AI is too slow, so isntead we opted to generate the movement using the AI outside of the real time showcase. This way we would play the hours+ worth of tracking data, generate the movements and the for each player store the location of their bones (only the necisary ones (totalling at 29 bones per player with 22 players)). This works fine for shorter clips, but with 1 hours games at 60 frames per second (which is the framerate the AI is trained to run at) the filesize is a bit insane.

sly grove
#

so if you're trying to store a string in memory like that, it's a bad time

#

you'll probably want to switch to a different JSON serializer that has streaming capabilities

#

like Newtonsoft JSON

#

so you don't have to store the entire string in memory at once

livid zephyr
abstract hill
#

Ahh ok, I have used Newtonsoft breifly before, but only in passing, is there a perticular way that it is needing to be setup to perform this save correctly?

sly grove
#

yes use the streaming apis

abstract hill
#

Ah okay thanks, Ill have a look

sly grove
#

that example is for deserializing but serializing is similar (just opposite)

abstract hill
#

Gotcha, thank you

#

Im just looking for the package nwop

sly grove
#

Here's a code snippet from one of my projects:

                JsonSerializer serializer = this.serializer;
                using var fs = File.OpenWrite(path);
                using var gs = new GZipStream(fs, CompressionMode.Compress);
                using var sw = new StreamWriter(gs);
                using var jw = new JsonTextWriter(sw);

                serializer.Serialize(jw, Career);```
abstract hill
#

Thank you ^-^

undone coral
#

thank you for sharing and please post a link if you guys already have a preview of this!

#

there are fortunately many "fast" json formats

#

that you can add to your ETL pipeline

proven venture
#

doesn't ml agents have a way for this?

undone coral
#

@abstract hill since it is bones, you can convert the JSON to FBX animations (hard) or alembic (easier) too, besides JSON, and there are built in importers in unity. runtime alembic importing works very well. it always loads alembic files at runtime, and they can be played back at any speed and pretty robustly, whereas runtime FBX you'll have to use trilib. if you already have a good JSON workflow, you can drop in replace with BSON (a binary representation of json that json.net supports already) - bson supports streamed reads of an array-of-bson documents.

#

@abstract hill i direct messaged you a demo of alembic with high fidelity bones and meshes playing back in real time. it's a multi-gig file running at 60fps

undone coral
#

i think keiishkii means he has a separate system that reconstructs video game type animations from live action video

#

and right now that system writes to a JSON format

proven venture
#

i was thinking of imitation learning 🙂 but recording and playback of movement is another beast

abstract hill
abstract hill
undone coral
abstract hill
#

Yeah, I'm definalty intresxted in this. Thank you

undone coral
abstract hill
#

Thank you ^-^

humble dawn
#

Hey, I'm trying to serialize and store a quaternion and then read it and apply it to a transform. When I'm doing this, the y axis seems to get a -90 everytime. Any idea what's happening here? I thought Quaternions aren't supposed to have problems like this. Basically, in the editor I see the object's y axis rotation as 120. But when I save and then load the quaternion, the object's rotation is now 30.

humble dawn
#

I'm using a serializable version of Quaternion from a Unity answer. This is the operator overload -
public static implicit operator SQuaternion(Quaternion q)
=> new SQuaternion(q.x, q.y, q.z, q.w);
Is this an okay way to copy quaternions?

compact ingot
humble dawn
#

My code's in multiple files so it's not easy to show. For now, does this answer's way of having a serializable quaternion and also the operator overloads seem correct?

humble dawn
#

Whoops, turns out the problem was the rotation set on the object in the inspector by default. Code's all fine. Thanks anyway 🙂

noble stream
#

Hey, I face a bizzare issue. I do 'OrderBy' on list with custom Comparer, basically I just compare the positions. The point is, the OrderBy looks to behaviour different on Editor and on Build. On the Editor, it doesn't invoke Compare on the same object in list, but on build app it does. When I do

    {
        if (x == y)
        {
            Debug.LogError("Same!");
        }```
In the editor I didn't receive this logs but on build they appears. Do you notice something similar or have a clue what could happen here? I'm sure that I check the same things on build and on the editor.
abstract basalt
sly grove
#

OrderBy will never compare the same ordinal element to itself

#

(assuming you haven't overridden the equality operator on that type)

quartz atlas
#

Hey I am trying to get ScreenToWorldPoint(Input.mousePosition) to be same on client and server with netcode for gameobjects but for some reason whenever I change windows size of host or client it adjusts only for host. So Client gets wrong coordinated. Anybody got this issue already?

sly grove
quartz atlas
#

I am making drop option from inventory. Everything works fine on host. It drops the item under my mouse when i drag it. But on client it drops off map. I tried changing window size of host and dropping it on same spot on client and when I changed either client or host window size it kept changing

#

e.g. (-1790.00, 232.00, 0.00) changed to (-1377.00, 174.00, 0.00) when I dropped it on client after resizing host's window

sly grove
#

If you're dropping something into the world, you should simply be using that world space coordinate you dropped it to

#

The ui stuff should never be communicated over the network

quartz atlas
#

I have my inventory attached to player prefab. Whenever I call drop it get's camera of that player and calculates world position. After that I call Rpc to spawn item with those coordinates

sly grove
#

Sounds like you're using screen space instead of world space

#

you shouldn't need to do the ScreenToWorldPoint anywhere except on the machine that the object was dropped from

quartz atlas
#

Yeah. I have InventoryManager on player prefab that first gets the drop position and it uses camera attached to player dropping it. Then it calls Rpc that spawns the object

#

Interestingly when I debug it in update after clicking with mouse it shows correct coordinates. But I can't find anything that could change it in my get coords function

noble stream
noble stream
# abstract basalt What does that equality operator look like?

I actually don't have a problem with comparison, just surprised me a difference in editor vs build. I will try to check it on some more generic case and maybe I will able to provide an example with source code. My comparation looks like this ``` public int Compare(StorageSlot x, StorageSlot y)
{
if (x == y)
{
Debug.LogError("Same!");
}
var first = x.transform.localPosition;
var second = y.transform.localPosition;

    if (first.y > second.y)
    {
        return 1;
    }
    if (first.y < second.y)
    {
        return -1;
    }
    else
    {
        if (first.z > second.z)
        {
            return 1;
        }
        else if (first.z < second.z)
        {
            return -1;
        }
        else
        {
            //There should not be the case when position are equal
            if (first.x > second.x)
            {
                return 1;
            }
            else if (first.x < second.x)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
}```
analog nexus
#

How do I either schedule a task for the main thread or run a continuation on the main thread

abstract basalt
analog nexus
#

I guessed I need to use task factory and the unity synchronization context somehow

sly grove
analog nexus
#

Basically I get a callback from filesystem watcher that is on the wrong thread and I want to schedule the handler on the main thread

#

I tried await task.delay.cinfigureawait false but that was not doing it.

#

I'm not using unitask

#

I thought I had that solved for a websocket callback in a previous project once 🤔

sly grove
analog nexus
#

I don't want to poll

sly grove
#

e.g.

ConcurrentQueue<something> queue = new();

void Update() {
  if (queue.TryDequeue(...)) { // do something }
}```
sly grove
#

whether its your code or someone else's

analog nexus
#

That might be true

sly grove
#

Maybe look into UniTask if you want something cleaner

analog nexus
#

But if possible is like to use the async/await abstraction over that

sly grove
#

yeah definitely UniTask then 😄

untold lark
sly grove
untold lark
sly grove
#

and in the right channel

analog nexus
#

@untold lark namespace needs a { } block

#

The error is pretty clear?

sly grove
#

would be more clear with a configured IDE

untold lark
#

Name space {unityEngine.Rendering.player}
Like that?

honest hull
#

Is there any way to do bindless textures in unity?

analog nexus
#

@untold lark ☝️

#

Suggesting to check Microsoft docs first

noble stream
# abstract basalt I was wondering if float equality was evaluating differently depending on compil...

Actually there is nothing wrong with a this comparasion (previously I had a bug, when a missing returning 0, when x are equal), but what makes me wonder is that when I do "the same" check, in the editor I get nothing, but on build a have a logs from it. I did some more generic check and with this piece of code, in editor I don't receive this "Same!" log error, but in a build it appears ```using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ObjectComparationTest : MonoBehaviour
{
private void Awake()
{
List<GameObject> objects = new List<GameObject>();
for (int i = 0; i < 10; i++)
{
objects.Add(new GameObject(){name = $"obj + {i}"});
}
List<GameObject> ordered = objects.OrderBy(s => s.gameObject, new ObjectPositionComparer()).ToList();
}
}
}```
ObjectPositionComparer - looks like previous

#

On build I have this log which not appear on editor Same! UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:LogError(Object) SlotPositionComparer:Compare(GameObject, GameObject) System.Linq.EnumerableSorter`2:CompareKeys(Int32, Int32) System.Linq.EnumerableSorter`1:QuickSort(Int32[], Int32, Int32) System.Linq.EnumerableSorter`1:Sort(TElement[], Int32) System.Linq.<GetEnumerator>d__1:MoveNext() System.Collections.Generic.List`1:.ctor(IEnumerable`1) System.Linq.Enumerable:ToList(IEnumerable`1) ObjectComparationTest:Awake()

abstract basalt
abstract basalt
noble stream
noble stream
sly grove
#

(only with new input system)

#

If not using new input system you would need to use a native plugin

undone coral
#

the list is sorted

#

it does indeed compare the same element to itself

#

this might be related to a stable sort feature. i'm not sure.

noble stream
#

yeah it is, I'm not sure that I can name it as bug/issue, but it's definitely bizarre behaviour.

#

I would like to know what exactly cause it because it gives me a hard time to find one issue before. Basically just curiosity 🙂

abstract basalt
#

I doubt they guarantee any particular implementation, provided the external result is the same and it matches the algorithmic complexity.

#

that said I kind of doubt it's intentional, spells like an off-by-one error

noble stream
#

So it basically nothing specific Unity related

abstract basalt
#

Might be somewhere in mono, did you try il2cpp?

noble stream
#

Yes, my main project is in il2cpp and there was my main testing resource, the second one test project is in mono

crude mural
#

Does anybody know when Unity gonna support .NET 6.0?
At least approximately prediction?

weak herald
#

Hey, anyone here have a cool "Savegame" system? I'm designing a refactor for my save system, (currently using playerprefs). Anyone wanna talk design?

crude mural
weak herald
#

Oh cool, let me read through it

#

this free to use? or you charging lic

crude mural
weak herald
#

thanks buddy, I'll take a look through. Will probably use for inspiration, but good to know I can copy sections out of it 😉

crude mural
#

You may just install it as package and extend classes if you need. Using UPM packages is very comfortable thing

analog nexus
# analog nexus How do I either schedule a task for the main thread or run a continuation on the...

follow up to my question yesterday. I found this way to run a task on the main thread:

// remember unity task scheduler while on main thread
private readonly TaskScheduler mts = TaskScheduler.FromCurrentSynchronizationContext(); 

private void OnChanged(object sender, FileSystemEventArgs e) 
{
// here we are on a worker thread called from a FileSystemWatcher callback
  UnityEngine.Debug.Log("outside " + System.Threading.Thread.CurrentThread.ManagedThreadId);
  Task.Factory.StartNew(
                    () =>
                    {
                        UnityEngine.Debug.Log("inside " + System.Threading.Thread.CurrentThread.ManagedThreadId);
//now on main thread
                        OnFileChanged(file);
                    },
                    System.Threading.CancellationToken.None,
                    TaskCreationOptions.None,
                    mts);
}

does this look like a terrible idea? UniTask is doing something else

tender light
compact ingot
analog nexus
#

I'm hesitant to pull it in as a dependency

compact ingot
#

why?

analog nexus
#

it seems pretty intrusive and a complex codebase

#

I'll have to convince my team it is worth it

flint sage
#

It's not more intrusive than whatever you're doing now

compact ingot
#

its completely optional to use it, you can keep doing what you are doing AND use it on demand

#

and it is by no means complex, it basically just wraps the notion of asynchronous processes into something that could be described as a domain specific language (just like LINQ captures the notion of a data query)

#

and it gives you access to doing all this correctly in a very robust way where all the edge cases have been considered

#

its also not UniRx which would be way more intrusive as it would immediately require you to change your architecture to make good use of it

#

tbh, if your team doesn't see a problem with how you're describing async processes in your projects rn, you can't convince them really why UniTask would be better, maybe trying to DIY a better way (based on your specific pain points) is what is necessary to really appreciate how good it is.

tall briar
#

What are some of the best Unity vids I should watch, especially coming from Unreal? I want to level up my 3D Unity game real quick today

sturdy edge
fallen sentinel
#

Hey guys I’m looking for a Senior Unity Dev to help my studio make a transition from Unreal to Unity. Anyone know a good place to hire unity mobile devs?

flint sage
#

Not here

abstract folio
analog nexus
#

We are already using System Tasks a lot

#

So moving to unitask would be a bigger refactor

jolly token
#

You don't have to replace everything with UniTask

analog nexus
#

Right

#

Btw the solution I have for the time being is inspired by this https://thomaslevesque.com/2015/11/11/explicitly-switch-to-the-ui-thread-in-an-async-method/

jolly token
# analog nexus Right

This is bit old, but there is documentation and you can do something similar as UniTask
https://github.com/modesttree/Unity3dAsyncAwaitUtil

public class AsyncExample : MonoBehaviour
{
    async void Start()
    {
        // Unity thread
        await new WaitForBackgroundThread();
        // Background thread
        await new WaitForSeconds(1.0f); // Or WaitForUpdate
        // Unity thread again
    }
}

The original blog post is deleted but you can still see from Documentation folder

honest hull
#

Is there an alternative to bindless textures in unity, since unity doesn’t support bindless textures?

regal olive
#

Hey, how can I recreate Fez's 3D rotation mechanic in Unity?

honest hull
#

I need a way to sample an unknown amount of different sized textures from a compute shader

honest hull
#

I don’t use shadergraph

honest hull
#

that requires the same sized textures and the number of textures to be known at runtime

abstract folio
crude mural
brisk pasture
#

does anyone know how to enable nullable reference type support in just one assembly definition of a project?

jolly token
brisk pasture
#

yeah its what is already going on

#

was hoping like a css.rsp in the asmdef folder would work but no luck

true plume
#

Hello guys
I have a question

I have a template class like this

public abstract class ASetChatMessage<T> : MonoBehaviour
    where T : AChatMessage
{
    [SerializeField] protected T chatMessage;
    public Sprite Avatar => chatMessage.Avatar;
  ...
}

public class SetChatMessageMedia : ASetChatMessage<ChatMessageMedia>;
public class SetChatMessageText : ASetChatMessage<ChatMessageText>;

AChatMessage class is also an abstract class (public class ChatMessageMedia : AChatMessage for example)

How to do that ?

private ASetChatMessage<???> a; // How??
private SetChatMessageMedia b;
a = b // How??
a.Avatar.gameObject.SetActive(false); // How??
fresh salmon
#

You can't. To make this work you would need another base, abstract class that ASetChatMessage<T> inherits from

#

Then you'll be able to store "any deriving generic" into that variable

#
private ChatMessageBase a;
private SetChatMessage b;
a = b; // now valid
#
ChatMessageBase a;
ASetChatMessage<ChatMessageText> b = new SetChatMessageText(); // maybe valid assignment?
a = b; // valid
true plume
#

Yes but I can't access to Avatar variable

#

(thank you for your answer)

fresh salmon
#

Extract it to the base class

#

Note that this comes with the caveat that you won't be able to extract protected T chatMessage to that base class as T doesn't exist there. Shouldn't pose any problems though, if you need to do operations on it from the outside (like call a method on the base class that gets its value at some point), you can make an abstract method on the base class, and directly override it in the generic base class

true plume
#

I think I have an idea, ill try something

livid zephyr
#

Can you make a nav mesh agent travel to many objects within a navmesh using SetDestination()?

#

By putting it in a foreach loop and setting the.new destination position at every instance of the loop

brisk pasture
#

you would wait till it reaches destination then call the SetDestination with the new Destination

somber swift
shadow orchid
#

can just queue up destinations in a list

somber swift
#

Yeah, why not. Just meant NavMeshAgent component doesnt do that automatically for you

steep robin
#

Hi, I'd like to know if someone know how to deal with scene reloading with Zenject

#

if I modify a script when a scene is running, context get lost and everything stop working

#

I think there should be some way to restart the injection process

stuck onyx
#

Is it possible to know by code which device are we simulating with the device simulator ? I tried SystemInfo.deviceModel but always returns my macbook name

#

okay must use : UnityEngine.Device.SystemInfo

rich cypress
#

Im having an odd behavior, 2 instances of the same script with lerp, update the values of the other script with no reference to each other?

#

How is that possible

regal glade
#

I'm trying to store levels in json format but they end up being around 50-1000 MB in size which is a bit of an issue, is there a better way to export a class than plain text that might compress the size somewhat, and if so where do I look?

#

read something about POCO, is that worth investing time into? i'm just not sure what to look for other than trying to convert it all to binary or something

wary swift
#

50-1000mb seems a bit much
How many objects are you trying to save?
Are you sure you're doing it right?
Does the unity scene file of these levels even come anywhere near this filesize?

regal glade
#

@wary swift i have a 3D array of tiles that contain various information, and the array might be like 500*500*50. The scene doesn't contain any of that information as I'm just creating the data with programming right now, but I'm trying to create a level editor to save and load physical maps to load into the engine later.

#

I'm rendering the tiles on a quad only

#

i turned off the "pretty text" and reduced all my variables to 2-3 letters and it shaved off a lot of file size but i still think it's not entirely viable.

wary swift
#

An array of 50050050 would be 12.5 million elements so getting file sizes like that would make sense
Are you sure you need to store that data or can it be regenerated by a some form of random function?
Leaving json for "normal" serialization is something I'd do as well

regal glade
#

i do need to store the data, it's just information for buildings and such that are placed tile by tile, much like a minecraft level

#

but there are more things i can do to cull data written a lot

#

though i still need to get it down a bit thats why i was asking about alternate ways to export

#

like hex or something idk

#

this is a bit new to me

#

for example im exporting empty tiles now and they take up as much information as a placed tile, so that should reduce size by massive margins

upbeat path
regal glade
#

yeah i did think of that but i think changes in the earlier steps is warranted first 😛

livid zephyr
livid zephyr
#

'''

wary swift
scenic forge
#

Depends on the nature of your data, you can also rearrange your data structure to make it a lot more repetitive and thus compressible

#

But honestly don't reinvent the wheel unless none of the mentioned solutions work for you.

livid zephyr
#

Can you make a nav mesh agent travel to many objects within a navmesh using SetDestination()?
By putting it in a foreach loop and setting the.new destination position at every instance of the loop

#

This is the code that is suppossed to take care of that

livid zephyr
livid zephyr
# upbeat path Is this for patroling?

Not really, I have a Helicopter where i want it to automatically travel to zones I have set up in my scene and reveal them when its raycast hits the invisible zones. In a sense, im building flying AI and wanted to use a navmesh

upbeat path
#

what you can do is put your loop inside a Coroutine and then after the SetDestination use a yield WaitUntil remaniningDistance < 0.1f
for example

livid zephyr
#

this is the code i have so far

regal glade
#

@scenic forge thanks, no i don't need JSON it was just the first think i knew about how to use more less. thanks i'll look into these.

upbeat path
# livid zephyr this is the code i have so far

So something like this

IEnumerator Fly() {
            NavMeshAgent agent = GetComponent<NavMeshAgent>();
            foreach (var zone in zones)
            {
                zoneClosestToApache = GetClosestZone(zones);
                agent.SetDestination(zoneClosestToApache.position);
        yield return new WaitUntil(() => agent.hasPath && agent.remainingDistance < 0.1f);
            }
}
livid zephyr
somber swift
crude mural
steep robin
crude mural
#

You are free to Unload and Load the scene back as many times as you need. Everything gonna be fine, until you have cross scene connections

#

If you have cross-scenes injections, you may need to split "that" gameobjects to dedicated scene, and never Unload it.

steep robin
# crude mural Maybe I didn't get a point of the question in that case

the case is: in the editor while developing. I'm running a scene to test it. I spot a bug, so I make a change in a script WITHOUT STOPPING THE SCENE. after saving the script, normally unity do a reload and you can continue testing the scene. the problem with zenject is that when this reload happens, injection get lost and is not triggered again

crude mural
#

Ohh, right. You won't do that with Zenject. Zenject was designed to be executed the first one in Awake method. You should stop the game, recompile code and press "PLAY" button again

sage radish
livid zephyr
#

I'm assuming because it still having that zone in the list and still thinks its the nearest zone

steep robin
steep robin
#

I'm gonna try Play Mode Settings

#

LOL...it seems that the problem is PlayMaker now... 😄

upbeat path
undone coral
undone coral
crystal galleon
#
        public Node CreateNode(Type type)
        {
            Undo.RecordObject(this, $"({GetType().Name}) Create Node");
            Node node = this.CreateNodeOfType(type);
            nodes.Add(node);            
            EditorUtility.SetDirty(this);
            return node;
        }

        public void DeleteNode(Node node)
        {
            Undo.RecordObject(this, $"({GetType().Name}) Delete Node");
            nodes.Remove(node);            
            EditorUtility.SetDirty(this);
        }
```Since the `Undo.RecordObject` already marks an object as dirty, as said in the `EditorUtility.SetDirty` documentation (`If you do want to support undo, you should not call SetDirty but rather use Undo.RecordObject prior to making changes to an object, since this will both mark the object as dirty`), why is it needed that I `EditorUtility.SetDirty` after adding or removing a node from the list? This topic is somewhat confusing to me.
livid zephyr
# upbeat path It could also be that the new path has not yet been found. try adding a yield re...
    private IEnumerator Fly()
    {
        NavMeshAgent agent = GetComponent<NavMeshAgent>();

        foreach (var zone in zones)
        {
            if(!zone.GetComponent<Zone>().hasBeenScanned)
            {
                Debug.Log("Moving to Zone");
                zoneClosestToApache = GetClosestZone(zones);
                agent.SetDestination(zoneClosestToApache.position);
                yield return null;
                yield return new WaitUntil(() => agent.hasPath && agent.remainingDistance < 0.1f);
            }
        }
    }
#

Like this?

upbeat path
#

yes

livid zephyr
#

Ok I added the if statement but ill remove it and see if it works without that

upbeat path
#

there are lots of edge cases which can occur with SetDestination so I would check out the documentation to make sure you are covering them all

crude mural
long ivy
#

sounds like details are leaking into the base class. Why not make an interface instead? Reading about the command pattern might be helpful for you

tough ore
#

Not sure if this belongs in #📱┃mobile or not. I'm trying to remove some frameworks from my iOS project with a [PostProcessBuild]. Does anybody have experience with that?

shadow orchid
#

is that the thing where it compiles in the background after making changes?

lethal flicker
#

Has someone here previously worked with any maps SDK? Specifically Bing Maps would be great. I've got questions that I can't find any answers to in documentations or elsewhere.

crude mural
smoky kite
#

Hey guys how do I change the organizations, in plastic scm? this project is in another organization i wanna switch up

nova dagger
#

I use this code: ```c
if (microcontroller.IsOpen)
{
recievedData = microcontroller.ReadLine();
Debug.Log(recievedData);
cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
}

to read serial data  from my arduino, it works however it takes a long time (like 5 seconds or more) for it to start changing according to the  value my microcontroller recieves
#

the variable microcontroller is a Serialport variable assigned to the correct port, with the correct baud rate

smoky kite
abstract hill
#

Hi everyone, I am running into an issue where Unity is running out of memory and crashing,
The TL;DR of what I am doing is creating files that are several gigs in size, I initially though the issue I was running into was to do with saving however it apears that its just the size of the class that is the issue.
I considered saving the class in stages, but I think that would cause alot of issues in terms of restiching the file back together at a later date for playback.

Is there a smarter way of dealing with classes several gigs in size, or is there an already implemented solution avaialble for this - I have considered saving things using SQLite, but I'd rather avoid rewriting everything I have already and getting that to work with the project if possible.

jolly token
abstract hill
#

Frame data for 22 characters transforms

#

Every bone is recorded. I know there is proberbly a better way of doing this, but for now I was just looking for an easy solution if possible

jolly token
abstract hill
#

Yeah, so the setup is:

  • Generate a file of movements (this is using playback data of over an hour long at 60fps)
  • Record the movements and store them in a class, basically a big class of CharacterData -> FrameData -> BoneData -> Position, Rotation, Scale
  • Save these to a file,
  • Load them in at a later date
  • Play back the file
#

I know this seems convoluted, but the trouble is the generation part takes so long as its using PFNN's, as such the idea was to preprocess everything, rather then generating them while playing them back. The only issue is that for times when the file spans for longer then an hour or so it starts to have issues (in this case the memory issue)

#

I had an issue previously about saving this data, where the string JSON string got to large, so instead I was aided in how to stream the saving of the data to and compressing it using NewtonSoft

#

So I was wondering, is there a simular way to work with large classes like this?

jolly token
brisk pasture
#

also how large is too large

#

strings can get pretty big and still parse just fine, just not recommeded since it will take longer to parse the json

abstract hill
#

Well the size is this
1.5ish hours -> 1.5h * 60m * 60s * 60f = 324,000,
Each frame I am recording 22 players each with 29 bones -> 638,
Each bone records ints transoform data, so position, rotaiton and scale (this is just an approximation but with each being a vector3 / quaternion and with is saying the 20 characters to record a vector3 (which I think is wrong but the estamate is fine)) thats still -> 3 * 20 -> being 60

On top of this each player also has some other data

But ignoring that, that means the JSON output will a minium, ignoring any {} and spaces, be a string of length 324,000 * 638 * 60
= Thats 1.2 * 10^10 characters

abstract hill
# jolly token You should not treat this big data as a single class/json. You should make them ...

I agree, though this is kind of what I was asking about for the better solition, I was thinking of having a seperate file with a list of paths to the other files, where each sub file would cap at around 5mins of playtime instead.
However, I wanted to see if there was a cleaner way of dealing with this first, as that would require a bit of janky code trying to figure out what index the player is on and when to load new files and such.

upbeat path
abstract hill
jolly token
upbeat path
#

no, I'm thinking of using a folder structure
CharacterName/Second/FrameNumber/bonedata files
one CharacterName folder per character
one Second folder per second to be recorded
one FrameNumber folder per frame of the second
26 files (one per bone) in the FrameNumber folders.
you could even be a bit clever and only write the bone data when it changes

abstract hill
#

Would that not require a file to be loaded every frame though?

#

Well alot of files loaded per frame

upbeat path
#

you could load them how you want

#

which is more important, save time or load time?

abstract hill
#

Load time, as once the file is generated and saved it would need to be played back at 60fps

upbeat path
#

well with this option you can begin playback as soon as the first set of bones is loaded and if you do your file io async or even on a different thread then you will get you 60fps playback speed

#

maybe use 1 file for all bones/frame so only one file is loaded/frame

abstract hill
#

Hmm, I think you might be right. Ill look into doing it like this then

#

Thank you

upbeat path
#

maybe use a folder structure
Second/Frame/Character/bonedata file(s)
if you need all 22 characters bones/frame at the same time

#

This is more a DOTS approach rather than an OOP approach

#

btw. Converting the Vector3's and Quaternion to a binary array for saving is extremely trivial to code

brisk pasture
undone coral
#

in my opinion you should adopt a motion format that (1) supports streaming, (2) is compatible with HumanIK and therefore Unity and (3) is open source. one such format is qualisys track manager's format. you probably want to output BVHs per frame - it does not support streaming, it's an ancient format, but it's the most compatible

#

trying to output FBX, which is the most flexible, seems the hardest

#

alembic unfortunately doe snot have a native workflow for bones

nova dagger
#

I use this code:
```c

 if (microcontroller.IsOpen)
    {
        recievedData = microcontroller.ReadLine();
        Debug.Log(recievedData);
        cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
    }
to read serial data  from my arduino, it works however it takes a long time (like 5 seconds or more) for it to start changing according to the  value my microcontroller recieves
the variable microcontroller is a Serialport variable assigned to the correct port, with the correct baud rate
undone coral
#

it will behave strangely

#

what asset / library are you using?

nova dagger
#

not really using an asset, just System.IO.ports

undone coral
#

well this code snippet isn't enough to tell you what's wrong

#

it is probably only reading 1 line from a buffer of many lines for every frame

#

the serial port is probably sending data much faster than 1 line per frame

nova dagger
#

true, hold on this is the script:

#
    public string recievedData;
    public GameObject cube;

    SerialPort brainbox = new SerialPort("COM4", 9600);
    void Start()
    {
        brainbox.Open();
        StartCoroutine(dataFromPort());
        
    }

    IEnumerator dataFromPort()
    {
        if (brainbox.IsOpen)
        {
            recievedData = brainbox.ReadLine();
            Debug.Log(recievedData);
            cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
            yield return new WaitForSeconds(0f);
        }
    }
undone coral
#

okay

nova dagger
#

I changed it to use a coroutine

undone coral
#

this isn't really advanced code. it depends how much you want to learn right now

#

there are lots of ways to approach this problem, some make a lot more sense than others, it depends how skilled you are with unity

#

and what this is

nova dagger
#

Yeah I'm decent with unity although it's been a while, and this is basically a school project about serial communication, I made this as a little extra to also connect it to a pc

undone coral
#

you will block eventually when there is no data to read, which means your problem will automatically require more work than ReadLine alone

nova dagger
#

there should always be data sent

#

since currently its just the value of a potentiometer constantly being transmitted

undone coral
#

hmm

#

then, your DataReceivedHandler will set a field to new Vector3(0, float.Parse(recievedData), 0);

#

it cannot set the transform directly

#

in an Update, set the transform's rotation to the rotation in that field

#

the reason it has to work this way has to do with threads, the main thread, the fact that you can't touch the Unity API from outside the main (or render) threads, etc. stuff you can learn more about online 🙂

nova dagger
#

okay thanks, I'll look into that

nova dagger
#

or because it is static

undone coral
nova dagger
#

ah does this belong in general?

#

right now the handler doesnt get triggered

undone coral
#

well part of this journey is being able to figure this out, it's going to be something small

#

for example, the parameters used to construct the serial port object probably have to be set to enable events

nova dagger
#

Hmm where can I find more documentation on that?

#

on the enabling of events

tough shadow
#

Aight, so i got a bit of an issue with unity 2d. I want to make a flashlight using raycasts so in order to do this i have made a fan of raycasts and where they hit. At the moment i am doing Debug.DrawLine to represent where the cast goes, but to try and make an actual flashlight. How would i crop out/remove a section of an image on a canvas to show said area, to make the illusion of a flashlight?

compact ingot
tough shadow
#

it will bleed over walls

#

right?

compact ingot
compact ingot
tough shadow
#

from what i can see it just spreads out

compact ingot
#

Idk what you want to achieve , can you be more specific?

tough shadow
#

from my tests before objects do not** cast shadows when it is the normal light object

#

as shown here

#

there is a URP spotlight

#

with shadows on

#

and it infact does not cast shadows

#

that is about as specific as i can get

tough shadow
safe vapor
#

in C#, if I have a list that has been initialized and populated with stuff, for example List<playableUnit> units and I copy one of the List items into another already initialized List like factionUnits.Add(units[0]), is the data I just added into factionUnits a pointer to the location in memory where that playableUnit is stored or is it a copy? Would doing something like units[0].name = "new name" apply to just that entry in the units List or would it apply for that element in the factionUnits List as well?

sterile snow
#

There is something that feels inherently cursed about having to manipulate canvas sorting order with script because messing with sibling index just makes multiple other things have a huge fit

#

Not an ask for help by the way I just find simulating depth with the UI to be really annoying

#

HOWEVER

#

This, this had no right to take two days straight

#

I never want to have to script carousels ever again

lament salmon
safe vapor
#

its a class

#

so that means its a pointer

#

so changing the original should modify the copy

lament salmon
#

Yeah

shadow orchid
#

this is with default unity canvas UI?

sterile snow
#

Yuppers

next marsh
#

Does C# contain a way to access non-generic members in a generic class?

#

E.g.

public class Test<T>
{
  public float f;
  public T t;
}```... and then access f without casting explicitly to a specific type of Test?
#

The context of this being the use of an ArrayList

#

(of which only contains two types: Test<A> and Test<B> where A and B are classes)

thin mesa
#

there's no casting necessary to access that member. you access it like you would any other field

next marsh
#

Ah lemme expand my scenario since I think it's lacking important information

thin mesa
#

however it seems like your question is not about a generic class, but accessing the members of objects contained in an ArrayList?

next marsh
#

Yes correct

I have an ArrayList which contains only Test<A> and Test<B> types, however I want to access non-generic members of an element in the ArrayList

austere jewel
#

Use an interface

next marsh
#

Then cast to the interface and access the members there?

thin mesa
#

yes. or if you only need to access the interface's members use List<T> instead of ArrayList

next marsh
#

Awesome, thanks for the good advice folks 👍

austere jewel
iron pagoda
#

IList<T> can access both Lists and Arrays, but can't be used to add or remove elements from an array.

stuck onyx
#

I cant find the namespace Unity.DeviceSimulator, why is this ?

#

i have it enabled and im using it but i cant find this particular event

#

i want to suscribe to it

steep robin
#

Hi, I have a problem with my build on Linux Ubuntu.

#

When the game starts, the "Made with Unity" screen doesn't show up, and I got only a black screen

#

I'm not sure if it's a build related problem

#

My project use URP. I created an empty URP project for test and the game starts correctly

vernal canyon
#

Hey all, Looking for a free Blur material for my UI. Asset store isn't helpful and the standard asset image effect they mention in the doc no longer exists.
I'm not an expert at shaders. so without any adjustements to the graphics pipeline, is it possible to blur via script or have a simple material? 🙂

nova dagger
#

I use this code to read data my connected arduino reads, but it takes ages before the value starts updating according to the arduino

    public string recievedData;
    public GameObject cube;

    SerialPort brainbox = new SerialPort("COM4", 9600);
    void Start()
    {
        brainbox.Open();
        brainbox.BaudRate = 9600;
        brainbox.Parity = Parity.None;
        brainbox.StopBits = StopBits.One;
        brainbox.DataBits = 8;
        brainbox.Handshake = Handshake.None;
        brainbox.RtsEnable = true;
        brainbox.DtrEnable = true;

        brainbox.Open();

    }

    IEnumerator dataFromPort()
    {
        if (brainbox.IsOpen)
        {
            recievedData = brainbox.ReadLine();
            Debug.Log(recievedData);
            cube.transform.eulerAngles = new Vector3(0, float.Parse(recievedData), 0);
            yield return new WaitForSeconds(0f);
        }
    }

    private void Update()
    {
        StartCoroutine(dataFromPort());
    }
fresh salmon
#

You're also calling .Open() twice on the serial port. Open it only after you set it up.

nova dagger
#

oh ok thank you

fresh salmon
#

Never did Arduino with Unity or C# so I don't know if it's the computer that drives the baud rate, but if it's not, make sure to match it up with the Arduino's. I recall seeing 19200 or higher...

#

And if all of this doesn't solve it, try reading data without ReadLine. This might wait until it waits and end of line character \n or a terminator \0

nova dagger
#

Thanks a lot, it is quite complicated working with threading and coroutines but I'll figure it out

fresh salmon
#

I've done some stuff with serial ports in the past and it's not that hard. The simplest and most versatile system is to put everything you receive in a collection (like a list or queue), and let another part of the code read the data from the collection

#

If you're using multiple threads (coroutines do NOT run on another thread), you can use a thread safe collection from the System.Collections.Concurrent namespace, to interact with the collection safely between threads

fickle ether
#

hello, i'm having a problem with adding an item to my list, on line 181

#

it says: NullReferenceException: Object reference not set to an instance of an object

#

what i'm missing?

upbeat path
#

presumeable pathpoints is a List which has not been initialised

fickle ether
#

hmm, how can i initialised it?

upbeat path
#

new()

fresh salmon
#

No offence but you're in the wrong channel if you ask such questions

#

Try debugging your issue first

fresh salmon
#

For Unity NullReferenceException might be the most common exception, better get used to see them, and fix them

fickle ether
#

yes i know i just confused with this one, i have no null object here but... sounds like i have to create a list temp of pathpoints and then add this list to the main list

fresh salmon
#

You do have a null object here, at paths[i].PathPoints, that list is null

upbeat path
fickle ether
#

no, the paths is not null

fresh salmon
#

The exception says otherwise

fickle ether
upbeat path
#

pathPoints is null

fresh salmon
#

No that's the wrong class

upbeat path
#

no

fickle ether
#

this is it

fresh salmon
#

Yeah that's it

#

Never initialized = null

upbeat path
#

so you are missing = new() after the pathPoints declaration

fickle ether
#

damn

#

thank u xD

regal olive
#

Can confirm the CG shader works without a pipeline asset inside project settings.
However if i add the URP asset the CG shader will not work. The HLSL shader also does not work

sly grove
fresh basalt
#

what's the line of code to enable keyboard for input fields on android webgl?

#

can't find it anywhere

thin mesa
regal olive
fresh basalt
#

sorry, but it's not there.

#

i'll ask in webgl

#

my bad

thin mesa
# fresh basalt i'll ask in webgl

oh you said webgl, which isn't exactly supported for mobile devices, so if what i sent doesn't work then there likely isn't a convenient way

fresh basalt
#

there was an update a few months back that fixed the heyboard issue, just can't find the line to enable it

honest hull
#

Hey does anyone know how unity handles textures in their raytracing pipelines?
Since bindless textures arnt supported and all

upbeat path
fresh basalt
#

it was introduced in the start of the year 2022.03b

upbeat path
#

yeah, but beta version. use it at your own peril

wooden cedar
#

Also probably didn't need to be posted in multiple channels

honest hull
#

Hey if you take a texture from a shader and put it in a list is it still by reference or does it copy the entire texture? What if I convert it from texture to texture2D before putting it in the list?

jolly token
honest hull
#

Ahhh ok thanks! Was confused because I Can easily have like 8-14 gigs of just textures when creating atlases, and was confused where it was all going

flint sage
#

No recruitment here

fallen sentinel
#

New to unity, is there a good spot to find a good dev to be able to pay and ask questions too? @flint sage

fallen sentinel
rugged pollen
#

how would y'all design a tetris-style inventory? in particular so designers can pre-populate inventories (say chests) with items in 'em?

brisk pasture
#

this question just confuses me, tetris is a gameboy game to me that has no inventory

rugged pollen
brisk pasture
#

UI wise its just clicking and dragging things, data wise you are just keeping track of what a player owns and where it lives on that grid

rugged pollen
#

thank you, yes, I'm curious if anyone has any ideas on the editor tools side, or perhaps data format side that would make it easier to design chests and things w/ items in them at various positions, rotations

compact ingot
#

But before you do that, be sure it adds something meaningful to the game and you don’t do it purely because it’s fancy. You can just have a weight/bulk value associated with items that would yield pretty much the same effect on gameplay (unless you specifically need the player to be constantly annoyed by their inventory layout)

#

Or you could go the ultima 7 way and abandon the grid to simulate messiness in a backpack, or you do the nested backpacks/bags thing where various bags you find have different sizes (wow style). Those would be alternative designs if you want to give people some gameplay around inventory organization that doesn’t involve bin-packing and a lot of tooling work

regal lava
#

Shouldn't be too hard to do. Just a bunch of matrix work, though preventing resizing/rotating would probably cut down on a lot.

#

Make a 2D array and store the space it occupies in the item, then determine how it fits using the pivot of the item.

#

You'd have to calculate against the size of the inventory which could result in going over the maximum index which you'd have to account for.

rugged pollen
#

on the implementation of the inventory itself I feel like I have a good grasp -- though rotation does make it more complex if I don't rely on Unity primitives. it's the design side that has be stymied. I guess I will try to come up w/ a scheme that brute force populates an inventory grid from a list ... as long as it's not too densely packed that seems like it might work

#

on the game design side, yes, this is a way more complex inventory, so the juice better be worth the squeeze!

quartz atlas
#

Is there a way to sync GameObjects with netcode? I have array of gameobjects which represent grid of islands for easy detection on which island I am trying to build something. Each island is a gameobject that has grid for building. The issue is that Rpc cant take GameObjects as parameter and NetworkVariable doesn't take nullable types. So if there isn' a way to sync GameObjects do I have to always think about solution that involvec sync using just basic types?

EDIT: Okay, apparently the is a thing called NetworkObjectReference. I guess that answers my question

smoky glade
#

Halo, how do i know if 2 SceneManagement.Scene struct are the same?
And, related. Is it ok if i call SetActiveScene per frame? Would it skip execution if the Scene i wanna set as Active is already the Active scene?

jolly token
#

You should profile it if the performance is concern, you could track current active scene with activeSceneChanged event

hardy egret
#

Guys, my Function is not obbeying me lol, when I assing an existing var (from outside the function) from a var (from the function), the function simply does not do this, and the existing var continues with its old value. (sorry my english btw)

#

I tested everything, the only thing that is wrong is the assignment

#
using System;

namespace Couse
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] vect = new int[3];
            vect[0] = 2;
            vect[1] = 4;
            vect[2] = 5;
            
            AddValue(vect, 6);

            System.Console.WriteLine(vect[3]);

        }

        static void AddValue(int[] Vect, int newValue)
        {
            int vectSize = Vect.Length;
            int[] newVect = new int[vectSize + 1];

            for (int i = 0; i < vectSize; i++)
            {
                newVect[i] = Vect[i];
            }

            newVect[newVect.Length - 1] = newValue;

            Vect = newVect;
            
        }
    }
}
#

output: Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.

devout hare
#

Doesn't look like Unity code

hardy egret
#

So im learning to use VS code

devout hare
rugged pollen
#

go read up on variable scopes

#

you're changing a reference not a pointer

#

using a list will probably save you some headache. or you can look into the ref keyword

hardy egret
#

thank you for your help!

weak herald
#

Hey, I'm trying to override implicit conversion operators for a wrapper class. I can get it to go WrapperType -> underlyingValue
But I cant do the opposite, implicity set the wrappers underlying data.

#
public static implicit operator T(PersistantDataType<T> data) => data.mData;
public static implicit operator PersistantDataType<T>(T data)
{
    // What to put here?
}
#

Any way to do it by modifying the object? It has to be static so I assume not eh

jolly token
#

Just make property and do wrapperType.Value = 0.555f

weak herald
#

Ok fair enough

#

Thought it would be cool/clean to make a type that behaves exactly like underlying type, but had methods to save/load from disk. Anyways, i'll just use a method to assign the value

lime bough
#

ok i have problem.

the classes for a game that i am modding (legally, single player, dev approved) do not belong to a namespace.
I would like all of the game classes to be accessible to mods via a namespace (Game.Classes.[]) and not have the global env cluttered.

I have exported all of the classes, remove the code from the methods, and forwarded the types to the original via TypeForwardedTo.

Problems began to arise when I tried to compare types and (obviously) the game type was not the same as my forwarded type. Similarly problems began to arise when trying to implicitly/explicitly convert.

By referencing Assembly-CSharp all of the classes are immediately added to the global env which sucks. (global::Class == Class)

Any ideas?

#

I am using a custom mod loader and unity doorstop .NET 4.8 C#8.0

lime bough
#

ooooooo

#

i think thats perfect

lime bough
jolly token
lime bough
jolly token
#

Yeah I think using . would have problem

lime bough
#

RIP multiple layers

#

yay it works. not 100% ideal but its much better

#

ill have to live with it. thanks!

jolly token
cyan nacelle
#

For 2D TileMaps, we have a 400x400 32bit sprite, sized map that takes like 12 seconds to load in unity. Is that normal? It does have multiple layers with animations

pliant crest
#

don't think anyone can answer that really

#

depends on hardware, depends on what tiles you are using

#

etc...

cyan nacelle
#

we have insanely buffed computers, its just simple 32x32 sized tiles, a map that is exactly 490x383 tiles big. And at most 1 tile animation is 5 sprites. We do have layers like water layers that are mostly covered with those 5 tile animations. These water layers are the ones in unity that are having hard times to load. Is unity known to be bad with tilemaps this size?

regal lava
#

My assumption is that the tile map is done completely by lookups, considering that the map itself expands incredibly far in game space. So, assuming you've occupied all those cells, that's quite a lot of operations when loading up.

cyan nacelle
#

@regal lava I assume its whatever the built in Unity Tilemap script is

#

this layer is problematic cause of the animations, we have tilemaps on the same scene that have way larger info sections, but no animations that load instantly

crystal ridge
#

Hello, I'm using JSON to save my game data, but I was wondering if I could stick the SaveData() method in a coroutine and only proceed once the file has been written. How would I achieve this?
Here's an example of my save code:

public class JSONSaveLoad : MonoBehaviour
{
    public void SaveData()
    {
        SaveData save = new SaveData();
        save.health = 100;
        save.skill = 10f;
        save.dead = false;
        string jsonString = JsonUtility.ToJson(save);
        File.WriteAllText(Application.persistentDataPath + "/SaveData", jsonString);
    }
}

public class SaveData
{
    public int health;
    public float skill;
    public bool dead;
}```
long ivy
#

you have already achieved that, or you need to clarify what you want to happen and what you think is currently happening

brisk pasture
#

File.WriteAllText is already blocking till the operation is complete

echo crater
#

Physics.OverlapSphere doesn't collide with my instantiated objects. Both my prefabs have mesh renderers just like the objects that are in the scene. Anyone got a fix for this?

   {
       Physics.SyncTransforms();

       Collider[] colliders = Physics.OverlapSphere(transform.position, 1000);
       foreach (var hit in colliders)
       {
           string n = hit.name;

           if (n.Contains("Skelly")) {
               Debug.Log("rEKT");
           }
       }
   }```
pliant crest
#

would recommend you draw a debug version of the sphere

#

to make sure you are colliding with what you think you are

echo crater
#

I gave up and made the sphere 1000 in radius

#

still nothing

pliant crest
#

1000 is probably too large

#

but yeah just draw a debug sphere

#

and see what you are colliding with

echo crater
#

If I stand my player where a psawned monster is it will still collide with the player but not the monster

pliant crest
#

you should probably compare the tag

echo crater
#

I tried rapid spawning the monster that is trying to collide with things and still on the player

pliant crest
#

instead of the name of the object

echo crater
#

I've been pausing the game just before the if statement

#

and then pressing continue

#

and then looking at the names of collided objects

pliant crest
#

so please do the first suggestion

#

make sure its doing what you think it is

#

then move on from there

#

cause you have to prove your assumptions otherwise its pointless

#

(this is all assuming the colliders are setup properly)

echo crater
#

yeh I just use the default colliders that come with the unity store assets

pliant crest
boreal agate
#

I am having a issue where the function of the code is spitting out null despite already having everything filled for it.

boreal agate
#

The State I have is giving me ArgumentException: The Object you want to instantiate is null.

pliant crest
#

whats owner?

#

and which instantiate is throwing?

boreal agate
#

owner is the Battle Controller and the instantiate its throwing is the int first

pliant crest
#

hows it being set?

#

or better yet

#

just break point into the line

#

and see if heroprefab exists

boreal agate
#

It is being set in the inspector and I have the hero prefab set into the battle controller

pliant crest
#

okay then breakpoint into it

#

check what the reference of heroPrefab is doing, like did you accidentally destroy it/set it to null etc...

boreal agate
#

Oh I think I know what the problem is

#

I have a obsolute code that may be causing not the hero but the job to be null

#

its in the static gameobject Create code

#

The problem is though is how I can change it

#

PrefabUtility.CreatePrefab( fullPath, instance ); because it says this is obsolute and wants to change it to Saveasprefab asset

#

hmm still seems to give me a error

#

ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate[T] (T original) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
InitBattleState.SpawnTestUnits () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:33)
InitBattleState+<Init>d__1.MoveNext () (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:17)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
InitBattleState:Enter() (at Assets/Scripts/Controller/Battle States/InitBattleState.cs:10)
StateMachine:Transition(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:38)
StateMachine:set_CurrentState(State) (at Assets/Scripts/Common/StateMachine/StateMachine.cs:10)
StateMachine:ChangeState() (at Assets/Scripts/Common/StateMachine/StateMachine.cs:24)
BattleController:Start() (at Assets/Scripts/Controller/BattleController.cs:20)

austere jewel
#

Also please use our guidelines to post code, so we can see line numbers without downloading files. #854851968446365696

boreal agate
#

ah okay

#

Yeah the error seems to come from this script but the null doesn't tell me much