#archived-code-advanced

1 messages · Page 29 of 1

frozen badger
#

I understand, but in my case this deck is my attempt at the game manager type class

#

having it in "the game manager" is not fitting because how small a part of the game it is

#

and so instead, perhaps consider what I call the "ItemDeck" to be the "ItemManager"

#

Like, imagine a linked list. Removing an item from the center causes multiple elements to be altered, but I wouldn't put the remove functionality outside the linked list

#

And the linked list does not emit events when an element is removed or the Next pointer is altered, right?

tender light
#

Exactly. And again your game might want those events

frozen badger
#

That's what I'm saying, that can't happen

#

It's like saying I want random.range to emit events when it rolls a 7

#

The assumption that events are desired upon objects being chosen is incorrect, and stems from the belief that they are actual cards, right?

tender light
#

Not at all

frozen badger
#

Or maybe "discovery" means something else that I am unaware of?

#

In card game language it's also called a tutor, right?

#

Or is it more like scrying?

tender light
#

Yeah. I think MTG calls it that. Does not matter what the mechanic is. I will re-iterate the point one last time and then I give up.
Sooner or later you might want to put additional functionality on top of the players actions. The corruptor example earlier was great.
Its an encounter that is forced upon you. This logic should NOT be part of the data structure. It should instead live outside of it. That's all.
The class of Deck should JUST store data. Nothing more.

frozen badger
#

Sure, but if it just stores data then it's just a list

#

And if something says "the next encounter will be a corruptor" then that will be outside of the data structure

#

However, how to access the data structure, to me, makes sense inside the data structure

#

I.e "roll one random" or "get by tag"

obsidian glade
#

these functions are almost written already in the form of linq queries, e.g myList.Where(card => card is HealthType).Shuffle().Take(n);

tender light
#

That's exactly what the doctor guy was trying to explain is a bad idea. Because then overriding that behaviour becomes problematic. Its not something easily extensible. Its also something that is offten affacted by other game systems. Therefore a bad idea to couple it together.

frozen badger
#

Right because he envisioned stuff like "every time you pull a card, gain one health"

#

Or "if this card is drawn, lose one health"

frozen badger
regal olive
#

I'm using the NugetForUnity package to import the ML.NET and supported packages into the project, but I am having trouble trying to get the System.Collections.Immutable package in the same way. The UI doesn't really do anything in that case. The other packages need this one, but somehow this dependency does not get installed with the others. What can I do to fix this?

flint sage
#

Ask the developers?

regal olive
#

I guess I can log an issue and wait.

undone coral
#

what is your goal?

#

like what kind of application are you making

undone coral
undone coral
#

there's an effect in spellsource that's like, "Your Draw effects become Discards instead"

#

and because the invocation of a spell function itself is data, and all the spell functions have the same signature - even though they are all different spells! - this turned out pretty easy to implement robustly

undone coral
#

i can keep thinking of real examples

#

Discovering from an opponent's hand - now you're not using the deck anymore

frozen badger
#

Yeah but a significant of them would be from card games, right?

undone coral
#

yeah just because that's what i'm familiar with

frozen badger
#

Like, there's no "Hand" to discover from as there are no actual cards

undone coral
#

here's a good one: "The next monster you would have encountered is put into your inventory as an item instead. You can face it at any time by using it"

#

😵‍💫

frozen badger
#

Right, that's like 4 layers down though

undone coral
#

Potion of Theft: "Discover an item from an enemy's inventory."

frozen badger
#

wouldn't it be easier to just pull a monster at that point and put it in an inventory

#

as opposed to waiting until the next fight

undone coral
#

yeah it would be a pretty complicated thing to do

#

these games are fun to make lol

frozen badger
#

I am having a time disjointing the effects as far as possible from the items, etc

undone coral
#

Lucky Armor: "Whenever you would roll dice, your unlucky 1s become natural 6s (or 20s)"

frozen badger
#

Like, pulling the effect "TeleportPlayer" out of the item and instead making it a generic effect

#

and then items are collections of effects

undone coral
#

yeah

frozen badger
#

Different effects are active/usable at different moments

undone coral
#

you can look more into the spellsource architecture - the caveat is spellsource content is authored by nonprogrammers but who can think procedurally - in short it kind of looks like this

#
// teleport anywhere within 5 units of the player
public class TeleportationPotion : BasePotion {
  public float radius = 5f;
  public float castingTimeSeconds = 0.8f;
  public override async
 UniTask<CastResult> Use(GameContext gameContext) {
   var target = await gameContext.SelectTargetCoordinate(
    new RadiusSelector(
      center: gameContext.player.transform.position,
      radius: radius));
   var teleportationSpell = new TeleportationEffect();

   teleportationSpell.castingTimeSeconds = castingTimeSeconds;
   return await teleportationSpell.Cast(gameContext);
  }
}

public class TeleportationEffect : BaseEffect {
 // this would be pulled up into base effect since
 // lots of stuff will have cancellable casting time
 public float castingTimeSeconds;
 public override async
 UniTask<CastResult> Cast(GameContext gameContext, Target target) {
  // throws operation cancelled and propagates up
  // if the user clicks the X button in the UI
  
  // time spent casting
  // if the target (the player) is damaged while casting,
  // cancel everything
  await gameContext.DamageCancels(
   target: gameContext.player,
   effect: async () => { 
    await UniTask.Delay(TimeSpan.FromSeconds(castingTime));
   }
  );
  
  // this will eventually be gameContext.Teleport() when you
  // want more advanced teleportation rules
  gameContext.player.transform.position = target.position;
  return CastResult.SUCCEEDED;
 }
}
frozen badger
#

Yeah, but that is still an item in that sense right

#

I want my non-programmer compatriots to be able to set up items themselves

undone coral
#

almost ready

frozen badger
#

so I'm working towards getting the effects into dropdownlists they can pick in the editor

#

on the scriptableobject for the item

undone coral
#

i think it's better to create Bolt objects

#

because lots of games try to have you program in the inspector

#

and it's painful

#

anyway i hope that is illuminating

#

this stuff is easy enough to program

#

that usually getting the text is more valuable than your colleagues being able to program it themselves

#

does that make sense?

#

you should ask them to write text

#

until your game is more mature it's hard to do the thing where you program using data

#

there's a lot you would have to know intellectually - if you want it to be useful, the data representing the effects has to be context-free, non-polymorphic and homoiconic - that is just

#

a huge leap

#

in that second link @frozen badger you can actually see a concrete example of exactly what @obsidian glade was talking about

#

java streams == C# linq

frozen badger
#

Sure, but this also is a card game right? And so there is a lot of "Card interaction" so to speak

#

same as like, slay the spire

undone coral
#

well

#

yeah but same in any RPG

frozen badger
#

Not really, like the fireball spell rarely changes the ice bolt spell

undone coral
#

have you used the starcraft 2 editor at all?

frozen badger
#

Like, in this case the only thing that is similar to a card game is how stuff is handed out

#

no, I used the wc3 one a lot

undone coral
#

okay

#

so you would know how it's like, a tree of random crap

#

to implement spells right

#

this is very similar

frozen badger
#

Sure

undone coral
#

this is what the implementation to the WC3 spell system looks like... sort of.

#

the differences are academic

#

like they have an explicit, poorly implemented copy of half of basic LISP AND the virtual machine used to run it. i just do the first half

#

the examples i wrote for you in c# are nice because your game stack looks like your c# stack. in WC3, it is not

#

so like if you threw an error in the example i showed, using async, it will correctly show in the stack like, what UI button press was associated with casting the spell

short fog
wet burrow
#

Because I get errors saying my struct doesn't support the equals operator

pliant crest
#

huh TIL to compare structs you need to override the equality

#

never needed to do that apparently

candid lodge
#

which is less expensive way to find closest gameobject unity ? looking to make shoter game

jolly token
#

ValueType.Equals automatically call Equals for each members, but causes boxing
And no default == operator for structs

pliant crest
#
    public static bool operator ==(Test lhs, Test rhs) => lhs.Equals(rhs);
    
    public static bool operator !=(Test lhs, Test rhs) => !(lhs == rhs);
    
    public override int GetHashCode() => (Id, Name).GetHashCode();

    public override bool Equals(object? obj) => obj is Test other && this.Equals(other);
    
    public bool Equals(Test p) => this.Id == p.Id && this.Name == p.Name;
jolly token
#

Also implement IEquatable<T> when using the code ^

pliant crest
#

ahh yes

#

afaik i've avoided boxing in this as well

#

(obviously replace Test with your type)

jolly token
#

Yeah if it implements IEquatable<T> then EqualityComparer<T>.Default would not do boxing

wet burrow
#

It's great to get a lot of them so I can figure out the common rules, in case there are multiple ways to do it, so I can figure out what's best for me

pliant crest
#

standard way

jolly token
#

Wait for C# 10 then we can use record struct 😄

wet burrow
pliant crest
#

b becomes the type Test as well

#

so its like testing and casting at the sametime

wet burrow
#
public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false; // Checks that it's not null
    if (ReferenceEquals(this, obj)) return true; // Checks if it's the same
    if (obj is CategoryTag b == false) return false; // Checks that the object is the correct type
    return id == b.id && name == b.name; // Checks the values
}
public override int GetHashCode()
{
    return id.GetHashCode() ^ name.GetHashCode();
}

I made these, they don't show any errors so I'll need to see how they turn out

pliant crest
#

you shouldn't do that

#

you should have one source of truth

#

not multiple @wet burrow

#

unless for some reason you don't have Equals that takes in your type

wet burrow
#

so I should have either the equals or the gethashcode but not both?

pliant crest
#

na

#

your equals is doing the comparison

#

but its the object version

#

return id == b.id && name == b.name; // Checks the values

#

that should be in the typed version

#

its also a struct

#

so i have no idea why you are doing reference checks

wet burrow
pliant crest
#

well you can zombie together a solution if you want

#

but make sure you understand what you are doing

#

don't just copy paste

wet burrow
#

I guess that's one disadvantage of getting a bunch of answers from different places

pliant crest
#

i've given you a complete solution

#

just remember to implement what cathei said

#

or make your own based on the microsoft article i've sent you

#

all roads should lead to the same answer thou

wet burrow
#

A more performant solution would depend on what you're trying to do

#

Or you could use SceneManager.GetActiveScene() to get the current scene data, then get its GetRootGameObjects() function, and iterate through those and their children

wet burrow
#

thanks for the info @pliant crest

lyric dragon
#

Hello guys,
I am currently working on animating the eye movement. I want the eyes of one of my models to follow the camera.

I watched some youtube and made something that satisfies my needs, but there are few problems.

I did something like leftEye.transform.LookAt(camera.transform), but the orientation of the eye doesn't really match the iris position, so instead of following the camera with the iris, it follows it with eye's white.
My workaround was to find an appropriate rotation such that it makes iris follow the camera.


leftEye.transform.LookAt(camera.transform); 

leftEye.transform.Rotate(new Vector3(10, 90, -13));

This is the approximate code which is put into the void LateUpdate()

I figured out those 10, 90, -13 values by hand, by constantly tweaking a little bit and running over and over again in the editor.

It works fine, but as soon as I move camera to the sides, the eyes do not follow the camera, but somewhere ahead of the camera, this results in model's eyes looking ahead of camera position.

How do I dix that?

young wraith
#

Hi I'm having a problem detecting collider bounds if it's circlw

#

*circle

digital helm
#

Hi, I have a shadergraph that has 6 possible textures and I wanna be able to expose UV channel selection for each texture, but I've ended up with over 1200+ shader variants being created

#

is there a better way to not end up with 1200+ variants

compact ingot
#

Depends on what exactly you mean by that. Do you want to subdivide a polygon shape into a regular square grid?

#

maybe draw a picture of what you want

compact ingot
crimson ruin
#

RectTransformUtility.ScreenPointToLocalPointInRectangle looks bugged, it doesn't account for scale even though it has all the context to do so. If change scale of the target RectTransform between two calls I get identical value even though this should ever be the case if the point happens to be straight on the pivot, which it isn't

compact ingot
crimson ruin
#

How so? Seems to work as expected

compact ingot
#

it just makes it all weird, the math behind it is very lossy

#

you can use scale to do local effects, but you should not use it for layouts

crimson ruin
#

Ah, I guess there could be rounding issues since I guess it's in pixel space really

#

I need to for a world map type of deal where you can pan & zoom

compact ingot
#

afaik the whole ugui system basically ignores scale

crimson ruin
#

So it seemed kind of intuitive to just scale & translate

undone coral
undone coral
opaque cape
#

Im sorry in advanced

#

Im trying to figur out Cellular Automaton this does not quite work.

    private void Cellular_automaton(int count)
    {
        for (int i = 1; i < count; i++)
        {
            var temp_grid = noiseGrid;
            for (int j = 1; j < mapWidth; j++)
            {
                for (int k = 1; k < mapHeight; k++)
                {
                    var neighbor_wall_count = 0;
                    for (int y = j - 1; y < j + 1; y++)
                    {
                        for (int x = k - 1; x < k + 1; x++)
                        {
                            if (Is_within_map(x, y))
                            {
                                if (y != j || x != k)
                                    if (temp_grid[x, y] == _wallPrefab)
                                        neighbor_wall_count++;
                            }
                            else
                                neighbor_wall_count++;
                        }
                    }
                    if (neighbor_wall_count > 4)
                        noiseGrid[j, k] = _wallPrefab;
                    else
                        noiseGrid[j, k] = _floorPrefab;
                }
            }
        }
    }

    private bool Is_within_map(int x, int y)
    {
        if (x < mapWidth && y < mapHeight)
            return true;
        else
            return false;
    }
#

I appreciate any kind of help 🙂

devout hare
#

Need a bit more details than "does not quite work"

sly grove
#

Because both are basically outside assemblies dealing with your game assemblies from the outside

regal olive
# undone coral hmm nugetforunity doesn't really work

I'm trying to use ML.NET in Unity for a classification task. I will script and train the model externally, but I will use the trained model inside the game.

There are some restrictions (based on the 4 year old sample ML.NET has for Unity). It's problematic to find the DLLs necessary to make it all work.

undone coral
regal olive
#

I have heard of Barracuda. Will it be suitable for developing a C#-only model?

undone coral
#

what are you trying to do?

regal olive
#

Well one I could script only using C#. I am doing this for an assignment so I can't use anything apart from C#.

undone coral
#

okay

#

so it sounds like you are new to all of this

regal olive
#

The next thing is I don't have a lot of data, so I have been advised to generate synthetic data by taking the only sample I will create manually and adding noise to it to generate more data.

#

I have very brief experience working in Python and Java for sentiment analysis tasks but this is not my primary field!

undone coral
regal olive
undone coral
#

okay

#

personally i would suggest to not use Unity at all

#

it's way beyond your abilities

#

it sounds like you are very new to this

regal olive
#

I am literally making a game in Unity.

#

I have to do this, new or not.

undone coral
#

what is your goal?

#

what are you trying to do?

#

like big picture

regal olive
#

To train a model to classify different types of "standard" (not mathematical) knots.

undone coral
#

no i'm saying

#

what is the game, what are you classifying

#

what is the idea

regal olive
#

The game itself is a simulator of sorts where the player gets to toe knots in different scenarios.

undone coral
#

were you trying to create a rope in VR earlier?

#

you were

regal olive
#

The model should just be able to classify what knot it is based on data taken from the rope. In this case I am generating a Centripetal Catmull-Rom spline from the rope segment centres, taking a pairwise difference of the coordinates, and passing them off as a long vector of floats (split into x, y, and z values).

undone coral
#

so now you want to classify the knot some how?

#

okay

#

to use an ML model in unity, the best workflow is to export it and its trained weights in the ONNX format, which ml.net supports, and load it with barracuda.

regal olive
#

Exactly. I have been able to make a sort-of VR simulation of a rope. Now I need to tell knots apart.

#

In that case, I'd have to make the NN in something like Tensorflow, which may not be suitable, I am guessing. But I like the idea of using Barracuda to load the model.

undone coral
#

i don't know if it makes sense to do this generally, you will be able to figure out what knot is tied analytically

undone coral
#

you can make the neural network in ml.net

#

you can do whatever you want in ml.net, and export the model to the onnx format

#

that said, nobody does this, so it's going to be full of bugs

regal olive
undone coral
#

nobody uses ml.net 👀 and nobody uses barracuda

#

these things have 0 adoption

#

you should probably determine the knots analytically. i'm sure if you punch it into google you'll find something

#

gotta go

regal olive
#

Do people use ML Agents for classification tasks, because from my experience we were basically doing RL there.

undone coral
#

all of this stuff has a rounding error of adoption, so it has a lot of bugs

regal olive
regal olive
undone coral
#

my suggestion is, don't do this lol

#

is it essential to identify the knots? what about making some funny gameplay instead

opaque cape
#

Hello, i got a 2d grid array how do i target the outline of the grid to spawn stuff like resources.

undone coral
#

like tying the rope around a bunch of different funny objects as levels, and they are your qwop game

undone coral
#

when you say outline of the grid, you mean the "walls" in this cave right?

opaque cape
#

Yes

undone coral
#

praetor also gave you

#

a way to look for adjacent nodes

#

you can visit every grid point and check

opaque cape
#

I see, thanks for the help.

weak prawn
#

Hi, I just found out that most of my methods under Update() is being called every frame which is really not ideal, can you please share your ways on how you deal with Update()? For example, when my Character is wall running, I want the Raycast to stop being called. But when I jump or switch to another Wall, I want it to be called.

regal olive
undone coral
#

okay well

undone coral
#

i think i could identify most knots, analytically, if they were "drawn" in 2d (which is really three dimensions, x z and "over" versus "under")

#

of the form intersections of rope (t1, t2, over or under) maybe?

#

if it were a single rope

regal olive
#

The data is directly the coordinates of a spline representing the rope, and not some image.

undone coral
#

where t is the distance laong the rope

#

yeah but

#

listen it's not going to just, work

#

you're not going to be able to do program finding with ML.net

regal olive
#

I get what you're saying. There are existing projects doing knot image recognition.

undone coral
#

if your project is all about IDing knots

#

surely you've made an attempt at doing this analytically

#

where did that go?

random dust
#

Does anybody know if there is a way to check if a string can be deserialized into a json object or array without throwing unnecessary exceptions? Right now I check if an exception throws when I try to deserialize the string, because I could not find an alternative. Relying on exceptions is a bad practice so I want to avoid it.

// Try to deserialize the string into an object or array if possible.
            try
            {
                responseObject = JObject.Parse(responseBodyUnparsed);
            }
            catch (JsonReaderException)
            {
                try
                {
                    responseObject = JArray.Parse(responseBodyUnparsed);
                }
                catch (JsonReaderException)
                {
                    responseObject = responseBodyUnparsed;
                }
            }
undone coral
random dust
#

Is valid json object or is valid json array basically

#

I could check if the string starts with { or [{ I suppose, but I was hoping for a more reliable solution

undone coral
#

lol

#

it's pretty grim out there

regal olive
undone coral
#

i think you do try to parse it and see what happens

undone coral
#

a neural network isn't going to be able to do the dimensionality reduction into whatever form really simplifies a 3d knot, not without colossal amounts of data

#

you will have to figure this out!

regal olive
#

Which I can't because there's more work on total, but this is a start.

random dust
#

Oh well, thanks 😛

regal olive
#

I'm afk actually, will elaborate further soon.

floral notch
#

Hey everyone, I've been very confused about this for several hours now(first time using raycast in code), I have this script attached to my main camera and I get the error "null reference exception object reference not set to an instance of an object" in line 31, I have no idea whats wrong, some help would be appreciated, thanks in advance

autumn topaz
#

how do you make a jagged nativearray that refrences a struct?

regal olive
#

@undone coral there's a way to simplify the process a model will take to identify a knot.

We take a given set of spline coordinates and first take their pairwise differences into some buffer. This allows us to immediately remove any dependence on the transform or other positional property of the spline. It can also be normalised since the distance between each spline point is always the same.

We can easily generate synthetic data from these differences by adding some noise to each point in this new buffer, and then perform some manner of dimensionality reduction using PCA or similar as a preprocessing step.

Of course, the main pain point is how I would consume the model, but I guess the first two steps are within my reach.

signal reef
#

Does someone know how do I make some code in FixedUpdate() occurs before other script that also uses FixedUpdate() in it's logic?

severe topaz
#

there was something in project settings iirc @signal reef

regal olive
severe topaz
signal reef
floral notch
severe topaz
#

i see the problem on 32 but not 31, so again it's more likely that VS not being set up for unity might be causing it

#

honestly just remove that line

floral notch
severe topaz
#

i checked docs and Z isn't used for screenpoint to ray

#

depth of ray is what you have set to 100

floral notch
#

huh, weird, you mentioned an error in Line 32

severe topaz
#

yeah, that was it and i double-checked it, i still have no clue why it'd bother reporting 31

#

you don't have to assign anything either if you're not reusing it, it'd condense into
if(Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), RaycastHit hit, 100f))

#

if it says null then it's probably camera not being assigned properly

floral notch
#

oh interesting, ill give it a go

severe topaz
#

wait, is there a camera in the scene?

floral notch
#

yes

severe topaz
#

then yeah check how to configure VS for unity if it still complains

floral notch
#

alright, Ill need to check

hushed plume
#

given the wall's normal and the objects velocity, what should the resulting object's velocity be after a collision?

right now i've got
(velocity+Vector3.Reflect(velocity,hitnormal))*velocity.magnitude;

but that doesn't seem to be working

jolly token
hushed plume
#

it's not bouncy

obsidian glade
hushed plume
obsidian glade
#

and what isn't working about it?

hushed plume
#

going through the ground

#

also bouncing sometimes

undone coral
# regal olive <@247793168056057857> there's a way to simplify the process a model will take to...

We take a given set of spline coordinates and first take their pairwise differences into some buffer. This allows us to immediately remove any dependence on the transform or other positional property of the spline.
the knot could start earlier or later in the spline
the first bend could be in any direction...
sounds like there are a lot of things you would have to do to reduce dimensionality

#

which is sort of something neural networks are good at, but on the other hand, you will have to generate thousands to tens of thousands of examples

#

possibly per class

#

which is way out of scope for you

#

you should really try to do this analytically first

#

when is your deadline?

analog verge
#

After starting my game on Nintendo Switch, the application get freeze if I touch fast the screen immediately after starting. I think the application was loading Resources folder contents at that time. Does anybody know about this issue?

pliant crest
sly grove
floral notch
#

My bad

dusky kettle
#

hey guys, so say I want to write a script that scrolls a material offset at a constant rate
what is the most inexpensive way to go about this?
my thought is to utilise the jobs system, but it feels like all that would do is make another thread add a number to another number and that it would be more computational power initialising the job than it would be actually doing the math
I just wanted to know the absolute best way to do this so I can do it at scale and not have to worry about performance being left on the table
and sorry if this doesn't count as code-advanced, I just wanted to cover all grounds in case the method turns out to be super complicated

#

ill try and find where I wrote to do it earlier

undone coral
dusky kettle
#

thats a good point lmao

#

im not sure i just thought maybe there might be a very technical better solution that might bypass some unity processing on top since the way unity scripts work seem to be kinda higher level

#

i dont fully understand how unity works yet, still learning

vast shale
#

if it's the same for all objects you could also just use a shader global. slightly more control than time.time inside the shader

young wraith
mint sleet
#
{
  "name": "fa df asdfa adsf sda f",
  "detail": "ads fasdf asdf asd f asdf asdf asd adsf ",
  "modules": [
    {
      "moduleId": 1,
      "templateId": "c498678f-9682-4d96-a52e-8f6be993e801"
    },
    {
      "moduleId": 2,
      "templateId": "5819774b-d710-4153-a91a-0a6dbfe8a37a"
    },
    {
      "moduleId": 5,
      "templateId": "e089e26d-d3e4-4cfd-a962-3bed2dad1ab2"
    }
  ]
}```
#

hello how can I compare "Module" arrays' "moduleId" attribute with each other to see if it is repitetive?

#

That is soo easy I know but could not do it.

#

if two objects have moduleId 1, for example, it will return false

regal olive
regal olive
regal olive
crystal galleon
#

I want to make a class serializable, but on Deep Copy (via JSONUtility.ToJson/FromJson), I want it to ignore a specific field, which stores a Scriptable Object, which are NonSerializable. How could I do this? I do need to make a custom serializer, but I'm clueless

regal olive
vocal dagger
#

Not sure where this belongs, im playing around with unitys IK.
However, i want that the whole upper body of my player moves to reach the target with his hand.

How do i do this via code ?

vocal dagger
#

Anyone ?

severe topaz
sly grove
#

every bone along the tree will move somewhat to get the end effector to touch the target

#

you don't need to do anything in code

vocal dagger
#

Another topic, how could i ensure that a rigidbody only moves within a certain area ?
I did some clamping and check of the z/x position... however this stops working as soon as i rotate my game... which is quite common in my case.

Glad for any help, have no idea how to solve this

sly grove
sly grove
vocal dagger
# sly grove Use colliders to confine your objects in a physical space

Thats not the problem... clamping is the problem... imagine a AI which only moves a pug within a certain space like this to defend its goal :

        // Pug is in the players half, return ai back to its starting position for defending. 
        if (_pugTransform.position.z < _remoteBoundary.Up)
        {
            movementSpeed = MaxMovementSpeed * Random.Range(0.1f, 0.3f);
            _targetPosition = new Vector3(
                Mathf.Clamp(_pugTransform.position.x, _remoteBoundary.Left, _remoteBoundary.Right), 
                _startPosition.y,
                _startPosition.z
            );
        }
#

For this colliders can not be used

#

And it works, but only for a fixed rotation of the game table... once the game table is rotated it messes up

#

I basically need some vector3.clamp to keep a vector3 between two other vector3's which act as some sort of line/border

sly grove
#

I'm not sure why colliders can't be used, but you can also just put this bounds stuff on a GameObject and rotate that. Then use transform.TransformPoint to transform your boundary "corners" to the appropriate places.

Your code clamping on individual world axes will have to change though

#

you'll need to just do some simple vector / Plane stuff to confine the points

vocal dagger
#

Thats the problem the code clamping, i just have no idea how i should to that. Rigidbodys move within world space... and the code also needs to "rotate" or change axis or whatever... how do you do this normally ? Any code samples ? I cant find anything about this :/

autumn topaz
#

I'm trying to turn a jagged array of a simple struct 'face' (public Face[][,] topFaces, sideFaces, frontFaces;) in my 3d block game a job, but I dont know how to convert this to a native array. Does anyone here know what I should do here?

undone coral
sly grove
#

you can also use a NativeHashMap to map coordinates to the faces

autumn topaz
#

hmm interesting

#

I have done some searching and it seems like structs of nativearrays isnt possible either so I will look into it

tough plank
autumn topaz
# sly grove Multidimensional arrays can always be flattened into 1D arrays

Another question, I have started converting the 3d array into a 1d one but lambda functions such as this
Face GetFace(NativeArray<Face> inputArray, int sizeX,int sizeY, int layerIndex, int arraySize) => inputArray[(layerIndex * arraySize * arraySize) + (sizeY * arraySize) + sizeX];
do not work even though just accessing the array on its own works fine. why does this throw an error when called?

autumn topaz
sly grove
#

SO I wouldn't expect to be able to use any lambdas really in the job system

#

lambdas are managed objects

#

allocating and working with managed objects in the job system is a no-no

autumn topaz
#

what about regular functions? do they not work as well

sly grove
#

static functions work

autumn topaz
#

ok will try that

#

I mean i could go without a function but you can imagine how much of a pain it would be in a script that calls this function 100+ times lmao

undone coral
#

this needs to be declared static

solar anchor
autumn topaz
serene grove
#

Hi

#

how can i make basic character customization with photon

#

i can pay for help

undone coral
#

do you have a screenshot of your game handy?

serene grove
#

yeah i currently have 2 character

solar anchor
#

I want to download a nugget package
IotaWallet.Net.Domain
and the error above occurs.
I am on a mac.
I did not find any .net framework 4.7.1 for mac to download an install nor can I change to .net 4x in the player settings
Image
could someone please give me a hint how to get this package into my project?

serene grove
#

i have the models

#

anybody has photon example for help me

kindred crane
#

So its a multiplayer game?

#

Or are u using photon to... save data to cloud?

serene grove
#

basicallay

#

just a basic world

#

player just log in

#

after making basic edits

#

change hair

#

skin color

#

shirt top bottom

kindred crane
#

So ur using photon to store data onto a cload server?

serene grove
#

i using cloud

#

can we save

#

prefab data

#

and load them?

#

cloth1 activated after cloth2 deactivated

undone coral
serene grove
#

i think so

kindred crane
serene grove
#

i researched but i cant find any doc

kindred crane
#

Ive never used photon but cant u just use whatever code is used to send data to the server to send data to the server

#

Also

#

It is less performant to save all the prefab data just save like a string for whatever the customised look of the plr was and then u can load that data onto the client side

undone coral
serene grove
#

i checked assetstore

#

why we dont have any

#

multiplayer supported character creator

kindred crane
#

Cuz nobody made it

serene grove
#

;.;

undone coral
#

maybe i can give a specific recommendation

serene grove
#

currently

#

i have 2 assets

#

can i post them?

#

here

#

@undone coral

kindred crane
#

Post ss of them not the actual models

#

@serene grove

serene grove
#

no i have assetstore links

#

a multiplayer template and a character creator

undone coral
#

just the screenshot

serene grove
#

okey

undone coral
#

oh

#

you didn't make the models?

#

i'm asking a screenshot of your game

#

of what you see in the scene view right now

serene grove
serene grove
undone coral
#

okay

#

i think it's fine

serene grove
#

also i have this one

#

for character creator

undone coral
#

you're at the start of a long journey

#

it's okay i don't need to see it anymore

serene grove
#

how can i integrate them

#

i can currently select male or female

#

i wanna add cloths shoes etc

misty glade
#

Looking for feedback on how structure this. I have a technical artist who is creating many dozens of prefab one shot particle effects. I've got a number of gameobjects in a scene that I want to basically staple these effects to when they're relevant. Unfortunately, the type of objects isn't consistent. Some are icons, some are buttons, some are in-game objects, etc.

What I'd like to basically be able to do is instantiate one of these VFX prefabs at a time and point and scale in space, without tying the prefab to the object...

Maybe a scriptable object with a list of VFX and a getter that takes an enum to give me a prefab that I can instantiate and destroy from the object in question?

rare sage
#

Hi all, I've got two problems:

I'm working on a game where the game slows down when the camera is rotated by the player, otherwise it runs at 60fps with no problems. I've run it with MSI Afterburner and that confirms that the framerate drops down to 20-30fps whenever the camera is rotated, though it feels like less when you're actually playing the game.
I'm using the new input system to track the mouse delta, and the camera logic is just for a simple FPS camera. Here's the code for camera rotation:

float mouseDeltaX = _playerInput.actions["LookX"].ReadValue<float>();
float mouseDeltaY = _playerInput.actions["LookY"].ReadValue<float>();

Vector2 mouseDelta = new Vector2(mouseDeltaX, mouseDeltaY);
Vector2 currentRotation = mainCam.transform.rotation.eulerAngles;

currentRotation.x -= mouseDelta.y;
currentRotation.y += mouseDelta.x;

mainCam.transform.rotation = Quaternion.Euler(currentRotation);```

Can anyone see something that could be causing the slowdown, or know about other issues that can cause it?

I've tried connecting the profiler to the built version of the game, but whenever I use it it reports the game as running at 60fps, all the time.  Using MSI Afterburner at the same time as the profiler shows that the game isn't running at 60, which is fun.  It's probably connected to the first issue, but does anyone know why that might be happening?
jaunty bone
#

Happy Turkey Day! 🦃

Looking for tips on how to debug a photon connection to master! (Specifically for WebGL using websockets)

Been at this for hours, connecting locally in the unity ide build works... the windows build works... (all call OnConnectedToMaster() and creates/joins a room)

but not in the WebGL build....

In the browser console with my debug lines I see that neither the OnConnectedToMaster() or the OnDisconnected() callbacks being called. Therefore, my cry for help to debug what is going on here. bool connected = PhotonNetwork.ConnectUsingSettings("1"); is true, so I read there should be at least some kind of callback...

Code in this thread. Thank you so much in advance!

analog verge
severe topaz
rare sage
rare sage
pliant crest
#

asking us isn't gonna help that much

severe topaz
#

but yeah ^

rare sage
#

I did, the profiler doesn’t report any frame drops

flint sage
#

That rendering graph looks like it's just more complicated and expensive rendering

#

Go disable vsync and see then

pliant crest
#

looks like most of their wait time is from vysnc

rare sage
#

Waiting on vsync isn't the issue, because that's expected if the game is actually running at 60 like the profiler says. If you read the original message I posted you'll see that the problem is that the game drops to 20-30fps when I rotate the camera and the profiler doesn't pick up on that, meaning it's not all that useful for finding out where the problem area lies right now.
I've tried disabling vsync and got the same frame drop behaviour, only with an unlocked framerate.
That video from Code Monkey seemed promising, but the game already has the input system to update on update() rather than fixedUpdate()

pliant crest
rare sage
#

Yeah it does, when you run it in the editor you can actually see the big performance spikes in the profiler and inspect them, but the cause of the drop in performance just falls under "EditorLoop" which is supposed to disappear when you build the game and run it, but the same issue happens on built versions on the game which has stumped me

pliant crest
#

mind sending a screenshot of that?

rare sage
#

Sure, gimme a second

#

Big performance spikes caused by moving the mouse a little at a time, at the bottom you can see EditorLoop took 300+ms on this frame in particular

pliant crest
#

is this true throughout the spike?

flint sage
#

Enable deep profiling and see what is in there

winter yacht
plush hare
#

So I'm trying to write a component that attaches a unique ID to a gameobject in a scene for network synchronization purposes. All of the solutions online generate a GUID and then get the hash. This generates a very large number. Is there a way to do this starting from 0?

#

preferably assigning it only in the editor when the game isn't being played

winter yacht
winter yacht
# plush hare custom

I just increment a static integer every time a mob is spawned. This id won't be unique outside the mob type.

plush hare
#

a unique, persistent ID

#

I might go the GUID route, and then create network IDs starting from 0. When the client joins, just have the server send both GUID and network ID to map them together

#

that seems like the least frustrating route

winter yacht
#

Sounds like a plan.

wispy lion
# plush hare So I'm trying to write a component that attaches a unique ID to a gameobject in ...

I have done this for ScriptableObject

public class NetworkScriptableObject : ScriptableObject {
    [SerializeField] [ReadOnly] protected int networkID;

    public int NetworkID => networkID;

#if UNITY_EDITOR
    [MenuItem("Data/Regenerate NetworkScriptableObject IDs")]
    private static void RegenerateIDs() {
        List<NetworkScriptableObject> data = AssetHelper.GetAllAssetsOfType<NetworkScriptableObject>();
        for(int i = 0; i < data.Count; i++) {
            data[i].networkID = i + 1;
            EditorUtility.SetDirty(data[i]);
            AssetDatabase.SaveAssetIfDirty(data[i]);
        }
        AssetDatabase.Refresh();
    }
#endif
}

It requires regenerating when creating new objects, but you can use IPreprocessBuildWithReport to make sure they get regenerated when building. I feel like it should work the same with gameobjects.

#

(btw, I'm starting the NetworkIDs at 1, because the default for int is 0, so you can immediately know something is wrong if your id ends up being 0)

boreal pendant
#

Trying to follow a tutorial on player movement and dont understand these errors, any ideas?

plush hare
boreal pendant
#

which section then?

plush hare
#

Beginner

boreal pendant
#

alright sorry

crystal parrot
#

is MethodInfo.CreateDelegate(typeof(Action)) fast to call on IL2CPP?

pearl basin
#

i generate a byte array that represents an image ~30 times a second, it's 640 x 480, and is represented as [r1, g1, b1, r2, g2, b2, ...], how do i display this bytearray, or what's an alternative?

regal glade
#

I know there's some methods not entirely explained in this code, and it's a bit long so if nobody feels like it that's fine. But if anyone has the time I would really appreciate some input on how to speed this up. Basically I am doing some checks on tiles in a 3D array to determine whether they should be opaque, invisible, or semi-transparent based on character position and which room/building we're in currently, then I write this information to a 2D texture with SetPixels32 every frame.

The whole thing takes like 6 ms to execute and I kinda need to get it down, but other than re-designing it from the ground up I'm not sure if there's something else I can do, like change what kind of variables I access etc. I read something about structs above 16 bytes would be slower so maybe Color32's aren't great to iterate for example. Maybe I'm doing some slow things unnecessarily.

After line 262 the code kind of just repeats itself 5 times for different branchings

https://pastebin.com/enkXcJQF

flint sage
#

Have you considered doing this on the GPU instead?

#

(I'm not going to try to decode 600 lines of code tbh)

regal glade
#

Yeah that's fine I get that.
Do you think that could be beneficial? I am already doing some rather heavy raymarching with a compute shader.

flint sage
#

Sure, parallel execution is great

#

You can also just do threading on the CPU as well using Parallel.For for example

#

(Not for every tile but for sets of tiles)

regal glade
#

I did try Parallel.For but it slowed to a crawl. But I need to try it again as I think I wasn't doing it properly

flint sage
#

Of course depends on what exactly you're doing

regal glade
#

It was pretty difficult to figure it out with all the variables

flint sage
#

If you need to lock then it's slow af

regal glade
#

yeah do you need to lock for reading as well or just for writing?

flint sage
#

Depends

#

If you want to ensure that the data doesn't change until your calculation is done you need to lock from the read

#

But if you don't and you can guarantee that you won't write to the same indexes then you don't really have to lock in general

regal glade
#

mm right. i'm only reading and then writing information to a color array based on the information we're reading, so maybe if i can properly write to a buffer at the end or something. didn't quite get that part which is where i think the issue was.

flint sage
#

This all is assuming that your calculations are the heavy part and not the apply

#

also aplpy(false) is probably faster if you don't need mipmaps

regal glade
#

it's not the apply yeah i've tried that

#

oh ill try that right away

#

nah didn't make much of a diference

regal glade
#

Yeah Parallel.For with a thread limit of 4-8 seems to boost the frame rate a bit, from 120 to 180 or so. 12+ makes it slower again.

#

wouldnt mind getting it down more but it's a good start

regal glade
#

Paralleling the bottom most Y loop instead of the X loop popped it up to 300+ so I guess that's that 😂 Thanks for the pointers.

solar anchor
#

help! I have a .net framework problem

#

does someone know about .net frameworks?

#

and how to add them in vs to unity projects?

#

when I make a new project in VS i get the .net framework dependencies directly but when I make a project in unity I dont get them and when I want to install nugget it doesn't work because the frameworks are missssing

obsidian glade
sly grove
regal glade
#

I have a tool class that i assign as a field in a controller script, by making a new Tool(), and it works fine, but if I change any unrelated variable in that script it's like all the tools get cleared and I get reference not set errors everywhere. Is there any obvious explanation for this?

I could do this before but I have no real clue what might have caused this sudden issue. The only thing I could think of was that I enabled unsafe code execution but I already disabled that.

sly grove
solar anchor
rare sage
solar anchor
regal glade
#

@sly grove Don't really know what to show you. This is a bit of a mess but this is really pretty much all there is to it. I don't see how anything would cause changing a variable in the inspector at run time would cause such a wipe of the tools. If I debug.log the class itself I get (null) when it works, but once I change a variable it just spits out an empty space, while trying to print the .toolName it throws an error obviously.

#

Top script assignment is where it drops the tool

sly grove
#

can you show that in action

#

just seems like currentTool is null

#

I'd start by putting Debug.Log everywhere you're assigning that reference

#

If I debug.log the class itself I get (null) when it works,
Wdym by logging the "class itself"?

#

I don't see how anything would cause changing a variable in the inspector at run time would cause such a wipe of the tools
changing variables in the inspector will cause OnValidate() to run, for one thing.

regal glade
#

with the class i mean just Debug.Log("currentTool: " + currentTool); where currentTool is an EditorTool class

#

Yeah I don't do OnValidate either, only start and update and lateupdate

#

the variable (poop) i changed is not used for anything i just added it

sly grove
regal glade
#

it's a normal monobehavior

#

i haven't set anything special for it when it comes to serialization

#

and this did work fine before so

sly grove
regal glade
#

i have no clue what i might have done

sly grove
#

That would be your issue

regal glade
#

oh?

sly grove
#

You absolutely cannot create MonoBehaviours with new

regal glade
#

hmm alright let me try that

sly grove
#

they can't exist without being attached to a GameObject

#

Is there a reason it needs to be a MonoBehaviour?

regal glade
#

i was running Instantiate in another tool that inherits from the base EditorTool, to place gameobjects at runtime

#

but otherwise no if i can solve that some better way which i think i can

sly grove
#

You don't need to have it derive from MonoBehaviour to call Instantiate

#

Instantiate is a static method on the UnityEngine.Object class

#

You can just do using UnityEngine; and Object.Instantiate(...)

regal glade
#

yes! that solves it. thank you so much i would never have figured that out on my own, saved my day. 🙏

sly grove
solar anchor
#

I could reference the unity project to the other?

solar anchor
sly grove
#

no i mean going into unity external tools preferences and pressing the regenerate project files button

solar anchor
sly grove
#

Can you clarify exactly what you mean by "get access to the commands"?

solar anchor
#

I need to use the librarx

young wraith
#

Hi is there a collider.bounds.min equivalent in texture

sly grove
#

Collider is a component

#

Texture is just an asset

young wraith
#

makes sense

undone coral
potent shoal
solar anchor
#

how to change the targered .net framework to . net framework 6

#

it's always targeting 4.7.1

sage radish
solar anchor
#

i tried directly referencing the dependencies. that didn't work as one project still does target .NET 4.7.1

solar anchor
#

and is that even recommendable?

violet valve
violet valve
#

".NET 6" and Unity are beams that do not cross, despite similar naming conventions and the fact that both relate to C#. @sage radish EDIT: Sorry, I was pinging the wrong OP

solar anchor
#

ok sorry for mixing things

#

what do I have to do now to make it working?

violet valve
# solar anchor ok sorry for mixing things

No problem, it was a confusing nomenclature before. .NET 5 was the first version of Core to basically make "framework" obsolete, but again this doesn't have anything to do with Unity in particular. It's more about web and form applications. I haven't read your initial query - I just wanted to chime in on this versioning issue.

violet valve
#

@solar anchor A complete answer might require some investigation; I'm sorry I don't have time to try to replicate the issue and provide first-hand feedback.

solar anchor
#

Could not install package 'IotaWallet.Net 0.2.8-alpha'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.7.1', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

solar anchor
#

what would you recommend? or someone else? When I open a new vs project I can add the library without any problems. but if I make the project in unity and then open the project in vs...i get that error

violet valve
# solar anchor ok

If you're using NuGeT, you might be able to to target a lower version. I don't really know the product so I am just spitballing here.

#

Generally speaking, Unity is best guaranteed to be compatible with .unitypackage files. If you're trying to hook into external dependencies, you might be on your own. One reason for this is that Visual Studio doesn't compile your C# code when working in Unity... the Unity Editor notices when the file system changes and uses it's own compiler to produce CIL. Have you noticed that you never build in VS? @solar anchor

solar anchor
#

will the .dll contain the .net 6 or will it be needed again?

violet valve
violet valve
solar anchor
#

I want to use it for webgl

violet valve
# solar anchor I want to use it for webgl

If you're offering to pay for someone to figure out if this is possible, I might be interested but am not immediately available to take a look... though I could try to give you a timeframe. Being for webgl or not isn't relevant. "Unity" disqualified this use case against anything that I mentioned, because the creators don't base their product off .NET 6 or anything that it is used for.

solar anchor
#

i dont understand 😄

#

"Unity" disqualified this use case against anything that I mentioned, because the creators don't base their product off .NET 6 or anything that it is used for.

violet valve
solar anchor
#

ok I probably can't just build the vs project and put into the unity project?

violet valve
solar anchor
#

hmm

violet valve
# solar anchor hmm

So in other words, other libraries might be compatible, but Unity has it's own microcosm so it's not guaranteed.

limpid prairie
#

Hey guys, how do I access the "Navigation" tab at the top via scripting?

#

It's a tab from Window > AI Navigation

violet valve
#

@solar anchor .NET "framework" is officially discontinued since Microsoft has adopted targeting multiple operating systems with the same C# code. Any reference to that in Unity is kinda outdated, but I understand where the confusion comes from. You might think that framework 3.5 and .NET 6 are the same product, but they aren't.

#

@solar anchor For a general idea, search up .net core vs .net framework and just assume that .net 5+ is "core". That should give you a good overview of what these branches mean.

surreal vessel
#

do you keep your settings centralized or not?

#

curious

#

could do a static Settings class or just use playerprefs everywhere directly

violet valve
surreal vessel
#

i see

violet valve
#

The issue is, it might not take up a lot of data, but I don't trust Unity to uninstall anything in registry. It kind of leaves a mark on any computer where someone runs your game, whereby saving JSON to a flat file leaves something that they can delete. It's also pretty easy to do in C#.

surreal vessel
#

yeah but a lot of apps do it and its not an issue imo

violet valve
jolly token
surreal vessel
#

i was going to use PlayerPrefs everywhere where somethings influenced by a setting, but it doesnt have an onchanged event which is such a big flaw imo

jolly token
#

You can always swap implementation if you abstract settings.
If you use PlayerPrefs everywhere then you will pay technical debt when you have to modify or refactor them.

surreal vessel
#

yeah and also generally its probably a better idea to have actual variables instead of accessing things with string keys

violet valve
solar anchor
#

ok so can I make it work in unity or not??

#

😄

violet valve
#

You might be able to jerry-rig it, but that's an investigation task that takes time.

#

@solar anchor I hope I explained some of the concerns and potential difficulties clearly enough so you understand the scope of the question.

solar anchor
#

just creating a .dll from a vs lib projectis not the solution

violet valve
# solar anchor

You have to consider C# version and a great deal of dependencies. I don't mean to stonewall you, but it's potentially complicated and you wouldn't know to what degree until you try.

solar anchor
#

hmm no it seems to difficult for me

#

maybe better to make the web app without unity 😄

violet valve
# solar anchor maybe better to make the web app without unity 😄

It could be difficult for me too, which is my point. I can't guarantee anything without trying for myself, but I know I might be in for a doozy if I did. That's the bottom line: the research isn't obvious, so whoever explores this is guaranteed dedicating time to research with no certain end.

#

@solar anchor In other words, I don't know and if you want me to try to figure it out, I have to do real work. That's my warning and honest take on this.

solar anchor
#

sounds good

violet valve
solar anchor
#

hmm. I'm thinking about letting this wallet working over a server and let call the functions over unity api connection

#

and people identify/ login by metamask and then interact with the wallet functions on the server

#

but then the question: what is the best server config to have it secure and maybe decentralized

violet valve
violet valve
solar anchor
#

Ok thx.

violet valve
# solar anchor Ok thx.

Context is a big help in determining the best approach to things. We don't necessarily know what you are using or what the best practices are, but we can assess and give impressions.

candid shore
#

Hey guys, My problem is im trying to spawn points in my game randomly at random postion but i dont want them to spawn to close to each other so im doing a do-while loop to check if these points are close to each other but i think i unintentially amde an infinite loop and idk how or why its happning.
Heres code:https://hatebin.com/onwhutoojq
(Just look at the Toclose Bool)

sly grove
#

so you just end up in an infinite loop

candid shore
#

So what do i do?

sly grove
#

Add an escape hatch to your loops to prevent an infinite loop and attach the debugger to figure out how you're ending up in a loop and adjust your code to fix it.

candid shore
#

See

candid shore
#

like theres no points

#

bc the issue only happens when i want togenerate more than 1 point

sly grove
candid shore
#

ok

#

sorry

#

cyalater

kindred tusk
#

That will guarantee that they're no closer than two of the edge paddings

#

But will give you a more uniform distribution

raven raptor
#

Yeah, it looks like the distribution process is somehow breaking the "worlds" rules. Then it never completes a success check & death spirals.

regal olive
#

hey

#

how do i deal with ramps when using rigidbody based movement

#

because my movement treats ramps like stairs

compact fulcrum
#

Been working on my own kinematic car collisions but I'm stuck; I've two methods to test collisions: Physics.CapsuleCheck (can take rotations into account but doesn't return the Collision info, only the Collider you collided with), the other is Physics.CapsuleCast, that returns the Collision but won't allow me to test a specific rotation. I need the normal of the collision to make object slide, but if I rotate it, it will eventually get inside the other object's collider and stop finding a collision. Any other alternative (SweepTest won't let me set the rotation either)?

sly grove
#

You can cast a capsule with any rotation with CapsuleCast

#

(the rotation of the capsule is defined by the two sphere centerpoints)

#

Also note that OverlapCapsule works just like CheckCapsule but returns more information about what you overlapped with

#

though it won't give you collision normals, only CapsuleCast will do that

compact fulcrum
#

thanks! the rotation bug is the only thing I need to fix so I can move on; still can't get it right, but there must be an issue in my code (yet to give OverlapCapsule a try)

undone coral
#

did praetor not address your question?

compact fulcrum
#

I'm still trying the alternatives, there may be issues with the values I pass; I want to make sure before I ask for help again 😄

dapper nest
#

Hey! I'm trying to switch from using LINQ orderby to using a SortedSet with a IComparer implementation, but even though in theory it should be the same, the results vary widely, so was hoping someone could maybe shed some light on it.

// First implementation of sorting by lowest value. This is for pathfinding
// and works exactly as expected.
HashSet<Vector2Int> pool = new HashSet<Vector2Int>();
var bestCell = pool
                .OrderBy(c => (c - start).sqrMagnitude + (end - c).sqrMagnitude)
                .First();

// Second implementation, which produces wildly different results, even though in my mind, the result should be the same. 
class CellComparer : IComparer<Vector2Int>
{
    public int Compare(Vector2Int x, Vector2Int y)
    {
        int first = (x - _start).sqrMagnitude + (_end - x).sqrMagnitude;
        int second = (y - _start).sqrMagnitude + (_end - y).sqrMagnitude;
        return first.CompareTo(second);
    }
}

SortedSet<Vector2Int> pool = new SortedSet<Vector2Int>(new CellComparer());
var bestCell = openList.First();
jolly token
#

Also can't tell how is _start and _end are assigned

dapper nest
# jolly token Is it only typo that last line uses `openList` not `pool`?

both good questions!

using pool istead of openList because it is an assignment to optimize the script, so I am trying to stick to the original naming, which is pool. Though I agree it should be called openList.

As for the second one, both _start and _end is both private class variables that is set when the method for finding path is called.

#

The first implementation is using method parameters start and end directly, while I cache them in a private variable in order to access them through CellComparer

jolly token
#

It'd be better if you post original code with paste site?

dapper nest
#

Not really. Outside of changing how to store the Cells, the actual code does not change at all. What is posted above is the only change, as the code for adding and removing from the set is the exact same. And like mentioned, the issue only arises with the second example

#

But I'll post the whole thing

#

The only changes is commented out.

jolly token
dapper nest
#

The thing is that I am not sure it boils down to something like that either, as it really just breaks the entire system. Consider the example here, where green is the current position, blue is the position to pathfind towards. It will then follow the red path drawn

#

Even if it came down to tiebreakers, there is no way this would be the result

#

And like mentioned, using the original LINQ works perfectly as expected

jolly token
dapper nest
#

Ah. That might explain it.

jolly token
#

So you could try adding tiebreaker with tile position

dapper nest
abstract folio
dapper nest
#

Yes I could use a list, but the whole point is to optimise it, which a list would really not

jolly token
# dapper nest When you say using tile position as tiebreaker, how would you go about that?
public int Compare(Vector2Int x, Vector2Int y)
{
    int first = (x - _start).sqrMagnitude + (_end - x).sqrMagnitude;
    int second = (y - _start).sqrMagnitude + (_end - y).sqrMagnitude;

    int comparison = first.CompareTo(second);
    if (comparison != 0)
        return comparison;

    comparison = x.x - y.x;
    if (comparison != 0)
        return comparison;

    return x.y - y.y;
}

Something like this for example.

dapper nest
#

Ahh I see what you mean. That might be exactly what i'm looking for!

jolly token
dapper nest
#

I was under the impression that the comparison had to be either -1, 0 or 1

dapper nest
jolly token
dapper nest
#

I moved the changes into the already optimised version of the project, which seems to have completely fixed the problem. Thank you a lot for your time and expertise @jolly token !

jolly token
dapper nest
#

Now I am able to traverse a 10,000x10,000 grid in less than 0.05 seconds! very happy about that

leaden sandal
#
public static void ToFadeMode(Material material)
    {
        material.SetOverrideTag("RenderType", "Transparent");
        material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
        material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        material.SetInt("_ZWrite", 0);
        material.DisableKeyword("_ALPHATEST_ON");
        material.EnableKeyword("_ALPHABLEND_ON");
        material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        material.renderQueue = (int) UnityEngine.Rendering.RenderQueue.Transparent;
    }

    public static void ToOpaqueMode(Material material)
    {
        material.SetOverrideTag("RenderType", "");
        material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
        material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
        material.SetInt("_ZWrite", 1);
        material.DisableKeyword("_ALPHATEST_ON");
        material.DisableKeyword("_ALPHABLEND_ON");
        material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
        material.renderQueue = -1;
    }```

I am trying to use this code I found to change the rendering mode of a material to fade and to opaque but I get this error:
> Render queue value outside of the allowed range (-1 - 2449) for selected Blend mode, resetting render queue to default
This is where the code is from: https://forum.unity.com/threads/change-rendering-mode-via-script.476437/
I have tried changing the renderQueue to a range of things but I don't really understand it.
PS: I am trying to fade out a model and fade it back in again, it fades out okay but doesn't fade back.
undone coral
#

if you want to fade something out, you can
(1) tween its materials' alpha
that's it

#

you can't use C# overrides to turn any material, in a general way, into something that fades

compact ingot
undone coral
#

hmm

compact ingot
#

i'd suggest alpha clip dithering

undone coral
#

Built-In / URP* problems

compact ingot
#

transparents don't sort right (by vertex) in any pipe

undone coral
#

in urp and built in, it seems like a colossal number of 3rd party materials have weird z write settings

#

which interact with each other, and then it's bandaid after bandaid

#

hdrp 3rd party materials are all really the same material in disguise

compact ingot
#

good to know, i've only ever had those z sorting issues 😄

undone coral
#

i'm not really sure though

#

lol

#

certainly when i'm working on other people's code

#

this is what i see. i select all the materials, the third party ones, i reset all these z write and blend mode and other settings to defaults, and the image doesn't change except all the alpha and sorting glitches go away

compact ingot
#

best way is the AAA way: just say no to (intersecting) transparency

undone coral
#

yes the code snippet shared above does make it seem like people have trauma related to URP and Built in materials' alpha

cerulean scaffold
#

Hi everyone, can the serializedVersion field in .meta files be set to anything, or could that lead to some problems?

#

I'm asking because I would like to not worry about that field when making changes to .meta files manually

sage radish
sly grove
#

I actually don't see such a field in my meta files so 🤔

#

I see it only in prefab and scene files

cerulean scaffold
cerulean scaffold
sly grove
sage radish
#

Yeah, for backwards compatibility

leaden sandal
undone coral
leaden sandal
#

I know, but it's the only way.

undone coral
undone coral
#

what are you trying to do?

leaden sandal
#

Change rendering mode of an object via script

undone coral
#

i mean what it eh big picture thing you are tryihng to do

leaden sandal
#

Tardis

undone coral
#

fade a 3d object in and out?

leaden sandal
#

Yes

undone coral
#

and what do you obsreve that goes wrong?

leaden sandal
#

But it must return to opaque

undone coral
#

what does that mean?

#

like what is the issue

leaden sandal
undone coral
#

i know, but what do you see that is wrong?

#

like what do you observe that goes wrong?

#

i'm not trying to be annoying

leaden sandal
#

It's completely invisible when running the code

undone coral
#

there's going to be a straightforward approach to this

#

i just have to understand what you are trying to do

#

fade an object in and out?

#

is that all?

#

surely you see people do that all the time

leaden sandal
#

Yeah then return it to opaque mode

#

My mesh's aren't basic boxes so when left on fade mode with no transparency it looks weird

leaden sandal
#

Standard materials with smoothness off, specular highlights off and it's blue.

undone coral
#

okay

leaden sandal
#

And I'm doing it to multiple textures

undone coral
#

so you have a few options

#

i don't totally understand why you need to manipulate the material at all. you can make this material transparent, then tween the alpha when you need

#

using DOTween

#

and not do anytning else, and if it's really as standard as you say, everything will work

#

and you won't have to worry about anything

#

you haven't really said what the real issue is, like what hte visual gltich is or whatever you SEE or OBSERVE that is the problem

#

so don't get mad at me if i "don't understand"

#

because i've asked like 4 different ways

#

you don't ever have to switch it back to opaque

leaden sandal
#

I'm not mad at you at all I'm grateful that your trying to help

undone coral
#

okay okay

#

if you DO need to switch the material back to opaque, which again i don't 100% understand why you'd have to do that but i am so much more familiar with HDRP and URP and not built in which have fewer bugs overall with rendering

#

make two copies of the material

#

instead of modifying these settings

#

and don't touch z testing or blend modes or anything there

#

click reset, then set back up the color and textures, and change nothing else. and have two materials - one "transparent" and one "opaque" and reference it in your effect

#

it sounds like you observe a visual glitch when you leave your geometry at 1.0 alpha in transaprent material. is that correct?

leaden sandal
#

Yeah

undone coral
#

like another user said you can use dithered alpha cutout. but i think that's really a problem with all the other things you are changing

#

like just duplicaet this opaque material, click reset

#

then manipulate the alpha in the editor

#

with your object in the scene with the new, clean material assigned. do you see any glitches?

leaden sandal
#

No, when it's in opaque it looks normal.

undone coral
#

you just shouldn't be doing any of this enable and disable keyword stuff

#

okay

#

can you show me

#

can you create a new gray material

#

change it to transparent

#

put your model in your scene, and in the scene view, show it to me glitched

#

using a new material

#

then we can see what the underlying problem is

leaden sandal
#

I'm not at my PC right now. but I think just swapping between textures would work.

#

Materials*

undone coral
#

well don't say you did stuff that you didn't do

#

because i am telling you, you are doing something super screwy

#

your materials are messed up, and the C# code you posted is really messed up

#

it's a bunch of mistakes interacting with each other in a bad way

leaden sandal
#

There's nothing sepcial in the materials so I can just delete and restart them

#

And use alternating materials

undone coral
#

okay

#

that's good

opaque cape
#

I made a 2d grid array how do i remove the small ones?

compact ingot
opaque cape
#

Make sense, thank you.

jade grotto
#

Any way to limit an ICanvasRaycastFilter to just operate on the Graphic it's on, not children?

jade grotto
#

Looks like Image.alphaThreshold also affects it's children, doesn't seem right

muted crane
#

So it will get the component only in the parent

jade grotto
#

This isn't something I'm fully in control of, in Graphic.Raycast it does 'graphic.GetComponents<ICanvasRaycastFilter>();' then in a while loop goes up the hierarchy doing the same, which is how RectMask2D is able to filter clicks on it's clipped children

maiden creek
#

Hello im having problems figuring out how to add a feature where if you press on a npc, the npc walks to the designated point

#

Like in a video, you can see when you press on an npc it walks to the stairs and some even go there them selfs

#

How do i do that is im using SpawnObject() and every npc has the same script so if in code it to travel to specific coordintes all npc clones go there

#

I need only the clone that i pressed to do that

#

What script do i need to use?

maiden creek
# maiden creek

To see it better. The question mark the question mark pops up above them.

slender stag
#

I am making a dll for unity, but it keeps crashing after I add a component the component adds, but is missing an array. I recompile the library, and unity recompiles, shows the array, I change the array length from 0 to 5, unity crashes.
Tried on Unity 2022.1.23f1 and 2021.3.13f1 LTS.
Library Info: Target Framework .NET 5.0, refrences UnityEngine assemblies from <unity hub path>\2022.3.13f1\Editor\Data\Managed\UnityEngine\

jolly token
slender stag
#

What should I target?

jolly token
slender stag
#

I have .NET Standard 2.1 and .NET Framework

jolly token
slender stag
#

It was set to .NET Standard 2.1... Pretty sure .NET Framework is more up-to-date?

jolly token
#

So your library should target .netstandard2.1

warm forge
#

This isnt the same script

jolly token
#

Yeah that’s not PauseManager

undone coral
#

can you share a snippet of what you already have?

clever urchin
#

So I have a question to do with compute shaders and collision meshes.

I'm currently using the GPU to draw my map for performance reasons, this map is destructable. It's a 2D grid of tiles essentially however i'm having trouble generating a collision mesh for this

#

What is the best way for me to generate a collider from a 2D grid of points, could I do a bounding box search in the grid to get the perimeter of each collider and generate it that way some how?

harsh matrix
#

are you familiar with distance fields

clever urchin
#

No but they look very similar to what I want ha

harsh matrix
#

you can basically sample your space and give it a value, say <0 = ouside and > 0 inside

#

then jsut build a mesh connecting the sample points where it's 0

clever urchin
#

Oh neat, it looks like it can be parallelized too?

#

So I could just compute buffer calculate it, generate the points and make a mesh collider from connecting those points together?

harsh matrix
#

if you can be sure all 0 points have 0 neightbours, you can build a compute shader that checks its 8 neigbours

#

basically, your sample space needs to be somewhat continuous,

clever urchin
#

Ok I might be able to work around that

#

Since the terrain is destructible, i'm not sure how that would affect sampling. But I know the original setup will be fairly simple and can just modify the collision mesh on destruction or something

#

But yeah thanks so much for that, I appreciate it

harsh matrix
#

i think that deep rock galactic does somethign similar to this but 3d

clever urchin
#

That looks complicated asf lmaoo

harsh matrix
#

being destructible shouoldn't matter, as long as the system you use to generate the original map works, you just need to run the same code when you change the map right

clever urchin
#

Yeah, the map just might change a lot so I wonder if chunking it would be better performance

#

Guess I just need to play around

harsh matrix
#

yeah

#

worry about chunking later, get this system working on one chunk

#

don't preoptimize, you're working on a tricky problem

clever urchin
#

Yeah cheers

harsh matrix
#

hack the hell out of it until it works

#

have fun haha

clever urchin
#

Think like Terraria, except everything I can put on the GPU is going to be on the GPU

harsh matrix
#

i expect every pixel to be a voxel

clever urchin
#

Legit what it is lmao

#

Except 2D because 3D sucks :^)

harsh matrix
#

if you're working on computer shaders already, you can definitely do what your'e doing with 3d voxels too

clever urchin
#

Yeah, I think the jump isn't as big as I think it is. I just want to see how I go with 2D for the moment

#

Im a big fan of 2D games like terraria :)

harsh matrix
#

me too, lmao

#

i'm working on a 2d tile based rpg jsut to see how much tech i try to put into a low tech game

clever urchin
#

That sounds sick

harsh matrix
#

i am sick

#

i can't jsut

clever urchin
#

Lol

harsh matrix
#

not try something stupid complicated

#

i have a problem

#

it's ruining my life

torpid plaza
#

can someone help me with mathlerp

clever urchin
#

Yeah thats me with shaders, ever since discovering compute buffers and stuff like a year ago i've been trying to do everything in a shader

harsh matrix
torpid plaza
#

when i crouch the player goes to 0.5 and then when i let go of control it goes back to 1

#

so i figure i can use mathlerp right

harsh matrix
#

you need to give more details

#

this is not really the chat for that kind of problem though

#

check out general or beginner

#

@torpid plaza where are you trying to use mathf.lerp

torpid plaza
#

if(Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 2f, ForceMode.Impulse);
}

    //stop crouch
    if(Input.GetKeyUp(crouchKey))
    {
        transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
    }
#

@harsh matrix

#

i figure i was going to add it on the if statement for stopping the crouch

#

but i probabaly need to do it on both

harsh matrix
#

where would you use the lerp?

torpid plaza
#

on both if statements?

harsh matrix
#

can you show me how you would want to use it

#

liek show an example

torpid plaza
#

if(Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
rb.AddForce(Vector3.down * 2f, ForceMode.Impulse); ???????????= Mathf.Lerp(startYscale, 2, crouchYScale);
}

    //stop crouch
    if(Input.GetKeyUp(crouchKey))
    {
        transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);          = Mathf.Lerp(startYscale, 2, crouchYScale);
    }
#

hold on

#

@harsh matrix something like that i guess but i don't know what variable to use to set it to

#

im not even sure if mathlerp would work someone suggested it

harsh matrix
#

why do you want to use lerp here?? the code ytou have looks fine

torpid plaza
#

because when i crouch it just snaps back to 1 in a instant

#

itt's too snappy

harsh matrix
#

oh you wantlike a smooth change?

torpid plaza
#

yeah

harsh matrix
#

ok you need to use a coroutine

#

are you familiar with those

torpid plaza
#

no

harsh matrix
#

ok can I DM you

torpid plaza
#

yeah

quiet bolt
#

You could also use DoTween

#

So you can just make a one-liner that will smoothly transition over time

real blaze
#

or AnimFlex :p (just transform.AnimPositionTo(end, duration) or use Tweener.Tween(getter, setter, endValue, duration, delay, ease) if you feel like u wanna go deeper! )
https://github.com/somedeveloper00/animflex
free and open source. and you'll get 40% performance boost too 😁

GitHub

Contribute to somedeveloper00/AnimFlex development by creating an account on GitHub.

#

anyways

I have a problem with a manual physics scene having to iterate a dozen times per fixed update. issue is that the onCollisionEnter doesn't work as expected

#

I'm doing custom bounce mechanics in the onCollisionEnter, and when I do the physicsScene.Simulate() a dozen times in fixed update, the results will actually be different. I assume it's because some transformation resolving phase is being ignored when we do the Simulate more than once in a row, right?
this seems like a common problem but I couldn't find anywhere for a solution. does anyone have any suggestion?

real blaze
#

I solved it by calling FixedUpdates manually before doing ps.Simulate(), like Unity's own physics event timeline

#

to get all the required FixedUpdates, I created a global SO that holds a list of delegate void FixedUpdate()s and then each script will subscribe and unsubscribe to/from it themselves

#

and that fixed my problem.

#

tldr: make sure to manually call all necessary FixedUpdates before each call to physicsScene.Simulate()

tiny ocean
#

How would I specify a ToString formatter in a com.unity.localization Smart String?
I'd like to use the N0 specifier to emulate a ceil()
My smart string looks like this
{Cookies:plural:1 Cookie|{} Cookies}

hybrid prism
#

Hi
How can I debug ILPostProcessor inherited class (codegen after compilation)?

muted widget
#

https://gdl.space/nujatufago.cs

Any ways to speed this up a bit? I removed Recalculating Tangents because I am not using normal maps here. I don't typically work with meshes, so the more I can learn the better. Sorry, code was too large to send here 😛

flint oxide
#

I'm trying to burst some code via jobs and is unable to use System.Guid.ToString() in debug messages... any ideas?

sly grove
flint oxide
#

yeah so it seems like I need an alternative way to see the bytes in the Guid to print it out, mmm

sly grove
#

Can you just run the code without burst/jobs to debug?

#

I think that's usually how I did it

flint oxide
#

yeah but then it's hard to debug parallel problems 😦

sly grove
#

It's always hard to debug parallel problems 😉

misty glade
# plush hare So I'm trying to write a component that attaches a unique ID to a gameobject in ...

I ended up going to SO & prefab route and it's not bad. The end consumption is two lines of code (get a prefab by enum, then awake it - it'll destroy itself with a coroutine that sniffs the particle system duration).

Getting the actual effects to show up in the UI is no problem. 🙂 FWIW I'm using the mob-sakai particle effect library since it's.. really nice to use with UGUI based applications without fiddling with cameras and z-ordering endlessly

lunar jackal
#

any idea how I can change the background image of an IMGUIContainer in my programming? The docs stated nothing usefull, and in the forum I found no such topics

compact fulcrum
sly grove
undone coral
#

how is it controlled? joysticks?

compact fulcrum
undone coral
#

or a single mouse

#

also, did you make the vehicle model?

compact fulcrum
compact fulcrum
#

And in my tests there, it worked nicely with touch controls

undone coral
#

when i say with touch, i mean not with virtual joysticks

#

it would be an interesting problem to solve: how do you do drifting with touch, and no virtual joystick

#

in my experience people try to draw a doughnut with their finger and they expect the car to do a doughnut

#

which is very very interesting and sort of hard to do

compact fulcrum
#

oh that I haven't tried, would have to take a look at the games that do it

potent shoal
#

I'm really struggling with this. I have no clue how to get System.Security.Cryptography.Cng working in unity.

#

I have added System.Security.Cryptography.Cng, as well as System.Security.Cryptography to my assets folder.

sly grove
#

Does Unity not include System.Security automatically?

potent shoal
#

Apparently not.

undone coral
potent shoal
#

What version of the .net framework does unity use?

undone coral
#

however its implementation of netstandard 2.1 is incomplete

#

what is your goal?

potent shoal
#

I have a library using ECDiffieHellmanCng, which is a member of System.Security.Cryptography. I'm finding the versions are inconstant.

undone coral
#

okay. first step is to disable version verification in player settings, if that is all the issue is

#

that's what i assume you mean by "versions are inconstant [inconsistent]"

potent shoal
#

yes

undone coral
#

okay

#

so you'll wanna start by checking that box off

#

here's the big obstacle with what you want to do: if there isn't a managed implementation of the cryptography api you want to use, and it's not specifically supported by unity, you should only expect copying and pasting DLLs from nuget or wherever with the cryptography implementation to work on windows

#

there don't exist managed implementations of everything and there never will. what library are you trying to use? have you been trying to get iota to work?

#

is that what you were doing earlier?

potent shoal
#

I'm just trying to setup encryption for my game client and game server.

undone coral
#

or why is this cropping up? like what library are you trying to use

#

okay

#

you're trying to encrypt a TCP connection?

potent shoal
#

Yes, and it works fine outside of unity, which is where my master server resides.

#

My class is this

undone coral
#

okay, lemme ask you this first. do you think there is a standard way to encrypt a TCP connection?

potent shoal
#

I am not trying to encrypt the connection, but rather certain data going across the connection.

undone coral
#

hmm

#

what is the idea?

#

for anticheat?

#

what is the threat you are trying to prevent

potent shoal
#

It handles authentication for players, authentication for game servers, server spawners and also token authentication.

undone coral
#

your approach is dead in the water because a bunch of this stuff won't work, ever, in unity's .net environment, so let's at least talk about what makes sense

#

without getting mad or telling me this "already works"

#

which you haven't done yet and i appreciate

#

so what is the threat

#

i'm going to show you that there's no difference between encrypting the connection and encrypting the data going across the connection, for all your threats

#

so we can save the time

potent shoal
#

I see

undone coral
#

you should be using an SSL stream with tcp client, i.e., using TLS, if you want to make an encrypted TCP connection. you can also use http/2 or http/3, which supports bidirectional streams and will give you enterprise-grade security out of the box

#

sslstream is supported by unity and you should choose tls3 or whatever is the latest version when you choose a protocol

undone coral
#

if you have a realtime game, you can use websockets, which are very low overhead compared to raw tcp. if you need UDP connections, there is a ton of work if you ever want to have more than 1 server

potent shoal
#

I see

undone coral
#

i mean if you are trying to do this yourself

#

if you use a vendor it's way easier

#

like photon or whatever

potent shoal
#

My master server is setup in the way that makes the most sense to me. I built an entire framework to spawn and manage my game servers. I found that I preferred to use a TCP based connection, rather than HTTP for my master server.

undone coral
#

here's one perspective

#

yeah really hard to say without knowing what game you're making

#

which i would be happy to talk about

#

i personally use grpc, but it is extremely arcane to get that to work in unity

#

and it's low yield for anything but the most complex games

potent shoal
#

To elaborate a little. I have a game server which uses FishNet framework. However, I still need to interface the client and game server to a master server, and for this I've chosen to take my own approach and built my own network transport.

#

My game is fast paced, and uses client server prediction, something that took me years to understand, and my solution requires that I use UDP for that purpose.

#

As far as my master server connections, these all use TCP.

undone coral
#

okay

#

well

#

i don't doubt you can write all this stuff

#

you should use TLS

#

if you want to encrypt a TCP connection

#

on your backend server, you can similarly use TLS as a standard

#

alternatively, you can use a TLS proxy (an SSL terminator feature in something like nginx or traefik) on the backend

#

so that your server does not have to be aware of certificates or anything like that

#

you can use a self issued certificate, naturally, it's not a website