#archived-code-advanced
1 messages ยท Page 193 of 1
well, for starters, you won't
and two, tough cookie
you're making a unity game
maybe try it with GPU instancing
checked
but go itself not so good
bc many blocks will have own behaviour
you don't have a working game yet
if you do things my way, you'll have a working game much sooner
this mesh generation thing is a huge distraction
ye it will be much easier to made jsut GO
you can always try to optimize it later
but for what price?
Trying to replicate software like Stormworks is gonna require a ton of technical ability
actually kinda like space engineers also
so what i need to learn?
The basic principle isn't too hard to implement, but when looking at performance, there are probably a lot of processes under the hood to optimize performance
ye
can you give advice? i wanna MP game with in game coding + creating of smth. I also was thinking about "like screeps but with c# and with spaceships creations where you can build your own ship (istrolid as reference)".
will it be intresting game at least?
By all mean you should try, but if you're offering tools to create 3D meshes, or in game ways to code in C#, you will yourself need to be very familiar with how these work
I'd say, just make it work for starters and go on from there
bc its easy imagine this concept in 3d world where player has own ship. own factories etc. but 2d simplify it much
i have exp with Mirror
you can also try Mesh.Optimize and see how it perrforms
thanks
well gpu instancing is a very performant shortcut
for many interesting models you could combine, it's much faster than static
you can use poseidon CSG or another csg asset with runtime generation for a lot of other geometry creation tasks
you will need to do a lot more research @copper nexus , jumping into mesh generation is generally a Bad Move
i wanna MP game with in game coding + creating of smth. I also was thinking about "like screeps but with c# and with spaceships creations where you can build your own ship (istrolid as reference)".
making this 2D instead of 3D is still complicated.. if you're asking these questions here chances are it won't happen to be clear.
Start smaller, like way smaller unless you've released a game already this is pure fantasy imo.
is the c++ standard library xcode uses set during the unity build time?
im really struggling with getting a native plugin working since it has c++17 features
and xcode is not using c++14 or c++17 features
features that it should be able to use, but just doesnt
Hi!
I'm having a hard time profiling my application on the HoloLens with Unity. I know when a certain section of my application hits, it tanks performance, but I'm not entirely sure why, and am having a hard time finding the script that is tanking performance.
what is the plugin trying to do?
not in il2cpp
check the profiler
but that's academic
you're asking the wrong question
you will have trouble linking a complex library linked against libstdc++ (a GNU library from gcc) versus libc++ (the llvm one)
its a chess engine, stockfish 15. I need a chess engine in a mobile game im making for a class
Right but I don't know what to make of this
are you confident you are having a libc++ versus libstdc++ issue?
what is the difference?
stockfish isn't open source right? it's distributed via binaries?
its open source
hmm
c++14 or c++17 features
this can be enabled with a flag
have you tried googling it?
I have, though it does get rather confusing since there seems to be multiple methods and not really a guide
how are you adding stockfish to your game?
im using it as a native plugin
Im unsure if it will work, but it seems to be the most common response ive seen to how to add a chess engine to unity
use stockfish and add it in as a native plugin
hmm
well i think this is a worthy thing to learn but (1) it's really challenging and (2) stockfish is idiosyncratic in a lot of very not useful ways
that will not translate to other modern programs
dumping the stockfish source into your xcode project isn't going to work
somebody created a libstockfish library using cmake
but it wasn't merged
this is essential because stockfish by itself is a binary, and its build process in a Makefile is challenging to translate
you would need to work with this fork
which would at least get you started with producing a Stockfish.framework / stockfish.bundle you can work with and wrap
i.e. stockfish as a library
if your goal is to get a chess engine going
i would not do this
what would you do for a chess engine?
the simplest thing would be to use a weaker one that is just written in c#
and be done with it
if you really want to use stockfish in
an afternoon
I think ill go with a c# engine
you would write a rest API around its linux binary
for example what this is https://github.com/andrewmacheret/chess-server-lambda
ooh that could work too
ah
you will basically never in your life need to wrap a cli program that doesn't have a library
in a REST API
unless you like, want to work for Palantir working for the government
Can I in a subclass "hijack" the "Update" function, run 2 lines of code, and then run the rest of the superclass' Update function?
@heady bane this one actually seems to be
the most realistic to understand in a day
but i'm concerned there's no setup.py
Thank you
it's tough. you have to know a lot about programming ๐
i agree it's cool to have a really good chess AI
i would probably try to finish this with a C# chess AI library
i mean that you have to know
a lot about
worthless garbage
Yea, i think ill go with a c# chess engine. I've spent a lot of time on stockfish already and I thought I was getting closer than I was to the solution, but yea this part is taking too much time
like deploying an AWS lambda isn't that hard
but it's worthless knowledge
if you are at a stage where you really have a UNITY_..._EXPORT c extern declared
and being called
you could use the cmake based build i linked
and get a libstockfish /Stockfish.framework you can actually use
with a header
I think you could have the superclass call an abstract function that the subclass has an override function for
it's not usless but it's arcane
yea
it's really the stockfish's people's fault for being stubborn about not making it a library
it seems to be pushing into a lot of weird areas to even get it tostart doing something
the python thing is probably closest
to running on your laptop with 1 click
then you would use UnityWebRequest and it would be Good
you'd have to deploy the server somewhere though
Ah ok, I tried doing this but seems there's some funky business
the deploying servers part is what has made me a bit hesitant about that option. Getting a server set up for a small uni project isn't really worth the fuss I think.
im kind of unsure what you're doing in this script. I may have misread your question
oh okay
I meant an abstract and a override function
okay sorry, i made have messed this up a bit, sorry.
I think base.Update() should work
Did some troubleshooting, did indeed work. Just need to rework a seperate part of the code in order to get it to work. Thanks for the feedback! ๐ โค๏ธ
dont call base.Update
make the base update also private

which will unity lead to invoke both
in the right order
which will be base => child
Hmm okay let me check it out
Hi! I've got a public field Component in a parent class, in a child class I want to decorate that field with an [Attribute] which limits access somewhat.
Is there a clever way to do that, or would I need to write a custom Editor for the childclass ๐ฌ ?
I would be looking something akin to the virtual keyword for functions.
make parent property abstract
the generic ComponentReference<> class should be able to place any component in the field, but the inherited class should only be able to place components which are restricted by an attribute into the field
in this case I want it only to be able to have components be accessable which are part of the gameObjects.GetComponentsInChildren
[Dropdown()] supports custom functions
the alternative would be to implement a custom Drawer for ColorReference and copy over code from the DropdownAttribute, but I would rather not if avoidable - or in general if there's a better way to achieve this behaviour.
on itself
public abstract Component child {get;set;} ?
with that the child needs to implement it
where you can also set annotations
for it
hmm, can I add Drawers to properties though?
Afaik you'd have to have a serializable field, for the inspector to catch it
ofc you can
in ressources i posted a readonly drawer
which can draw properties
you just have to add [field: ... ]
works wonderful
my thing is supposed to make it grey...
yes! exploring [field:] more is definitely super valuable! Thank you.
I'm iterating through it atm, but ran into the issue that the inheritance tree might be a little to deep, as it currently goes ComponentReference<> -> PropertyReference<> -> ColorReference
but I think I'll flatten the inherited hierarchy
the problem being that the abstract property from ComponentReference has to be implemented in PropertyReference leaving me once again with two serialized fields ๐ฌ
maybe try SerializeReference instead
interesting, where would I apply the attribute? In PropertyReference[field:] or ColorReference[field:] ?
i dont get it ... why would it be 2 ??
i think PropertyReference
both members implement the property with fields
tried all three permutation, sadly SerializeReference couldn't magic this ^^
yeah sorry. was just a guess that it might work
abstract base class:
child class 1st degree:
child class 2nd degree:
don't mind the SerializeReference attribute - it's switched over to Field again
ah no there^^ SerializeReference doesn't work
in other words : why does fieldreference override the component and implement it , if it cant fully tell what its supposed to do ?
make it in the second class also abstract
until your class can fully implement it
yeah, that's the thing FieldReference or rather PropertyReference needs also be able to function, so instead of having ColorReference inherit from PropertyReference, it should directly inherit from ComponentReference -> that's what I meant by having to flatten the hierarchy
ColorReference is just a specialized (non generic) form of PropertyReference, but both need to be able to be used.
obviously, that's what I'm doing here ๐
that's why I'm taking this approach ^^

but thank you very much for the aid! โค๏ธ
atleast you know now how to serialize a field
I knew before though ^^
meant with the field: that you can put your own drawer in it
yeah! That's a+ knowledge right there! Thank you very much for it.
so. i get this with CombineMesh. then i .Optimize() it.
but still has not needed triangles inside. How i can fix that?
also whould be awesome to apply greedy mesh there
I think you'll have to implement a function to remove interior faces
optimize mesh only get's rid of close together vertices afaik
also i want to combine em
this is optimization what im talking about
sure, you'll probably need to find a library with functions for it
there's no default for that in unity afaik
ok. what about edges inside ?
that's not what unity is for to do anyway
public void Start()
{
var combineInstance = new List<CombineInstance>();
for (int x = 0; x < X; x++)
{
for (int y = 0; y < Y; y++)
{
for (int z = 0; z < Z; z++)
{
combineInstance.Add(new CombineInstance
{
mesh = Voxel.Mesh,
transform = Matrix4x4.TRS(new Vector3(x, y, z), Quaternion.identity, Vector3.one)
});
}
}
}
var mesh = new Mesh();
mesh.CombineMeshes(combineInstance.ToArray());
mesh.RecalculateNormals();
mesh.Optimize();
Debug.Log(mesh.vertexCount);
Debug.Log(mesh.triangles.Length);
MeshFilter.mesh = mesh;
}
this looks like something ur looking for
that should really be done by the artist in a 3d software^^
not neccessarily - LODs etc shouldn't always have to go through manual labor
you cant optimize grid that was genereated at runtime
only manual optimization
yeah
yeah of course not. but looking at the page preview image, that shouldn't be done at runtime
even if not during runtime, unity doesn't have a default library for the task.
This really needs either a full on asset, like the one I linked above, or a seperate library.
becaue that's NOT a thing unity needs to do nor should do
thats still dosent solve edges that inside cube
you'll need to write a script which collapses the interior edges and faces then
it's not a default task - you'll have to either do it yourself, or find an asset/library which already can do it.
blender has a function for that to remove useless vertices
and optimize them
Blender also has an option to Select (and consequently collapse) all interior faces afaik
I wish haha
your meshes are excluded ... but every others can be optimized ๐
working with landscape photogrammetry in my job - and even though blender is part of the pipeline - it's not the best at optimization ๐ฌ
well i'd say that involves huge meshes and that's def gonna be a difficult algorithm to write
yes, that's why we're working A) with a company which entirely specializes on Realtime optimization for Photogrammetry assets (Realities io) and they B) have an entire pipeline built around it. ^^
sometimes a mediocre optimized mesh is worth more than a perfect optimized mesh
but i would say that's not a usual use case for blender
at least it's more niche than others
ofcourse, ofcourse - not trying to take anything away from blender - working with it for years and love it
just - it doesn't optimize everything - I would even say, optimization isn't it's strong suit, compared to everything else it brings to the table
just want to put my mediocre blender knowledge into it...
why do you not bake it ?
? what's baking gonna do
you make a low poly and put the high poly around it like a skin
which will result in reducing drastically the mesh vertices and edges
i don't think that's viable for fotogrammetry
is that intended for @copper nexus ?
I think he's generating a mesh at runtime - probably something akin to a custom voxel solution
@buoyant vine refactored my classes to have a flattened hierarchy:
now there's an abstract BasePropertyReference, a Generic PropertyReference and a ColorReference, which inherits on the same depth
humm
no good?
haha, true
to stay consistent with in the project scope ๐ฌ
=> nfo == null ? default : (T) GetValue(component);
to make it an expression body
im very picky there XD
but its not necessary
if you dont want it
its just "extra" .. i like it more
but do you mean => _nfo == null ? Or is nfo => nfo == null ? somehow valid?
public T GetValue => nfo == null ? default : (T) GetValue(component); make it expression body get only
which would be
public T Value => nfo == null ? default : (T) GetValue(component);
then
hmm, I think I'd still prefer to be able to set Value from within the class
so I dont think I'll remove the setter from value all together
you can also write the setter
like you would for a backing property
this is just the shortest way ๐
of your last method
fair, I'll take it in to consideration and will iterate a bit more ๐
im just making suggestion
you can do whatever you want to do in your code
if you want to iterate with forloop to 100000 before returning value go ahead ๐
lol, yeah I just dont want to copy suggestions into the code, without understanding the reasoning behind it myself - so I'll take some time. ๐
why if a set a 256x256 texture into a plane of 4096x4096 the texture stretches? Id like it to appear as 256x256 as a part of the plane
should i use 16 diffferent 256x256 planes to avoid this?
because a "texture" is a bucket of color, unity paints the entire thing with the bucket per default
what should i change to avoid this?
ye its kinda voxel game
use 16 differert meshes?
idk sorry
oki thanks anyway!
is this on a 3D mesh or 2D image?
2d
change the import settings of the texture to repeat
the texture i ccreate it in runntime, ill see if theres an option
alright, I think then you want to adjust the uvs of the plane to fit the scaling you're intending
you could also preferably alter the Textures Tiling in the material of the plane
ok the tiling i kow where it is
๐
UVs are to meshes (even 2D) what tiling is to textures... kinda
oh but i cannot modify that from unity can i?
you can, but I think you'd rather change the tiling
np
@buoyant vine this is where I am now. Also hopefully made the naming a bit more clear by differentiating more directly between the serialized value in the PropertyReference and the targetSourceValue
if you only inherit it for giving it the serialize field then you could serialize it in the first place ?
as i think your entire thing doesnt make sense if you dont serialize the property you want to set
to find the children
@mild yew
well the purpose was to have ColorReference put an extra attribute on the component property
PropertyReference<T> should not have the attribute but ColorReference should
Hi,
So I am looking out for how can I implement a system in a modular way where I've 2 scenes which gets switched from Scene 1 to Scene 2 and I have UI animations, one for the Scene 1 and rest three for Scene 2, where I've created 4 .anim files and want to run it through script according to requirement but I want help in how should go for it i.e. what is the most modular way to manage the all UI animations through a single script for both the scenes and by using a single animator and would just replace the .anim at runtime.
Please help me out with this. Would be really thankful.
Thanks in advance
Is your UI DontDestroyOnLoad or something?
No it isn't a Singleton class. See, I have 4 animations, one for 1st scene and remaining for 2nd scene to play in. But I want some way except singleton to play these animation through a single script for both the scenes.
DDOL does not mean it is a singleton
Yeah basically UI is not kept as DDOL
Is there any other time we keep it as DDOL?
plenty of ways, but your terminology is vague
you need to be precise about what exactly you want, a script is just a text file with some code in it, you can use one text file, to contain the definition of one class that gets instatiated two times, which means technically, you have made it play with one "script"
what you probably want is to run it through one object/instance, which means it can't be a monobehaviour or it has to be DDOL
I think Kartik needs to split up his problem, Unitys timeline is very extendable and probably has what he's looking for in terms of sequencing animations, secondly he needs to look up methods to do cross-scene references
there is no reason to avoid DDOL if the purpose of the object is to persist across scene load or to transfer state
Yeah, now I get your point.
think of DDOL as a separate background scene that just never unloads... because thats what it actually is
As a seperate scene or as a seperate GameObject which exists for all the scenes whether at the time of switching or pausing etc.?
Ahhh okay. So DDOL is nothing but a scene of unloadable objects, am I right?
the default behaviour is to have only 1 scene, and on each load everything loaded gets destroyed, but since that is very limiting, you can have scenes load additively (without destroying what is already there) or use DDOL
Which persists throughout the application is running, right?
Yes, this Ik.
Thanks for this insight @compact ingot, I think I might be able to solve the problem now
great
Thanks once again
Anybody knows how to create a RenderTexture just capturing an area of the screen? I've been looking around the forums and docs and seems is not possible by passing a rect to the camera
is there any other way?
yeah i've tried that, it simply ignores it
more people in foums with the same problem
how to solve overflow of objects in voxel world?
i.e. rn its fine to get 101010 chunk. but how does minecraft solves that? bc it has 1616256. ik that it dosent renders all block with their verts/triangles. but it can be in minecraft too?
i've tried the SetTargetBufffers but it didnt work,
not sure why that would be - I think I used it about a year ago and it seemed to work as intended
ill try again then, i did it just beforre i've set the cam to Render()
maybe doing it earlier ....
do you think you have the script around?
if not its ok
you could try using Graphics.Blit directly too, afaik this is what targetTexture effectively does anyway
wouldnt that overhead the operration?
what im trying is to use less ram with it
anyway, noted, ill give it a trry too
thanks a lot
had a look and I think I replaced/removed it at some point as I was trying to achieve something a bit different (ended up as Graphics.Blit and ignoring the camera entirely)
not sure on what the most performant way of doing it would be
๐ thanks a lot
i am generating a cube marched terrain, and want to bend it so it becomes some sort of ball. any ideas?
easiest: use a shader
you can do it with shadergraph
need reference
Exponentially offset the vertex position based on some value. E.g. distance to camera
nonono it is not for that kind of thing
i am basically generating low poly trees with that, so i want to bend it to make the leafs of the tree
That sounds like overly complex. Ever tried bending a square piece of paper into a sphere? The results won't be good
Weird stretching and artifacts guaranteed
right. but i didnt find any good tutors on cube marging and ended up with that..
If you want to use a marching cubes algorithm, you want to essentially generate a 3d-grid in the shape of a sphere and then add complexity using 3d-noise
Something like fillamount
You essentially go through the grid and fill if its within a distance of your centerpoint
void PopulateTerrainMap()
{
// The data points for terrain are stored at the corners of our "cubes", so the terrainMap needs to be 1 larger
// than the width/height of our mesh.
for (int x = 0; x < width + 1; x++)
{
for (int z = 0; z < width + 1; z++)
{
for (int y = 0; y < height + 1; y++)
{
// Get a terrain height using regular old Perlin noise.
float thisHeight = (float)height * Mathf.PerlinNoise((float)x / density * 1.5f + seed + 0.001f, (float)z / density * 1.5f + seed + 0.001f);
float point = 0;
// We're only interested when point is within 0.5f of terrain surface. More than 0.5f less and it is just considered
// solid terrain, more than 0.5f above and it is just air. Within that range, however, we want the exact value.
if (y <= thisHeight - 0.5f)
point = 0f;
else if (y > thisHeight + 0.5f)
point = 1f;
else if (y > thisHeight)
point = (float)y - thisHeight;
else
point = thisHeight - (float)y;
// Set the value of this point in the terrainMap.
terrainMap[x, y, z] = point;
}
}
}
}
this is generating the terrainmap atm
That being said I think it might be smarter to make different individual meshes, like leaves and trunks, in modeling program and then procedurally combing them into good trees. It gives you more control and honestly better looking trees
i really want to stick to the generation, not manual modelling..
I mean if you're doing it for learning that's fair, otherwise I would advice against it
But try to generate a sphere first with marching cubes. After you got that down do a second smaller sphere (in the Same mesh) ... Then add 3d pelin noise
Try to pay attention to how much are you using processing time, these things can get rough
i think ima scrap
Sorry to bother you again but after reading the docs of Graphic.Blitโฆ. Isnt the purpose of this function just the opposite of what we were talking?
Blit takes a texture as source and a renderTexture as destiny
But what i want to do is just the opposite
Am I missing something?
the source texture can be taken from what the camera renders, in OnRenderImage() say
https://docs.unity3d.com/ScriptReference/ScreenCapture.CaptureScreenshotIntoRenderTexture.html looking for this maybe?
I'm thinking of using the unity profiler API in unit tests, has anyone here this in the past? Wondering if there's any gotchas with it when using it on multiple unity-tests run sequentially.
My use case right now would be looking for memory leaks in unity.
When creating a program that relies on serialization/deserialization, how do you usually handle updates and older formats?
You encode a version into it
Okay, and then you'd add "legacy" method to handle deserializing them and converting them to the current version?
Yeah there's a few options for those
Hello Folks!
Is it possible to use "Access token" to make API call from outside of the website?
For example API calls in Postman with scraped access token of a website?
Or is there any security bound between the frontend and backend of the website?
I'll sign in with my national credentials to a state website and will scrap the access token and will make an web application working into the backend. My goal is this.
The token can expire
and it probably will if the site requires strong authentication
They use OAuth and there is a refresh token too.
So when the access token returns 400, I'll make a new request with refresh token.
@devout hare
hey, was wondering if it's possible to infer what version of the IL2CPP library (compiler?) is being used by which unity version
how stormworks made? how space engineers made?
i mean editing of structures
watermelon
so im watching a turtorial on A* pathfinding , but because im dumb i really don't get why it is Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.up * gridWorldSize.y / 2; and Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius); , anyone mind explaining to me how it works
thats whats called trash code
prob none has the mood to get into that
its the complete opposite on how to write code
so basically for the first one
assume transform.position is the center
if you subtract half of gridWorldSize.x on the x and half of gridWorldSize.y on the y
then you're gonna be at the bottom left of the thing
and well the second one just composes a point inside that area that's defined by gridWorldSize with (x * nodeDiameter + nodeRadius) as the x and (y * nodeDiameter + nodeRadius) as the y
oh thanks a lot that basically explains everything
I want to get all Types which are derived from an interface
so I googled things and tried them but failed
all codes are working but the result's list's count is zero
so.. how can I get all Types ( not classes nor instances) which derived from certain interface?
Outside Unity you'd iterate through all loaded types and check which ones are derived from the interface by using https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=net-6.0#system-type-isassignablefrom(system-type)
Or another method similar to that
@maiden turtle Thanks a lot!!
hello, what could be causing that web request calls dont work on the editor play mode, only on build
Hello guys
How to set Main camera to specific cinemachine virtual camera/cinemachine (irrespective of priority) through script ?
How would you guys suggest me to stop the game until the rewarded Ad is finished?
you need to deactivate the old one and activate the new one.
Time.timeScale = 0
This is the simplest way, but it will affect everything
no both needs to be active
in multiplayer game one player sees one camera that follows one cinemachine , and other player sees second camera that follows second cinemachine
How do i make the legs not let the entire body move, I want the feet to lock the body too
(Im an moving the prefab itself)
What? Could you try a different explanation?
So I want the feet to stay on the ground, that works, but I want the feet not to move with the body, they do
The code simply Does a raycast from the Gray circles and sets the green circles on the hit point, the green circles are the feet
You could just stop updating the target position right? And only update it when the player moves a distance
Yes but the Empty objects will still move if I move the character object
You could or child it in a way that they don't move with the game object moving or calculated from local to world but that depends on what style you prefer. There are probably other options but that is what I can come up with now
Or have the target be a separate variable that you set it to
Np
you prob will run into camera bumping when you go up the stairs ?
Yeah i will, but thats not the player luckily
aight
All my players are beans, cant break the rule
why do you not make just make it "cheap" if its only for the stairs
Nah it not for stairs, its for nothing just testing IK lol
oh
yeah
then nvm good luck with your bumping ๐
Im just following this tutorial and like the spider body stays in place mine doesnt
I tried to explain procedural animation in 10 steps.
Check out my twitter: https://twitter.com/CodeerDev
wow that looks goody
gotta build that into my game
i dont need it probably... but i love random things that i dont need at all
Same
fits perfectly to my ingame terminal that i dont need
lol
SAME
OH you know what i just realized
I should be moving the Torso, then the feet stay
Hey I'm trying to get pathfinding working with a procedually generated map, and i can't for the life of me figure it out and everything i've looked up hasn't helped either. I'm trying to use the heightmap data to tell a character where to go but it's not working. Anything helps! (Unity 2D)
How youd like the heightmap data to be taken into account exactly?
so it's perlin noise (so 0 to 1) and i'm trying to form either a navmesh or something of the sort based on that
But what is the perlin noise doing on the navigation process? Is it something like 0 -> cant walk 1 -> can walk 0.5 -> can walk but try to avoid when possible?
so from 0 -> 0.4 can't walk and from 0.42 -> 0.7 they can
Do you want the value between 0.4 and 0.7 affect the path or is the area always either walkable or not walkable?
for that area yes it should be walkable\
But do you want value of 0.41 work differently than 0.69? So should some areas be easier to walk than others?
no, all alreays from 0.4 to 0.7 should all walk the same
Are you looking for ready assets to do the path finding or do you want to do all yourself?
im looking for either
Pretty much no matter which pathfinding method you use you have to learn how A* works. Grid based A* could be easier to implement but navmesh based A* could be more performant
Hi there
does anyone know the mathematical operations behind a "directional warp"?
I have a noise texture / sine wave texture (2d float array with 0-1 values) and want to distort it this way
alrighty thank you!
Unitys navmesh system relies on A* too
You could just use the heightmap data to create the grid of walkable and unwalkable areas
What is a good way to set up python scripts on a server fo unity to communicate to?
I know of the web request part in unity, but im stuck thinking of what to do on the server side
( why would you use python on server side ? )
cause I cant see how to get python on iOS
in unity
especially since the python code has a lot of machien learning code in it
which barracuda can handle the models
but I need a solution to it and fast
@heady bane usually all machine learning libraries have some sort of native compiler to them so you can generate binaries that can be integrated into Unity
Thats how I did it with TensorFlow; have my models defined in python, and then generate the corresponding paltform binary
i dont really want to deal with more of those after having to mess around with stockfish for days with no progress
I know i should be able to export the model as an onnx file
but its the other processing I need to
and that code requires 10 different imports
I just need something that can get that code to run on unity in ios
and I know a server can do that
I dont have time to mess around with trying to get 10 different things working on ios
like opencv
sorry, just getting stressed.
I thought i knew how to get this all working.
but it has backfired badly
Does anyone perchance know how to switch between XR plugins programmatically?
are you trying to use the stockfish api built around python?
have you succeeded running that code on your laptop
then getting the ios client to connect to that?
no i stopped using the stockfish api
okay
it wasn't possible to get it running
are you trying to get an app to interpret an actual chess board?
via the camera?
yes
the solution is similar, you upload the photo to a separate server which reads the image, then sends back the results
so what should I use server side?
well
are you uploading a photo of a natural physical chess board
or a photo taken through an iphone of a 2d graphics chessboard as rendered by popular chess websites
server side you use what you're most familiar with
well, i have the code for the model, and im using a real image to upload
the problem is that while ive done quite a bit of unity side server stuff, i havent really made a custom server to run python scripts before
i see
this model works for demonstration purposes?
if the model was authored, trained and tested in python
you can use flask to quickly turn it into an API
flask?
it's a python package that lets you annotate a python method as an http route
if you need this to Just Work for python, you can use a tutorial like this - https://www.serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/
@heady bane when is your deadline?
this way we can limit how much extra stuff you have to do
it sounds like you are working with a few other people who made these individual pieces and you're responsible for integrating it all
sounds like "software studio"
today,and its a uni project where one of the members has gone silent for months
okay you should
cancel all not working features and work only on the polish of the unity game
like adding animations and effects
this package implements stockfish via a unity plugin - https://assetstore.unity.com/packages/tools/ai/strongest-chess-ai-stockfish-203224
you can ask for a copy of the osurce since stockfish is gplv3
so he'll have to give it to you for free
i don't think it's worth trying to read a real chess board with the camera @heady bane because probably the code that you received from a teammate to do that doesn't work
it's a very challenging problem and unrealistic that people giving you stuff the day of the deadline achieved it
if the class values these sorts of features piled on
i think the server approach is the way to go
gpl != cost free software
has nothign to do with it
Well really what would be most helpful
Itโs just tough I donโt wanna send you down a journey for something g that will never be done
Hi. So i have this parent class where it have a delegates and event there. And this class have a property of ScriptableObject which have a public method to subscribe to the parent class' event. I use this method on the Start method of the parent class. Now i have a class that derived from that parent class and want to use invoke that event on Update. But for some reason, it threw this error
The event 'InventoryController.PlacedOut' can only appear on the left hand side of += or -= (except when used from within the type 'InventoryController') Assembly-CSharp
here's my base class code
https://pastebin.com/RLTUTyYj
and here's the class that derived it
https://pastebin.com/7ULRXYxU
why can't i invoke those events?
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.
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.
thank you for the help, and I understand yea. i should have asked earlier, but it just got a bit out of hand with just getting the chess engine part working
Hey so if I pack 4 uints into a single uint, is the max size of each of the packed uints 255?
Is there a way then for me to store 1 large and 1 small uint in one uint? What would be the max size of that?
I think you might be a little confused on the whole concept of events.
PlaceOut and PlaceIn are events which allows other class to subscribe to it by using += or unsubscribe using -= in which case the subscribed class will call the subscribed function (on the right hand side of the +=) when the base class invokes the event.
The error you're encountering is precisely to prevent programmers from accidentally overwriting the subscriber or triggering the event, therefore only the base class is allowed to call the PlaceOut() event.
If you were trying to invoke the delegate and returning the ItemData, you should be invoking PlaceOutHandler instead of PlaceOut
ohh, i see
but what happend if i have two classes derived from that parent class? if i invoke PlaceOutHandler on class A, will it be invoked on class B too?
No it would not. PlaceOutHandler is just a delegate on another function that takes an index and return an ItemData. You can use PlaceOutHandler just like any normal functions.
On the other hand, calling PlaceOut() in InventoryController would invoke all subscribed functions on other classes (which are typically not inherited from your event caller, but can be)
it's all going to work out ๐
you could in principle use varints
there are a lot of tricks @honest hull
it depends on what the values are. for example if they're all similar to each other you can store an average and three offsets
hey whats the equivilant of 0b11111 on GPU? trying to a bitwise and
I'm trying to add sliding down ramps for my CharacterController, and the problem is that when I'm on a ramp, gravity is constantly building up, so when I fall off the edge of it, my player snaps down immediately because the gravity becomes some ridiculous number like -20
I feel like this is a common problem because all gravity is handled the same way with CharacterControllers
hello friends, i have a code with different result at CPU and GPU (Compute shader)
can you please help me to solve this?
I want create normal texture for my sphere planet from noises that i have in _1dUcData
this code working by unity jobs but the same code dose not work on unity compute shaders
uint y = py + UcBorder;
float xPos =(_1dUcData[y * ucHeight + max(0, x - UcBorder)] -
_1dUcData[y * ucHeight + min(x + UcBorder, width + UcBorder)]) / 2;
float yPos =(_1dUcData[max(0, y - UcBorder) * ucHeight + x] -
_1dUcData[min(y + UcBorder, height + UcBorder) * ucHeight + x]) / 2;
float3 normalX = float3(xPos * intensity, 0, 1);
float3 normalY = float3(0, yPos * intensity, 1);
// Get normal vector
float3 normalVector = normalize(normalX + normalY);
// Get color vector
float3 colorVector = float3(0,0,0);
colorVector.x = (normalVector.x + 1) / 2;
colorVector.y = (normalVector.y + 1) / 2;
colorVector.z = (normalVector.z + 1) / 2;
// Start at (x + _ucBorder, y + _ucBorder) so that resulting normal map aligns with cropped data
if (x >= UcBorder && y >= UcBorder && x < width + UcBorder &&
y < height + UcBorder)
result[id.x] = float4(colorVector.x, colorVector.y, colorVector.z,255);```
i know the problem is from getting _1dUcData data.
the problem result is empty normal texture.
when the code do - between two part of _1dUcData[] its going to zero
AmeetZ DEV โ Today at 1:21 PM
Hey Guys, I need some help regarding Mathf.PingPong()
I am trying to make a Bobbing effect using that function,
So... here is what I did
public Transform graphicTransform;
private void Update()
{
//Ambience Effects
float offset = Mathf.PingPong(Time.time, 1f);
graphicTransform.position = new Vector2(graphicTransform.position.x, offset);
}
It works, but not the way I want it to
The y position of the Parent GameObject is 5 but the graphic goes to bob at the world center that is y = 0... I really don't understand why it is subtracting from the original y position...
Please Help!
position = world position
over there you are overwriting the Y coordinate
so if it was 10 before, you are now setting it to whatever offset is, overwriting the value
you wanna use localposition
im not sure if I can get serverless to work. its being weird with the aws authentications
Hi ! Anyone knows how i could create a way for UnityEvents (here : https://docs.unity3d.com/Manual/UnityEvents.html ) to work with enum types?
public UnityEvent<MyEnum> MyEvent;
oh wait...
You won't be able to set the enum in inspector, if that's what you mean.
But you can still trigger events from code
yeah, i know
I was thinking about overriding the UnityEvents Class in a new one, and only adding a way to display enums
What exactly are you trying to do?
well basically, i've got my huge dialog system, and i've got an enum containing all characters. My tool is destined to be used by non devs, so i can't just have an int representing characters, it wouldn't be easy to use at all, you'd have to remember each characters' ID, not easy at all. If it's something that has to be done, well i'll do that, but if i can avoid, it could be great
so that' why i thought about trying to implement a non primitive type
But as soon as i looked into the metadata of the classes, i knew this was a hard task, so idrk
I meant with events
Although first thought there: you should use a scriptableobejct for the characters
Instead of an enum
Maintaining an enum makes it impossible to add characters without editing code
But if you use an SO a designer can create a new character and set their name etc.
Anyway, this is how I usually fix the "can't send X data from unity event" problem:
public class EventDataExample : MonoBehaviour {
[SerializeField] MyEnum myEnum;
[SerializeField] UnityEvent<MyEnum> myEvent;
public void OnSendEvent() {
myEvent.Invoke(myEnum);
}
}
OnSendEvent would be triggered by a UnityEvent (for example UI.Button.onClick)
And I just put this component on the same object as the other event script (e.g. UI.Button)
i do
And the enum is updated automatically
If you have SOs then you don't need an enum
so i can just put the scriptable in parameter lol
You can pass SO instance
yeah lmao
thanks!
you wrote code gen for this?
haha
yeah lmao
File.Write and shi 
Ah well, it's a good skill to have
But yeah, totally unnecessary
SO just solves this by each instance essentially being an "enum value"
Might need a bit of creative coding in parts
well since i can put an enum value anywhere (not in events tho), i can have a tool that's easy to use, UX friendly, and you don't have to fetch scriptables everytime. Plus, i've got a "SearchableEnum" attribute which works perfectly well, so even tho i have a shid ton of characters, i can search em by name, and most importantly: people that don't know shid bout unity can too!
SOs are searchable too
And are UX friendly
In fact I'd say that's the main appeal
After a long reflexion, i think i might reconsider no using the enums on my next iteration 
I'll ask what the team thinks lol
Thanks a lot!
Also, i cannot get the parameter of a custom event, can i? Like getting the name "Camellia" for instance, from the EventsToTrigger variable?
oyur transitions on method will get exctly your camellia when invoked
Uh... you can
It's in the dropdown elsewhere
There are two sections...
I don't have enough context here, what is EventsToTrigger?
UnityEngine.Events.UnityEvent lol
Oh, the event itself
You mean if you do Invoke(MySo)?
It's an option in the dropdown
wait, context of why i wanna use that:
public override string ToString() {
string res = "";
res += "- Triggers some events :\n";
for (int i = 0; i < EventsToTrigger.GetPersistentEventCount(); i++) {
res += EventsToTrigger.GetPersistentMethodName(i);
}
return res;
}```
๐คท I have no idea. I have never used that.
i have the method name here, and i'd love to have the parameter too
I'm sure it's possible, but I don't know if there's a method for it
No
Instantiate
Invoke is a method on UnityEvent to call the event
There is also MonoBehaviour Invoke which is something else
Looking at the source, you can't get the arguments. Need to use reflection if you want
the god themselves
Never heard of that, i'll go check out the documentation, thanks!
You can also use SerializedObject since UnityEvents are serialized (that uses reflection internally)
But you shouldn't need to do this, since you can sinply see the arguments in the inspector
well one thing's for sure: no method has "Arguments" or "parameter" in its name
it's private, isn't it
Great lol
I can't just modify nor access this, can i?
Again, is this editor?
UnityEventTools has regsitering/deleting
Otherwise use SerializedObject to go through the members
i guess i'll use SOs when i can lol
thanks!
How to get a transform.up from a quaternion?
I get the quaternion from a Matrix4x4, so cannot use regular transform commands
If you have a matrix, you don't need to extract the quaternion to transform directions. You can do:
Vector3 up = matrix.TransformVector(Vector3.up)
Hey, I have a quick question about configurable joints
I have two instances of the same character, one of which is simply animated through an animator, and another which is a ragdoll. The ragdoll one has bones at the wrong places. His shoulder and clavicule bones, which do not have any rigidbodies or joints, are out of positions and way into the arm itself, while the animated character has all bones at the correct position. My hypothesis as to why, is that my configurable joints, used for the ragdoll, are messing with components that do not have rigidbodies attached. For reference, my hierarchy for the arm looks like this:
spine -> clavicule -> shoulder -> upper arm -> lower arm -> hand
Of these, only spine, upper arm and lower arm have rigidbodies and joints. The joints of the upper arm is attached to the joint of the spine.
My question is, is it possible that my upper arm joints is "pulling" my clavicule and shoulder bones closer to its position because it is attached to their parent ?
Hi, I've made a test shader. The idea is to highlight edges or something like that. I based it off of the default fog template.
However, Unity shows compilation errors: fragment input user(NORMAL0) was not found in vertex shader outputs
And same error with TEXCOORD0. What the heck does that mean?
Shader "Unlit/NewUnlitShader"
{
Properties
{
[NoScaleOffset] _MainTex ("Texture", 2D) = "white" {}
_BaseColor ("Base Color", Color) = (1.0, 1.0, 1.0, 1.0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
// Upgrade NOTE: excluded shader from DX11; has structs without semantics (struct v2f members normal,viewDir)
#pragma exclude_renderers d3d11
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f
{
float3 normal : TEXCOORD0;
float3 viewDir : TEXCOORD1;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _BaseColor;
v2f vert(appdata v)
{
v2f o;
o.viewDir = WorldSpaceViewDir(v.vertex);
o.vertex = UnityObjectToClipPos(v.vertex);
o.normal = UnityObjectToWorldNormal(v.normal);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
// sample the texture
fixed4 col = _BaseColor;
col.a *= dot(i.normal, i.viewDir);
return col;
}
ENDCG
}
}
}
sure hlsl is coding language but #archived-shaders is a thing
So I've been experimenting, I tried adding empty objects in my hierarchy to see if they get pulled too, and yes, the moment they get in between spine and upper arm, they get moved. Now the weird thing is, it continues to do this even when I remove during runtime the joints and rigidbodies
I'm quite lost here
Hi! i'm working with dotween, and with sequences. Somehow my sequence.Duration() is equal to 0 even though the delta between beginning and ending isn't 0?
The debugged float after begin and end is just Time.time.
Turn off Collapse
i'm making my code easier to explain lol i'm coming
Okay wait, my problem seems to be elsewhere:
sequenceGo.Play();
await Task.Delay(Mathf.CeilToInt(goingTime) * 1000);
Debug.Log(sequenceGo.Duration());
Debug.Log(sequenceCome.Duration());
sequenceCome.Play();```
here, i tried making one character go away and one taking it's place, and even though i have a task.Delay (and goingTime isn't != 0, i debuged.logged it and it evaluates to .75, the value that it's supposed to have. But here's the catch:
the beginning of the tweens of the character going away and the other taking its place, are at the same time. Even though they are clearly split by a Task.Delay().
I've asked this in general, but no one has idea
Need advice. I'm creating editor script rn, that modifies a lot of files at ones (scenes too). I'm using https://docs.unity3d.com/ScriptReference/AssetDatabase.StopAssetEditing.html and turned off auto refresh. But importing still continue happens. Any idea how to find what is causing importing?
And yes, first is called StartAssetEditing()
what is your objective?
what does the editor script do
why are the hierarchies of the ragdoll and character different?
Simply put, I use a script to create the ragdoll, and it creates a rather simple ragdoll, where the model has a much more complex rig. I can't make a script that creates a specific ragdoll to my model because the rig might change sometime during dev
did you try starting with an asset store asset?
it seems like something low ROI to roll yourself
and a lot of pitfalls
there's no such thing as a simple ragdoll
true
well, I tried a different direction to my whole problem, but I'll keep your advice in mind if I ever come back to it
thanks
What I've made is system where it is performant (this is local multiplayer with up to 5 people and I'm trying to make everything as performant as possible) and scalable to add muzzle flash VFX through scriptable objects where you can make a prefab of the VFX and plug in the prefabs particle system to the scriptable object. It will then take that particle system make a copy and then add the copy to a VFX object on the weapon where I can the cache it and call play whenever I see fit. Then I get the error "Setting the random seed while system is still playing is not supported. Please wait until the system has stopped and all particles have expired or call Stop with ParticleSystemStopBehavior.StopEmittingAndClear to completely stop the system." I know why, what, and how its happening but I have no idea how to fix it since the method that is handling it is dealing with generics. I'm sure you cant just tell it to not set this one random variable... here is the code that copies the values... https://paste.mod.gg/fjkwxemvodeq/0 Thank you with any help I can get!
A tool for sharing your source code with the world!
On a side note I really don't want to try object pooling because the system I already have is built for gameobjects... and I don't want a whole separate object pooling system to keep track of.
I have a big open world, that are divided by cells of scenes. I'm using gaia biome spawners to generate biomes onto them. Editor script loads scene, spawn GOs, terrain details and textures, saves and unloads
Hey Guys, I need some help regarding a small Floating/Bobbing Effect I am working on for my game... Here is the issue, I am using Mathf.Sin(); But for some reason, the Y value here isn't Transform.position.y
[Header("Variables")]
public float amplitude;
public float speed;
private float tempYPosition;
private Vector3 tempPosition;
private void Start()
{
//Getting the Original Y Position
tempYPosition = transform.position.y;
}
private void Update()
{
//Ambient Effects
tempPosition.x = transform.position.x;
tempPosition.y = tempYPosition * amplitude * Mathf.Sin(speed * Time.time);
//Setting the Offset Position
transform.position = tempPosition;
}
Can anyone help me out here?
im not sure if it is your issue, but keep track of the original position of the object and use that
wait
ermmm
u are
im stupid
sorry
No Problem, I am confused on why it is not using the position value
which position
transform.position.y
Yep, Exactly
herrmmph
Wait, Let me try Logging that and checking to confirm
ok
Well... When I logged it, the value was as it needed to be
But the Motion is still at Y = 0
I've had these weird ass issues before... let me think
Oki
can you send a video so i can see what its doing
Yea... One sec
ok
Give me few Minutes... OBS for some reason is taking time to open up lol
in the meantime try transform.localPosition.y
Nope, It still is the same... Floating at Y = 0...
im looking trying to think, one sec
Yea sure...
ok.... try putting in transform.position.y into the part with the amplitude and Sin(), its not going to work, but see what happens
instead of temp y position
Ok
I think Gaia pro 2 has terrain tiling with additively loaded scenes, did you try it?
Nope...
tell me if it still floats at y = 0
It still does
wait I think I got an idea...
I will try adding the Y position, rather than multipling
Let me see
then something is setting the Y pos maybe?
DISABLE THE SCRIPT AND PLAY
oops caps lock on...
Holy... It works.... uhhh what
with multiplying
no... I changed it to adding
oh
tempPosition.y = tempYPosition + (amplitude * Mathf.Sin(speed * Time.time));
nice
Thanks Btw... You helped!!!!
lol
Thank You!
yw
it is very bad. It instantiates a lot of scriptable objects to save them as files. But it means that it is required to use import each terrain + there is only usage for ALL terrains or terrains by one.
And when using on big ammount of scenes - it loads all scenes. And even dedicated server with 128 GB Ram can't handle this
hi! does anybody know how to import csv files for unity localization at runtime? or if its even possible
Okay, so, odd question, but does anyone know a way to update a mesh's origin without moving the mesh?
Context: I have some procedurally generated meshes. For this example, consider a door. That door is generated as a mesh at position 0,0,0 with vertices at, say, 10,0,0, 11,0,0, 10,2,0 and 11,2,0. So, the origin of the door mesh is at the origin, and if I were to rotate it, the door would "orbit" the origin. What I want is to be able to put the origin at 10,0,0, and have the mesh's vertices at 0,0,0, 1,0,0, 0,2,0 and 1,2,0, so I can rotate it on that "corner" to open and close the door.
What do you mean by "not moving the mesh"? Like it ends up in the same apparent position after the transform?
Can you offset the position of the GO the mesh is attached to and apply the opposite offset to each vertex?
Yeah, right now the door is where I want it to be, but the actual GameObject is at 0,0,0. I want the door to remain where it is, but with the origin actually at the position of the mesh. I figure I'll need to do something like that, but I'm not actually sure how I'd programatically get the "true origin" of a mesh.
Although, now that I've asked this question though I've just had a bit of a brainwave. My door meshes are rectangles, and since I just need it to be at one edge for an opening animation, I don't actually care which corner I find. Any of them work. I can just grab the first vertex I find and make that the origin, then the rotation will work fine. I don't care if the door opens in or out.
nice! Glad I could rubber duck for you
hmm
if you wanted to improve performance of particles, you would use vfx graph's built in pooling system
Hrmmm that actually seems like a pretty good idea, thanks!
this is the approach today
there is instancing in 2022.2
Is there a way to do something like GetComponent but target an interface (i.e. a component with that interface)? ๐ค
GetComponent works on interfaces
If the interface is on a mono
So you can just specify an interface, it will grab any components implementing it
Oh well there you go
Which does it return if it finds multiple
How does it define 'first'. Script execution order perhaps? ๐ค
First one it finds
No idea how it defines it, just starts looking until it finds one afaik
Huh, that would clean up an ugly area of my code then!
I was looking for interfaces in children and had an ugly for loop filter with 'IsAssignableFrom' to get the interfaces out of the monobehaviours.
Fortunately I won't have two on one and will never need to know! 
haha that's nice to know
I just have been hard casting it
it looks ugly but if you know that a reference to an interface is indeed a mono behavior you can do it
I already made the change from monobehaviours->interfaces to just getting the interfaces directly. All tests passed so I'm happy with it
@plain abyss SerializedObjects aren't the same as reflection, they're still slow but fundamentally different things. They are also the recommended way when interacting with fields on an object during edit time
What?
I tried doing the sls deploy, but I got this
had anyone used "frame debug" ?
my render target has only RT 0 and Depth
officer example :
screen will be black if i chose Depth
4 RTs is deferred rendering and 1 is probably forward rendering
https://docs.unity3d.com/ScriptReference/Camera-depthTextureMode.html probably set this
Hey guys, I would appreciate advice on how to structure my code. I am creating a game similar to LoL/Dota, and I am currently working on a stats system. My idea is to have a Scriptable Object with all possible stats (health, mana, etc), then have derivatives of this object with concrete static data for each hero. After this, I want to have a generic abstract script, which will contain in-game stats and be attached to the hero. This script will take static data for the hero and add possible modifications. So, it will have something like MaxHealth = BaseMaxHealth + MaxHealth Modification. My question is how to make my generic script to take data from static data for a specific hero?
Also, I am curious what you think about organising it in this way.
To summarise, the structure is one scriptable object with possible data, multiple static data derivatives of these scriptable object for each hero and one generic script, which takes this static data and modifies it
your approach is the wrong
dont think about "static data"
thats the most stupid thing you could do
ive made my card game data which has the same problem like yours
problem : needs to be resettable
i would recommend not to use scriptable objects at all
because it doesnt make sense ๐
lets say you got HP and Attack
this means you got a protected value which can be cahnged
You can use scriptableobjects but only as a data store, not as runtime data
and a readonly data which just calls the resetable method of the data
namespace Model.Cards.Data
{
[Serializable]
public abstract class CoreData<TVal> : IResetable<TVal>
where TVal : CoreData<TVal>
{
[field: SerializeField] public string Name { get; set; }
[field: SerializeField] public Attribute.Environment EnvironmentType { get; set; }
[field: SerializeField] public int Cost { get; set; }
public virtual void ResetTo(TVal data)
{
EnvironmentType = data.EnvironmentType;
Cost = data.Cost;
Name = data.Name;
}
public bool Equals(CoreData<TVal> other)
{
return other != null && EnvironmentType.Equals(other.EnvironmentType) && Cost.Equals(other.Cost) &&
Name == other.Name;
}
}
``` for example thats my data
Also doesn't make much sense to keep it as scriptableobjects since you will want a server authorative model and your server is unlikely to use scriptableobjects
[Serializable]
public class EntityData : CoreData<EntityData>
{
[field: SerializeField] public Attribute.Nature NatureType { get; set; }
[field: SerializeField] public int Attack { get; set; }
[field: SerializeField] public int Breakthrough { get; set; }
[field: SerializeField] public int Armor { get; set; }
[field: SerializeField] public int Health { get; set; }
public override void ResetTo(EntityData data)
{
base.ResetTo(data);
Attack = data.Attack;
Breakthrough = data.Breakthrough;
Armor = data.Armor;
Health = data.Health;
NatureType = data.NatureType;
}
public bool Equals(EntityData other)
{
return base.Equals(other)
&& Attack == other.Attack
&& Breakthrough == other.Breakthrough
&& Armor == other.Armor
&& Health == other.Health;
}
}
``` an extension of the above classs could be like that ( prob thats what you want )
protected EntityData ChangeableData;
private EntityData ResetData
and you would call the ressetto
with its private data
in editor you only let the private data be settable
not the protected one == your scriptable objec
also you would have duplicate classes with scriptable objects which is just cancer in maintainability
you can do mine and on server side you check the values additionally which would be most secure i guess
to do a double check
as user would have to modify code and addtionaly break through your server
which is neear impossibility
Thanks, guys. I can see now how scriptable objects create problems in this case.
Are you aware of any videos/articles I can watch/read on this? I am relatively new to Unity/C# (came from Warcraft 3).
Or maybe you could give me a simple example of how this could be structured.
@buoyant vine , in your example, in the abstract class CoreData, where data is coming from? How does the EntityData class understand where to take the data from (in this case which card it is)?
Are scriptable objects are just not good for multiplayer game because of the problem you described?
Yeah the problem is mainly with your server side, you would not want scriptableobject for the server
My current way of doing it is to just load those configs from json file, since its easier for both server and game designers to do balancing
I can give you some example if you want
This would be great
Ok, I'm commuting so I will dm you some example later
Thank you)
SOLID, clean code, Uncle bob,kent beck , grady booch
KISS , YAGNI , DRY
Thanks
Another question I have is actually regarding SOLID. I have a Movement Types class, which takes any input (interface), checks what Movement Type the Unit has and then its extension performs a specific movement type (For example, walking). As a type of movement, I have RightClick. Would it make sense to abstract RightClick because, for example, I might want to right-click to something else rather than movement at some point in time? What would be the way to abstract it? Maybe event?
public class RightClickMoveInput: MonoBehaviour, IMoveInput
{
public Vector3 MoveInput {get; private set;}
public Camera playerCamera;
private void Update ()
{
GetInput();
}
private void GetInput()
{
if (!Input.GetMouseButtonDown(1)) return;
Ray myRay = playerCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit myRayCastHit;
if (!Physics.Raycast(myRay, out myRayCastHit, Mathf.Infinity)) { return;}
MoveInput = myRayCastHit.point;
}
}
make a keycode field that you swap
if you dont want to move make it null
If(currentkey != null && Input.GetKey(currentKey) => move
and stop that "reduce nestings blabla" if it doesnt simplify your code
it sucks ass in that case as you just make everything the opposite of human thinking
which makes it barely readable
thanks
: D
RaycastHit myRayCastHit; whats that tho ?
stop that
Physics.Raycast(myRay, out var myRayCastHit, Mathf.Infinity do that instead
RaycastHit myRayCastHit;
if (!Physics.Raycast(myRay, out myRayCastHit, Mathf.Infinity)) { return;}
MoveInput = myRayCastHit.point;
====
if(Physics.Raycast(myRay, out var myRayCastHit, Mathf.Infinity) MoveInput = myRayCastHit.point;
its equivalent and shorter
which is apart from more readable
not against the human way of thinking
Makes sense in this casse
but this does not work as well when your if clause is much bigger
or you have multiple nestings
Rob talks about reducing unnecessary code nesting.
More at: www.acromedia.com
how to make the UI buttons work while its hold
function unnecesary () => return a != b && a > b; done or the mentioned one in the vid
no nesting crap
we dont do dat
it has some values but not in your case
but nesting would just be in your case that you dont have the brackets
which doesnt give you any advantage
and in your case its even more unreadable
which is against any SOLID principle you want to follow
the entire "clean code" stuff is about making readable code
that means you can break all principles if in your case it doesnt fit
thats an important thing you need to keep in your mind
in most cases it fits
Hey folks, I'm having an issue with Unity Netcode. Trying to establish my first connectivty between Host and Client. Well, I have a NetworkObject which is working fine on the Host. But on the Client it doesn't have that checkmark checked "Is Client" therefore any client code is working.. any ideas?
Why all my entities that use this code are all sychrinized?
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));
startTime = Time.time;
}
void FixedUpdate()
{
startTime += Time.fixedDeltaTime;
transform.position = new Vector2(transform.position.x - step, Mathf.Sin(startTime) * screenBounds.y / 2);
}
I mean I use Time.time and I spawn them in different times
But they follow the same sychonized rhythm
lets say time.time is on 0.04
then next fixedupdate proc would be 0.05
where you add it
to 0.09
but next proc of fixed is 0.10
so anything that spawns in between 0.0000001 and 0.4999999999 is synchronized
as example
so largest time between spawns fixes it
idk you dont use anywhere the start time
Because only now that i test it they spawn so frequently
Time.time is the time since the game started so regardless of when you spawn they'll all end up with the same startTime value
I do in mathf.Sin
ah nvm
ohhhh
what you probably want is startTime = 0 instead in Start
which would lead again to the problem i mentioned i guess
Or if you want them to start in different positions, startTime = Random.value * Mathf.PI
Works super fine ๐
Thank you
Thank you both
script1 https://www.codepile.net/pile/zJNVbQJr
script2 https://www.codepile.net/pile/bZ6pvNBj
how would i go about attaching script1 to the objects that script2 creates automatically
{{ description }}
{{ description }}
instantiate has a return value
Also, Is fixed delta time better than delta time in my case?
Casue Im going to use it on a phone and I want it to be exactly the same
There's no physics simulations involved so this should be in Update
But as I understand it. If Update() is faster on a faster machines
So When I put it on my phone it will count way faster
Slower*
thats unimportant, as you negate the speed with the time
you will be with 1 fps as fast as with 10000 fps if you negate the fps with the deltatime in update
fixeddeltatime or deltatime?
in update you need deltatime ( wher your code should be anyway as mentioned allready )
Time.deltaTime returns the amount of time in seconds that elapsed since the last frame completed. This value varies depending on the frames per second (FPS) rate at which your game or app is running.
thats deltatime
and fixeddeltatime is that
Time.fixedDeltaTime controls the interval of Unityโs fixed timestep loop (used for physics, and if you want to write deterministic time-based code).
This is my code right now
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));
time = Random.value * Mathf.PI;
}
void Update()
{
time += Time.deltaTime;
transform.position = new Vector2(transform.position.x - step * Time.deltaTime, Mathf.Sin(time) * screenBounds.y / 2);
}
It works. Will it work exaclty the same with a phone?
dont see why
it should not behave same
you should get some simulation test devices
you can install them on your pc
I do test it every time I make something new
these are ful emulated phones
where your pc simulates that exact processor and OS
very fancy stuff
But when I was using StateMachineBehaviors for an animated boss
whenever I used deltaTime in OnStateUpdate() it was way faster in the editor that in the simulation. So I used FixedDeltatime and I was saved
Is there a callback which I can use to have code run every time an instance of a scriptableobject is created via CreateAssetMenu?
or alternately if i write a parameterless constructor will that be called?
You did something wrong then
And deltaTime should be used in fixedUpdate ๐
How would i go about having my camera follow a curve? Currently my camera when i scroll just moves up and down depending on the direction scrolled. How would i make it move along a curve, where the higher up from the ground it is, the quicker it moves down, and the closer it is to the ground, the more it moves forward
Sorta like this
Are you trying to achieve the third person camera zoom effect?
I have an array of bytes, serialized chunk (array) of structs in ECS
How can I get a pointer to this byte array?
I have a pointer to other chunk, to which I need copy my bytes
Yeah sorta i guess, but the camera is independent of any character
Think you want a dolly path for that (Cinemachine) https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineDolly.html
you can take a look at different ease functions to do certain "shapes": https://easings.net/
Thanks for the readings guys, ill check em out
Could somebody help me out with a forum I posted? It's about gamecenter not working in my unity project.
hello everyone
i have seen some people opening namespaces to show implementation of api classes like System.Collections.Generic to show implementation for List<T>
and I want to check UnityEngine to check the implementation for the Input class
do anybody knows how can I do that?
im using the atom editor so ctrl b opens the currently open scripts search
how this command is called on visual studio?
ok, thanks a lot @buoyant vine
Any idea what type components can possibly be in this scope?
(IntPtr)(components + (i * savedType.elementSize)) , where i and elementSize are ints.
Declaration of components looks like this:
var components = this.Deserializer.ReadBuffer<byte>(headerChunk.Length * header.ElementSize);
But wtf is inside Deserializer is unknown.
a bit of context: this is serialized into byte array NativeArray of unmanaged structs
usually you just have code on the script like if (isLocalPlayer) ...
um how i can do this
Class called CoinPickUp:
private void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Duck") {
CoinScore.coinAmount += 1;
Destroy (gameObject);
}
}
Class called RandomSpawner:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) SpawnObjectAtRandom();
}
so in randomspawner i want it to run that "SpawnObjectAtRandom" when that item is destroyed in coin pickup.... how do i change the code in RandomSpawner to do that
:O dam... straight up like that
pretty much every networking framework has a way to do this
in the documentation/examples for your network framework
are you have link>? netcode
Hi everyone, semeone have idea how to fix this ? I am on the latest version....
I tried to use INetworkSerializeByMemcpy
but netcode takes more than FixedString32Bytes
I saw that someone reported the bug but the case is closed https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1396
if i use a string is not possible to create a NetworkList
are you serious on the first picture? post it properly
sorry I take another
public struct LobbyPlayerState : INetworkSerializable, IEquatable<LobbyPlayerState>
{
public ulong ClientId;
public FixedString32Bytes PlayerName;
public bool IsReady;
public LobbyPlayerState(ulong clientId, FixedString32Bytes playerName, bool isReady)
{
ClientId = clientId;
PlayerName = playerName;
IsReady = isReady;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref ClientId);
serializer.SerializeValue(ref PlayerName);
serializer.SerializeValue(ref IsReady);
}
public bool Equals(LobbyPlayerState other)
{
return ClientId == other.ClientId &&
PlayerName.Equals(other.PlayerName) &&
IsReady == other.IsReady;
}
}
error CS0315: The type 'Unity.Collections.FixedString32Bytes' cannot be used as type parameter 'T' in the generic type or method 'BufferSerializer<T>.SerializeValue<T>(ref T, FastBufferWriter.ForPrimitives)'. There is no boxing conversion from 'Unity.Collections.FixedString32Bytes' to 'System.IComparable'.
excuse me here is the code, I'm trying to make a NetworkList to access the names of the players to place on a UI
why are you you using FixedString32Bytes
FixedString32Bytes doesnt implement the interface IComparable
use a string
why is there a lobby state? if you are implementing this you are working too low level
if I use string the NetworkList say me ``` The type 'LobbyPlayerState' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'NetworkList<T>'
i mean i don't know that much about unity's new multiplayer package, but if it asking you to do this you should not use it
i think this package is not ready for prime time
you really should not be using it to make your game
stop while you are ahead
isnt netcode the old mlapi ?
based on what the user is doing the code is new
kay
but it's hard to tell. all of this stuff does not work
if you want anyway a lobby system why do you not use photon which PRIMARILY focused on lobby games
so it's not good to use the netcode for GameObjects? it better that I use Photon instead?
in my opinion if you're getting bogged down by an arcane bug like this
and your game is otherwise pretty standard
you should use photon so you can move on with life
i dont even know how you would setup a entire multiplayer game when you are only allowed to use non nullable objects
the game will be a battle royal style where I would like to manage several clients in a server and have waiting people
this is a long journey.
use photon
I understand this
whenever these games are written in a statically typed language like C#, you wind up with a dictionary of enums -> values
so that you can reference the fields dynamically but without reflection
thanks so much!!!
you would separate BASE_MAX_HITPOINTS, MAX_HITPOINTS, etc. etc.
waiting girls
fish-networking would be fine as well
never heard of that
aahhh google translate sorry
yeye "google translate"
what do you mean by reflection?
for example you might have a piece of code that reads
reflection is used to get deep into stuff like making a class loader / set variables even when they are private
should not be used in buisness logic
