#archived-code-advanced
1 messages · Page 29 of 1
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?
Exactly. And again your game might want those events
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?
Not at all
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?
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.
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"
these functions are almost written already in the form of linq queries, e.g myList.Where(card => card is HealthType).Shuffle().Take(n);
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.
Right because he envisioned stuff like "every time you pull a card, gain one health"
Or "if this card is drawn, lose one health"
Sure, I'll be doing stuff like this, I just need to keep track of the results as well
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?
Ask the developers?
I guess I can log an issue and wait.
hmm nugetforunity doesn't really work
what is your goal?
like what kind of application are you making
in @obsidian glade 's example, you get those linq functions and more for free by declaring an IReadOnlyList<T> implementation 🙂
yeah in my experience the seemingly most elementary thing winds up interacting with other stuff in your game
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
honestly you have one of the more interesting problems that goes into this chat so apologies for all the attention it gets. get cracking!
i can keep thinking of real examples
Discovering from an opponent's hand - now you're not using the deck anymore
Yeah but a significant of them would be from card games, right?
yeah just because that's what i'm familiar with
Like, there's no "Hand" to discover from as there are no actual cards
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"
😵💫
Right, that's like 4 layers down though
Potion of Theft: "Discover an item from an enemy's inventory."
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
I am having a time disjointing the effects as far as possible from the items, etc
Lucky Armor: "Whenever you would roll dice, your unlucky 1s become natural 6s (or 20s)"
Like, pulling the effect "TeleportPlayer" out of the item and instead making it a generic effect
and then items are collections of effects
yeah
Different effects are active/usable at different moments
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;
}
}
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
almost ready
so I'm working towards getting the effects into dropdownlists they can pick in the editor
on the scriptableobject for the item
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
@frozen badger a lot of stuff is too hard to program as data - https://github.com/hiddenswitch/Spellsource/tree/master/spellsource-game/src/main/java/net/demilich/metastone/game/spells/custom or see the equivalent in XMage
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
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
Not really, like the fireball spell rarely changes the ice bolt spell
have you used the starcraft 2 editor at all?
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
okay
so you would know how it's like, a tree of random crap
to implement spells right
this is very similar
Sure
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
Hi, how can i make a dribble system for a football game like this?
Procedural running / dribbling soccer ball in Unity in C#.
Because I get errors saying my struct doesn't support the equals operator
huh TIL to compare structs you need to override the equality
never needed to do that apparently
which is less expensive way to find closest gameobject unity ? looking to make shoter game
ValueType.Equals automatically call Equals for each members, but causes boxing
And no default == operator for structs
did you still need help with the overrides?
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;
Also implement IEquatable<T> when using the code ^
ahh yes
afaik i've avoided boxing in this as well
(obviously replace Test with your type)
Yeah if it implements IEquatable<T> then EqualityComparer<T>.Default would not do boxing
I posted in several places and got a bunch of different responses, I'm reading through all of them now.
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
this is the eh
standard way
Wait for C# 10 then we can use record struct 😄
So obj is Test b simultaneously checks if it's that type, and declares it as a variable referenced by b, at the same time?
pretty much
b becomes the type Test as well
so its like testing and casting at the sametime
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
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
so I should have either the equals or the gethashcode but not both?
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
I saw it in a forum post and realised the guy in it was making a class and not a struct
well you can zombie together a solution if you want
but make sure you understand what you are doing
don't just copy paste
I guess that's one disadvantage of getting a bunch of answers from different places
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
As in any gameobject? How often are you calling this function, and for what purpose?
An easy solution would be to simply use FindObjectsOfType using the GameObject type, then iterate through a for loop getting the Vector3.Distance values between their transform's position and the specified position you're checking against. Then get whichever object has the shortest distance
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
thanks for the info @pliant crest
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?
Hi I'm having a problem detecting collider bounds if it's circlw
*circle
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
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
avoid branches or combine them into variations that you actually need
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
you should never scale rect transforms
How so? Seems to work as expected
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
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
afaik the whole ugui system basically ignores scale
So it seemed kind of intuitive to just scale & translate
why would the two be related?
do you have any screenshots of your game?
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 🙂
Need a bit more details than "does not quite work"
Because both are basically outside assemblies dealing with your game assemblies from the outside
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.
are you familiar with unity barracuda and onnx
I have heard of Barracuda. Will it be suitable for developing a C#-only model?
what is a C#-only model?
what are you trying to do?
Well one I could script only using C#. I am doing this for an assignment so I can't use anything apart from C#.
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!
is your model a neural network?
It could be a Recurrent NN but that's not a strict requirement. I could basically use a stochastic model as well in my case.
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
To train a model to classify different types of "standard" (not mathematical) knots.
The game itself is a simulator of sorts where the player gets to toe knots in different scenarios.
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).
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.
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.
i don't know if it makes sense to do this generally, you will be able to figure out what knot is tied analytically
huh?
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
Yes! That's what I was thinking as well.
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
Do people use ML Agents for classification tasks, because from my experience we were basically doing RL there.
nobody sophisticated uses ML Agents
all of this stuff has a rounding error of adoption, so it has a lot of bugs
I searched far and wide but I got nothing. I'm running out of time as well tbh.
I'll take a look at the other approaches and see if I don't spring a trap full of bugs.
Me too. Can I ping you later?
okay based on some light googling
my suggestion is, don't do this lol
is it essential to identify the knots? what about making some funny gameplay instead
Hello, i got a 2d grid array how do i target the outline of the grid to spawn stuff like resources.
like tying the rope around a bunch of different funny objects as levels, and they are your qwop game
the algorithm you are looking for is for "edge finding"
when you say outline of the grid, you mean the "walls" in this cave right?
Yes
praetor also gave you
a way to look for adjacent nodes
you can visit every grid point and check
I see, thanks for the help.
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.
#854851968446365696 dont crosspost
My mate, IDing knots is the main function of my project!
since you know a lot more about this than i do - if i showed you a picture of a knot, which is a rope and clearly you can see at every intersection with itself (or another rope), which rope is "under" versus "over" - would you be able to identify the knot?
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
The data is directly the coordinates of a spline representing the rope, and not some image.
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
I get what you're saying. There are existing projects doing knot image recognition.
if your project is all about IDing knots
surely you've made an attempt at doing this analytically
where did that go?
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;
}
}
are you asking if there's an IsValidJson method?
Pretty much
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
lol
Search across a half million git repos. Search by regular expression.
it's pretty grim out there
Not yet! I'll explore that option too.
i think you do try to parse it and see what happens
well if this is all your project is about then you should be spending 110% of your time doing this
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!
Which I can't because there's more work on total, but this is a start.
First link I check lol
Oh well, thanks 😛
I'm afk actually, will elaborate further soon.
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
how do you make a jagged nativearray that refrences a struct?
@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.
Does someone know how do I make some code in FixedUpdate() occurs before other script that also uses FixedUpdate() in it's logic?
there was something in project settings iirc @signal reef
Change that script's Execution Order.
i didn't know that mouse has z @_@ or does it just set 0?
either way it should've been fine, but from the colors it looks like VS isn't set up properly
Oh I googled it here, gonna try it, thx man 🥹
This is supposed to detect depth for thr raycast, but im not sure, thats what im having trouble with, and the error it displays confuses me too
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
How would I set it up correctly I thought I did everything right.
i checked docs and Z isn't used for screenpoint to ray
depth of ray is what you have set to 100
huh, weird, you mentioned an error in Line 32
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
oh interesting, ill give it a go
wait, is there a camera in the scene?
yes
then yeah check how to configure VS for unity if it still complains
alright, Ill need to check
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
If it's completely bouncy then just Vector3.Reflect should be enough
it's not bouncy
what are you actually aiming for, and what's the reasoning behind adding the velocity and then multiplying by magnitude again?
I'm aiming for a velocity that doesn't go into the wall but still goes along the direction it was going in. adding the reflected velocity should cancel out the movment towards the wall
and what isn't working about it?
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?
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?
#854851968446365696 please post code as text not images
My bad
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
you can set the material offset to Time.time. why would this be expensive?
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
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
Hi can someone help me https://stackoverflow.com/questions/74542789/dont-include-pixels-outside-of-prefab
{
"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
I was thinking about this earlier! The data could be shifted on its axis by some set of indices. Half of the data could also simply be flipped about the central index.
I need to get this up by Dec 19, along with some other stuff like some basic scenarios demonstrating certain knot types.
For now I won't be doing more than 3 types, so just one overhand knot, and a few other hitches and bends should be enough.
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
Simple overhand knots are easy to make, and the weird spikey gizmo is essentially a representation of the normalised coordinate displacements.
I can record a number of different configurations like this and then proceed to synthesise more data from these original recordings.
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 ?
Anyone ?
probably the exact same way as when you tell character to walk up to the object before picking it up
That's the whole point of IK
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
Weird, in the case of unitys inbuild IK it did not. It only moved the arm, not the upper body
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
You have to configure it properly to include all the joints you want to move
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
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
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 :/
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?
one consideration is to not use jagged arrays, since you don't have to
Multidimensional arrays can always be flattened into 1D arrays
you can also use a NativeHashMap to map coordinates to the faces
hmm interesting
I have done some searching and it seems like structs of nativearrays isnt possible either so I will look into it
You can use Quaternions for rotating your boundaries vectors or whatever.
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?
This is the job system yes?
yes
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
what about regular functions? do they not work as well
static functions work
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
this isn't a lambda, this is an expression bodied method
this needs to be declared static
I had a question in #archived-code-general but it seems to need some experts from here 😄
ok it works now thanks
you're at the start of a long journey
do you have a screenshot of your game handy?
yeah i currently have 2 character
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?
i just want basic customization like shoes and some other things
i have the models
anybody has photon example for help me
basicallay
just a basic world
player just log in
after making basic edits
change hair
skin color
shirt top bottom
So ur using photon to store data onto a cload server?
i using cloud
can we save
prefab data
and load them?
cloth1 activated after cloth2 deactivated
this sounds like #💻┃code-beginner
i think so
Beginners know how to save data to cloud?
i researched but i cant find any doc
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
they don't but it's a good place to ask and get some guidance
hmm
i checked assetstore
why we dont have any
multiplayer supported character creator
Cuz nobody made it
;.;
if you could share a screenshot of what you have
maybe i can give a specific recommendation
just the screenshot
okey
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
okey give me a sec
how can i integrate them
i can currently select male or female
i wanna add cloths shoes etc
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?
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?
Are you on hdrp?
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!
Does anybody know or suffered with similar issues?
that code is so cursed you could as well ask that in #💻┃code-beginner
but the fps drop isn't related to it
Nope, URP for this project
Any clue what the FPS drop could be caused by then? It only occurs when the mouse is moved to rotate the camera during gameplay, and that’s it. No clue if there’s some setting which causes this behaviour and has accidentally been enabled or something
https://youtu.be/5JN9n1Lsp8g could be this
why not just profile it
asking us isn't gonna help that much
but yeah ^
I did, the profiler doesn’t report any frame drops
That rendering graph looks like it's just more complicated and expensive rendering
Go disable vsync and see then
looks like most of their wait time is from vysnc
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()
does this not happen in the editor?
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
mind sending a screenshot of that?
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
is this true throughout the spike?
Enable deep profiling and see what is in there
Know that getting particle effects to show up in the ui is not straight forward.
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
I think this will depend on your networking solution.
custom
I just increment a static integer every time a mob is spawned. This id won't be unique outside the mob type.
It needs to be attached to scene objects when the game isn't running
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
Sounds like a plan.
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)
Trying to follow a tutorial on player movement and dont understand these errors, any ideas?
Not for the advanced section pal
which section then?
Beginner
alright sorry
is MethodInfo.CreateDelegate(typeof(Action)) fast to call on IL2CPP?
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?
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Have you considered doing this on the GPU instead?
(I'm not going to try to decode 600 lines of code tbh)
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.
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)
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
Of course depends on what exactly you're doing
It was pretty difficult to figure it out with all the variables
If you need to lock then it's slow af
yeah do you need to lock for reading as well or just for writing?
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
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.
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
it's not the apply yeah i've tried that
oh ill try that right away
nah didn't make much of a diference
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
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.
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
For more information, contact the package author.
Have you looked at https://github.com/GlitchEnzo/NuGetForUnity
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.
You'd have to show some code and the exact errors etc
this is not the solution as it works in vs without unity....
Managed to find a solution to this, turns out a package I added to the project was taking up a bunch of frametime but it was only visible in EditorLoop, which is why the performance spikes weren't visible when profiling the built version of the game
Thanks to everyone who tried to help out though!
i installed nugget in unity and were able to get the nuggets. but I think the problem still stays. I cant access the commands
@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
wdym by "once I change a variable"?
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.
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
Is the EditorTool serializable/serialized?
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
It's a MonoBehaviour that you created with new()?
i have no clue what i might have done
That would be your issue
oh?
You absolutely cannot create MonoBehaviours with new
hmm alright let me try that
they can't exist without being attached to a GameObject
Is there a reason it needs to be a MonoBehaviour?
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
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(...)
yes! that solves it. thank you so much i would never have figured that out on my own, saved my day. 🙏
help please
hav eyou tried regenerating project files?
I could reference the unity project to the other?
what do you mean? replacing them?
no i mean going into unity external tools preferences and pressing the regenerate project files button
yes
You mean to get access to the commands?
Can you clarify exactly what you mean by "get access to the commands"?
I need to use the librarx
Hi is there a collider.bounds.min equivalent in texture
makes sense
you can load a texture from bytes in the Texture apis
I've been looking all over for an answer to this issue, but I'm kind of lost. Does anyone know why this is happening?
#archived-code-general message
how to change the targered .net framework to . net framework 6
it's always targeting 4.7.1
.NET Framework 6 doesn't exist. You're probably thinking of .NET 6, which isn't supported by Unity.
ohh 😦 is there a way I could use this library anyway? https://github.com/IOTA-NET/IotaWallet.NET
Iota or Shimmer Wallet Library focusing on Stardust. For C# CSharp .NET implementation of wallet.rs using rust bindings and P/Invoke - GitHub - IOTA-NET/IotaWallet.NET: Iota or Shimmer Wallet Libr...
i tried directly referencing the dependencies. that didn't work as one project still does target .NET 4.7.1
but is something like that possible? having 2 projects and calling from the unity project the pure vs project with .NET 6?
and is that even recommendable?
.NET 6 is a buzzword that has nothing to do with Unity. I haven't read anything above this comment, but I can tell that someone is using words where they don't belong.
Ah. So, .NET framework is a platform that targets features for windows. .NET 5 and beyond are actually extensions of .NET Core, which is a totally separate product from "framework". You're comparing Android to iOS here.
".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
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.
here
@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.
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.
ok
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
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
hmm ok I see. could I build in vs the working lib and move the new .dll to the unity porject?
will the .dll contain the .net 6 or will it be needed again?
Possibly - I don't want to promise anything. I would have to experiment a bit, which is probably your job at this point. IIRC, Unity is locked at C# version 10, despite the current modern version being 12 or higher, so it's possible that the resource isn't using the same language.
Your video game is neither a website, nor a windows presentation application, so .NET 6 has literally absolutely no connection to what you are doing.
i could pay for the solution to use this lib in unity
I want to use it for webgl
not sure about that
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.
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.
.NET 6 is a totally different product. Unity's C# backing isn't related at all. .NET and C# version are not the same thing.
ok I probably can't just build the vs project and put into the unity project?
Unity uses a locked version of C# and provides it's own compiler, so it's on a different release schedule than most of what you can find on NuGeT.
hmm
So in other words, other libraries might be compatible, but Unity has it's own microcosm so it's not guaranteed.
Hey guys, how do I access the "Navigation" tab at the top via scripting?
It's a tab from Window > AI Navigation
@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.
do you keep your settings centralized or not?
curious
could do a static Settings class or just use playerprefs everywhere directly
I personally avoid saving stuff to registry if I can help it, which is what playerPrefs does. My minimum is to encode to json and store in a flat file.
i see
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#.
yeah but a lot of apps do it and its not an issue imo
You can absolutely be as shitty as the rest; I won't criticize that. You do you.
There is no downside of abstracting playerprefs with your own setting class
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
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.
yeah and also generally its probably a better idea to have actual variables instead of accessing things with string keys
PlayerPrefs is intended as a storage destination, not a mechanism. It works well and is resistant to install/reinstall, but works via resources that the average PC user doesn't understand. It's not egregious if you use it, but if you're asking about reason for/against, you'll find plenty.
Give it a shot and let us know. Without spending time investigating myself, I can't tell you any more.
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.
just creating a .dll from a vs lib projectis not the solution
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.
hmm no it seems to difficult for me
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.
sounds good
I wish I could connect the dots a bit more directly, but a solution isn't obvious. :_
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
I would implement this and then come back here with your configuration in tow. Information security is a trade and the interpretations are distinct and wide.
Implement what?
Implement "the wallet server", then report here with your settings and we can maybe offer advice.
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.
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)
kind of a #archived-code-general question, but it seems very possible/likely for your code to get into a state where it is not possible to generate a point that has not been chosen already or is not too close to another chosen point already. You don't have any guard against that or escape hatch for too many iterations
so you just end up in an infinite loop
So what do i do?
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.
See
what do you mean exactly?
like theres no points
bc the issue only happens when i want togenerate more than 1 point
I'm not going to handhold you through debugging your code in #archived-code-advanced
Instead of doing a check, you could divide the world into squares and then place the points inside each square with a minimum space from the edge
That will guarantee that they're no closer than two of the edge paddings
But will give you a more uniform distribution
Yeah, it looks like the distribution process is somehow breaking the "worlds" rules. Then it never completes a success check & death spirals.
hey
how do i deal with ramps when using rigidbody based movement
because my movement treats ramps like stairs
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)?
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
this looks nice
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)
what do you mean test a specific rotation
did praetor not address your question?
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 😄
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();
Is it only typo that last line uses openList not pool?
Also can't tell how is _start and _end are assigned
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
The thing is the code you posted seems to be modified from the code that is running, so it is hard to tell if there is any bug or not
It'd be better if you post original code with paste site?
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.
Thanks, maybe it's tiebreaker issue? How different the result is?
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
Thing is SortedSet does not allow element with same priority
So if your Compare methods returns 0 for two different tiles, one will not be added
Ah. That might explain it.
So you could try adding tiebreaker with tile position
When you say using tile position as tiebreaker, how would you go about that?
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=net-7.0#system-collections-generic-list-1-sort(system-comparison((-0))) If you can use a plain ol' List<T>... I like this first method.
Yes I could use a list, but the whole point is to optimise it, which a list would really not
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.
Ahh I see what you mean. That might be exactly what i'm looking for!
Also I would pass start and end to constructor of CellComparer than using static variables 😄
I was under the impression that the comparison had to be either -1, 0 or 1
Fair point. This was kind of just thrown together quickly for the sake of getting help. But thank you for the great assistance
As long as the sign is consistent it will be fine, try and let us know how it went
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 !
Nice, good luck with your project 😄
Now I am able to traverse a 10,000x10,000 grid in less than 0.05 seconds! very happy about that
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.
hmm. why are you doing this
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
seems like there is an issue with z-sorting and the object is supposed to render opaque while not fading
hmm
i'd suggest alpha clip dithering
is this Built In Render Pipeline Problems
Built-In / URP* problems
transparents don't sort right (by vertex) in any pipe
i have had a good experience in hdrp dealing with alpha
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
good to know, i've only ever had those z sorting issues 😄
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
best way is the AAA way: just say no to (intersecting) transparency
yes the code snippet shared above does make it seem like people have trauma related to URP and Built in materials' alpha
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
I think it's safe to assume it's used for something
I actually don't see such a field in my meta files so 🤔
I see it only in prefab and scene files
I see it in texture files aswell. Maybe it depends on the Unity version. I'm on 2022.2.
I wonder what it's used for 🤔
probably for when the serialization format of the class changes
Yeah, for backwards compatibility
You can, I am switching a mesh between rendering modes in order to remove the weird effects that appear when using fade on my model. But sometimes it needs to be on fade.
well you can, but it won't work 100% of the time
I know, but it's the only way.
yeah if you imported asset store assets from an earlier version it would need to migrate somehow.
i don't understand the issue yet
what are you trying to do?
Change rendering mode of an object via script
i mean what it eh big picture thing you are tryihng to do
Tardis
fade a 3d object in and out?
Yes
and what do you obsreve that goes wrong?
But it must return to opaque
Rendering queue is not right
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
It's completely invisible when running the code
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
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
what materials are you using?
Standard materials with smoothness off, specular highlights off and it's blue.
okay
And I'm doing it to multiple textures
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
I'm not mad at you at all I'm grateful that your trying to help
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?
Yeah
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?
No, when it's in opaque it looks normal.
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
I'm not at my PC right now. but I think just swapping between textures would work.
Materials*
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
There's nothing sepcial in the materials so I can just delete and restart them
And use alternating materials
I made a 2d grid array how do i remove the small ones?
Walk each pixel, if you find a white one, start a red flood fill and count the pixels it fills, if the flood fill count is < nSmall, do another flood fill from the end pixel, this time black, continue until done
Make sense, thank you.
Any way to limit an ICanvasRaycastFilter to just operate on the Graphic it's on, not children?
Looks like Image.alphaThreshold also affects it's children, doesn't seem right
Use GetComponent<>()
So it will get the component only in the parent
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
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?
To see it better. The question mark the question mark pops up above them.
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\
You should not target .net 5 with Unity
What should I target?
Match with what you have as API compatibility level in project settings
I have .NET Standard 2.1 and .NET Framework
So which one did you set
It was set to .NET Standard 2.1... Pretty sure .NET Framework is more up-to-date?
No standard is more up to date
So your library should target .netstandard2.1
This isnt the same script
Yeah that’s not PauseManager
this looks nice, did you draw it?
you are showing us a #archived-code-advanced game with #💻┃code-beginner programming skills
can you share a snippet of what you already have?
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?
are you familiar with distance fields
No but they look very similar to what I want ha
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
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?
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,
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
i think that deep rock galactic does somethign similar to this but 3d
That looks complicated asf lmaoo
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
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
yeah
worry about chunking later, get this system working on one chunk
don't preoptimize, you're working on a tricky problem
Yeah cheers
Think like Terraria, except everything I can put on the GPU is going to be on the GPU
i expect every pixel to be a voxel
if you're working on computer shaders already, you can definitely do what your'e doing with 3d voxels too
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 :)
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
That sounds sick
Lol
can someone help me with mathlerp
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
hi
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
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
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
where would you use the lerp?
on both if statements?
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
why do you want to use lerp here?? the code ytou have looks fine
oh you wantlike a smooth change?
yeah
no
ok can I DM you
yeah
You could also use DoTween
So you can just make a one-liner that will smoothly transition over time
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 😁
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?
I used to deal with a similiar issue... This might help:
https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html
hmm, when I'm calling ps.Simulate() , I was actually very worried about these probs, so only modified physics stuff in physic events, and transform stuff in , well, other events. so the sync function wouldn't really help me.
- but I totally didn't know it even existed! thanks. seems pretty useful
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()
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}
Hi
How can I debug ILPostProcessor inherited class (codegen after compilation)?
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 😛
I'm trying to burst some code via jobs and is unable to use System.Guid.ToString() in debug messages... any ideas?
I think string itself is a managed reference type and can't be used in jobs right?
yeah so it seems like I need an alternative way to see the bytes in the Guid to print it out, mmm
Can you just run the code without burst/jobs to debug?
I think that's usually how I did it
yeah but then it's hard to debug parallel problems 😦
It's always hard to debug parallel problems 😉
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
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
@undone coral @sly grove just a little update on the issue I had: gave up on checking collisions on my own when I found out about ForceMode.VelocityChange. Managed to make it quick, responsive and still collides properly 👍
ah - yeah working within the system is good
that looks nice
how is it controlled? joysticks?
atm I'm using the keyboard keys, but I lerp the rotation of the wheels
how do you feel about making it work with touch?
or a single mouse
also, did you make the vehicle model?
nope, I got it on from some asset I was testing; ended up not using the code but kept the model so I can test it w/ it
It should work, I use a simple -1 to 1 range and I should be able to replicate what I had in other engine
And in my tests there, it worked nicely with touch controls
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
oh that I haven't tried, would have to take a look at the games that do it
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.
Does Unity not include System.Security automatically?
Apparently not.
do you have a backbone / razer kishi for your phone?
What version of the .net framework does unity use?
it uses netstandard 2.1 and supports many net framework 4.7.x apis
however its implementation of netstandard 2.1 is incomplete
what is your goal?
I have a library using ECDiffieHellmanCng, which is a member of System.Security.Cryptography. I'm finding the versions are inconstant.
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]"
yes
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?
I'm just trying to setup encryption for my game client and game server.
or why is this cropping up? like what library are you trying to use
okay
you're trying to encrypt a TCP connection?
Yes, and it works fine outside of unity, which is where my master server resides.
My class is this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
okay, lemme ask you this first. do you think there is a standard way to encrypt a TCP connection?
I am not trying to encrypt the connection, but rather certain data going across the connection.
hmm
what is the idea?
for anticheat?
what is the threat you are trying to prevent
It handles authentication for players, authentication for game servers, server spawners and also token authentication.
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
I see
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
for this stuff you probably want to use http...
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
I see
i mean if you are trying to do this yourself
if you use a vendor it's way easier
like photon or whatever
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.
I'm wanting to start a multiplayer project but with the new Unity Networking system coming out I'm struggling to decide which solution to go with.
I'd...
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
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.
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