#archived-code-advanced
1 messages · Page 180 of 1
No, both are paid programs
Oh ok, would you happen to know any free ones?
Oh wait are these separate programs? I was looking for something that runs in my code
correct, they are separate programs
Oh ok I see, thank you for the help but I will try to make it myself then!
I suppose runtime atlasing would be useful for programs like Scribblenauts
or a program where you draw the sprites and operate on them live
I am just doing the atlasing once at the start of the game, this is for modding purposes
So people can just drag and drop textures and the program will register them
yeah that's quite a significant task -- good luck
meanwhile, trying to make this render feature use the new RThandles for blitting is crashing my editor because I'm not cleaning up somewhere even though they say "oh it doesn't need to be cleaned up!" and running out of memory
rip
what is RThandles
and blitting? I have heard of blitting but not really sure what it is
RTHandles are an abstraction of render textures
blitting is a GPU operation to "process" a source texture to a destination texture
the "process" can be as simple as a straight copy from one image buffer to another, or it could render the source image buffer through a material/shader onto the destination buffer
often used for post processing effects
I use it to emulate crappy television signals
ohhh i see, that makes perfect sense
an image effect works by "grabbing the viewport image from the GPU into a buffer" and then the buffer can be assigned as a texture to a shader/material which is then re-rendered over a full-screen rectangle using that material
@floral flume do you think that making a texture atlas that is just a long rectangle of textures is bad?
I can do it a better way but that would be way easier
I think it's probably OK, and if it gets too long you could possibly segment it into multiple files
so have multiple atlases if you have a lot of them
do this for now, at least you get off the ground and have something usable until you get something nicer later
It will have to be the same file since this is being used as the albedo on a material
ok cool, yeah I will definity look into making it more efficient
follow the golden rule of optimization: "don't"
LMAO I believe in that rule whole heartly
Quite often the optimizations we struggle to create don't even help, which is why profilers are a thing
the profiler will say: "80% of your CPU is being spent on 20% of your code"
uuuu I dunno if I should have some sort of static directory of RTHandles that I want to pass between multiple render features in an effects chain in a render pipelineeeeee
this sounds very hacky and bad
i got no clue
so hey I am going to now "paste" the textures onto the atlas, do you know the best method I can use to make this work simply?
heh, you asked "best" method. But in the end it comes down to costs and benefits.
Like, the GPU could probably be tasked to do it really quickly but then it is a lot to deal with
best and simple is what I said, I dont need the MOST OPTIMAL
what AI framework would be best suited for a simulation in which npcs start building houses and fulfill their needs like sleeping eating etc. I thought about mixing GOAP and Utility AI
well... I'm guessing that the atlas will be immutable once it is loaded and stitched together
indeed
and you're gonna need some way of storing the rect coords as well as unique identifiers
like a dictionary
I recommend asking that question again in a few minutes cause our convo might drown it out
will do haha
I have that covered
sorry, actually I might be able to make it a thread let me try
hmmm... skyrim, or dwarf fortress?
Texture Bliting
more like skyrim 🤓
are you trying to have parameters that all come together to determine what your AI will do or do you have a single action for each condition like: if tired then sleep, if hungry then eat...etc
different parameters that come together
maybe I need to do some more research myself on these topics I never dabbled in AI much and I am pretty much a beginner
and are you wanting these ai to learn or to have a preset of behavior?
preset
Well then I think you should try simply making a list of tasks that can be queued up when ever and run through over time. And make priories like death actions and sleep (passing out) so that they overtake the other queued tasks.
Then you can make another list of conditionals where when things happen to the ai, they run through their conditions and check if they are true or not, each condition will either lead to queueing up a task or adding to a variable that needs to pass a certain threshold and if so then queing up a task
if you wait a sec, I can set up a tiny framework for you
you're a saint
something that will get you started but you will do the heavvy lifting
i will make it intuitive
I just need a direction and I am thankful for every input
AI research is fun but its a topic i just started learning looking forward to it haha
the world of ai is so AMAZING
I think that people are odd creatures in that they are actually multiple competing systems, some driven by thoughts, some more driven by urges
profound and so random lol
so if I were to make a system of people I would have them possess multiple systems that track things like bodily needs and urges such as hunger/toilet/fatigue, and other systems that track things like "progress on job/need for money/need for entertainment and socialization"
and these systems would have to compete against each other to determine what needs to be done first
now this would result in people that don't plan for anything -- they would be rather childlike
its wether to unga or to bunga in the end
just out of curiosity, do you know how virtual and override methods work?
but there would be systems that govern fulfillment of purpose(unga), and then systems that govern needs of the body(bunga)
I mean there is a pyramid of needs that exists at least as a model
and the top of it is self fullfilment
virtual methods exist in the parent class and may be overridden by child classes
yes, but I was asking Michael lol
you can stop right there, I might have given a wrong impression but I know too little about a lot of things. need to learn a bit more to unterstand some fundamentals
oh well, they are very simple and fun, do you want me to stop the framework?
no worries if so since I am going to use this framework myself also
you can stop it ❤️
no need to do work for me which I wont even properly understand yet
ok sure thing. I was going to give you a very brief and understandable rundown of it but I am not gonna force you. Anyway I am still gonna continue since I want this thing finished for myself
in fact, this is actually going to be something I need to do for the game I am currently working on
ill get back to you and thanks for being so helpful to strangers on the internet
My pleasure, plus your not necessarily a stranger since you somewhat demonstrated you mentality and personality and also use the advance section on the unity discord about AI frameworks so either you are a normal programming person that's curious and wants to learn a bit or you found the most specific way of cyber manipulation and/or kidnap
Making a panel that comes up when you press a button that shows a weapon's stats depending on which weapon's button you pressed. I need to change the weapon sprite that pops up in the panel to whatever sprite is linked to the weapon. Problem i have is there are 20 weapons. Is there a better way to do this than declaring 20 public sprite variables and inputting each sprite? Maybe there is a way to get the sprite from the image of the child and just change the sprite to equal that? Not sure how to implement that but it might be cleaner, looking for good performance out of it since it needs to do a lot of operations fast when bringing up the panel for the weapon
mecanim is able to record the sprite index of a sprite renderer, I think.. or you could use a List<Sprite> instead of separate vars
Learn to use arrays/lists
Is anyone familiar with the PID Controller being used in the Unity hover racer project? How do I expose the public properties of that script so I can fine tune it in the inspector? It doesn't inherit from Monobehavior
SOrry i didnt explain properly but thats currenty what Im using. I was wondering if there was a more advanced way that was cleaner than having to drag and drop 20 weapon prefabs or sprites into an array in the editor
Hey does anyone know how to turn off repeating texture using graphics.blit()? The image wrap mode is where the problem is but there is no option for no wraping.... How do I do that?
Resources.LoadAll?
Doesn't that work in the runtime?
I think there's an option to create a sprite altas with sprites in a fold, but I'm still dragging eveything
Why not save a reference to the correct sprite wherever you're saving the stats for each image?
What does it inherit from?
im not saving the stats for each weapon anywhere. Trying to figure out scriptable objects for that rn
ok this is a weird problem. I have a float[,], and I need to downsample it to a smaller array, as if it is an image
what is the easiest way to do that
should I like, take every other point and average it with its neighbors
it's for an LOD map so it's fine if it looks lumpy
Well, when you make your SOs you can stick the image reference there too.
is there an implementation for trng? or is Math.Random() true Random
i found RNGCryptoServiceProvider. i am not able to test it rn but is it fast?
It didn't inherit from anything. But I got it expose as a scriptable object now, works just fine. Just need to figure out how to tune it for best results
You can't generate true randomness without specialized hardware
Why do you need it?
signature algorithms and encryption
Not sure if this is advanced, but lets try it here. I am loading a chat collection from a backend and then getting parts out of it to not overload unity UI, basically lazy loading. Attached is my approach, which is 'working' besides the positioning, just ignore the sibling part. But do you have any suggestion or maybe idea, how to make it more dynamic? Not sure if this is the best approach so far: https://pastebin.com/B7evNzCz
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.
Sounds a bit like The Sims
Hi there. Just a quick question. If I wanted to add a pre-build process to my project how would I do that? For example if I have a separate command-line based exe file (stored outside the unity project) that builds and adds some important data files into my Unity project's resource folder, is there a way for me to automatically run that as a pre-process when I press play or build the Unity project? Any help would be appreciated. Thanks.
Sorry if I've posted in the wrong section but I didn't know where else to ask this
my friend copied code from the internet and it comes up and he has a compiler error how to help him?
or he will give up and not submit anything and fail
(Moved to General)
its legit he is in my situation
if we dont submit tomorrow we get 50 percent off
he has copied code but it comes up with compiler error
he got muted, dont expect a response
BTW you can just select them all and drop them all at once. You don't have to do them one by one.
Does anyone know how to resolve this issue?
Using .net core and unity webrequest can't find a good answer on google
well your SSL certificate is either wrong, or not correctly configured or you ar eusing https:// where no ssl is present at all
I'm just running it local and It tell me I already have a developer certificate.
The API is using Https, found a work around tho.
public class AcceptAllCertificates : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
return true;
}
}```
When using a real server you it shouldn't be the case anyone more
Get the right version is better
Validation is there for a reason, you might get runtime/compilation errors otherwise
how do i get the right version?
that is a package that I've installed from github
not what I should be looking for
Idk, download it from nuget or something
well it's not there, but if it's saying that a higher version is already running , maybe I could just exclude that folder from the package ?
Sure you can override assembly references if you change the package
Still, it'll complain about conflicts
So you need to decide which version to use
I can use the higher version ( version 5.0.0.0 ) but how do I override the version ?, i have never modified anything in the package folder before
Either recompile the DLL to depend on that new version (or remove version dependency all together) or disable validation for that dll (or project)
I'm trying to make a car accelerate using an animation curve how can I do that. This is the current script
Animation curve uses the evaluate function to get the value at a specific time point
and the time point how can I find that cause that's what I'm trying to find cause that doesn't give me a code example to understand
Depends on your curve, did you play around with it? the time is basically the length of the curve. So whatever value you put in as time will return the value at that timespot
I put it till 5 end
so your time is from 0-5. Thats your timespan you can work with
ok so I do animation.lenght?
I think that returns your key count, so yes, get the latest key, get its time, then you know your timespan
animationcurve
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
thats an example
ok so now do I do anything else
Depends on what you want to do with that curve 😄
to accelerate the car
Hi, I'm having a logical problem. I'm thinking about implementing a placement system in my 2d game, basically a grid for all placed objects on the map. The problem is combining this with procedural generation: Using start for an object to place itself on the grid wouldn't work due to the procedural generation all being in one frame, but awake comes in handy I guess (?), but how should I go about the destroy function? Because OnDestroy() is getting called too late, so clearing the object from the grid happens too slow for a switch of objects for an example, the old object tries to get cleared, but the new object is already trying to write over the grid, but the old one is still in the way.
I hope you get what I mean, I really don't know how I should be implementing it, I got a few different options, but I'd like to hear your ideas :)
thats not a good description. I mean you head something in mind using the curve, so what was it
I want the curve for the speed of the car to speed up
So you want to accelerate the faster it goes the faster it will accelerate or what exactly?
yes I want the car to go faster
Build failed. It works in gamemode. Help please?
just like you said
you have input problems
Well than accelerate it from 0 - 5 with the value of your animationcurve. So the first value should not be 0
I think Assembly references are the problem
ok so I make the power being the number * the motor power
To be honest thats something you should prototype on your own now. Theorising everything wont work hear. Try out and see what the result is 🙂
ok so it works but now I need to find a way to make it that when your not giving inputs it brakes
editor scripts need to be in a folder called Editor
Thank you!
ok so it worked but then when I let go it wouldn't start slowing down
Go find out yourself 😄 I can't do the thinking for you
If you tried something, com eback, but first, this is not advanced, so lets head to #archived-code-general and second fiddle around a bit so we have a base to talk about
For a series of scriptable objects im using, does it make more sense to store the level the player has upgraded their item to inside the scriptable object and edit the contents of the scriptable object when leveling up? Or does it make more sense to leave that data in Playfab API and make api calls to it when the user views the data or changes it?
Currently rocking it with Json files uploaded in Playfab but this seems inefficient and potentially costly and buggy if players spam between inspecting different weapons. I just want to make sure the player upgrades are safe though, and tied to an account so if something happens or they uninstall, they dont lose all the levels they dumped into each weapon. Would data changing for a scriptable object even work for this and would it save the data to the account somehow if the user changes devices or uninstalls?
You can not use script able objects for save data in a build
"can't build when scripts are compiling" what is this?
Wait for the compiler to finish working before making a build
Usually a spinner bottom-right indicates a compilation is in progress.
ok thanks
"'texture 2D' does not contain a a definition for alphaIsTransparency"
does anyone know a way to export a unity game or something like that without doing the build thing?
you have to build your game for it to be playable. like that's literally the entire point of building it.
then why It aint building then
It's like asking how you can run code without compiling, you need to do it
why It works perfectly fine when I play it normally on the thing
but now when I export it it says there are errors?
What error are you getting, ill take a look
this isn't really the right channel for it
Was thinking about that, where could he best post this if i may ask?
#💻┃unity-talk probably
"texture 2d does not contain a definition for alphaIsTransparency"
hi, how are you guys ? .. i have a short one .. it's more an opinion thing .. what is the most common thing u guys use interfaces for?
adhering to unity's constraints on components and making them compatible with the engine. For making own interfaces generally things I know I want to reuse later in several scripts or objects, etc.
Is it a bad thing that I routinely find it faster to solve problems caused by a lack of documentation or Unity bugs by hacking together my own solutions and workarounds rather than going through the official routes?
yes and no. Unity changes a lot and isn't always up to date with documentation, but this can bite you later on, especially if things end up updating or if it's a long term project. Best be careful with hacking things together
With that said, sometimes you just need something to work and can look into fixing it properly later 🙂
yeah, my problem is it is a long term project but the problems i run into leave me dead in the water until a fix is made (either by me or Unity pesonnel)
and I kind of don't feel like sharing around my hacky crap, especially since most of the time it is odd edge-case scenario stuff
Make sure not to go against Engine constraints, OOP constraints and generally you should be okido
And don't build on hacky implementations or spaghetti because you will probably need to do it properly at some point!
uh, last time I went up against an engine constraint it was back when Apple killed off OpenGL for its metal graphics, essentially killing compute shaders on their platforms (at the time)
that's my rule at least. Quick hack to test things out, or leave it as-is for a bit to improve later. = okay,
hack something together, pretend it's fine and expand on it = please no
uh, my problem is that I hack together things that are needed at the fundamental (fun and mental) level
haha orriight, well i mean if you dont want to share it here you can dm me a bit about your problem and i could take a look (can't guarantee im any help with it though, ill probably reply tomorrow as it's nighttime for me)
thank you for your offer - I'll take it up some time in the future
sure thing, best of luck with this!
well if someone needs to know how to make RTHandles shareable between postprocessing Renderer Features in a URP pipeline hit me up because I don't wanna write a long forum post documenting the solution to a niche issue
posting this here becuase the other ones were being used
I'm trying to raycast in unity
bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, 100.1f);
}
heres my function for checking whether my player object is on the ground
I've set it to 100.1f for testing purposes
my raycast is ignoring a TileMapCollider2D
^^ Tilemap
^^ my object
idk why my tilemap is getting ignored by the raycast
any help is greatly appreciated
I've read that Raycasts only look for gameObjects in specific LayerMasks
but everything in my scene is set to layer 0
they are the same scene
there is a 2D raycast for 2D collider
the 3d variant wount work
Physics2D.Raycast
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
its a easy error to make
Has anyone had trouble with deriving from HashSet<> and implementing ISerializeCallbackReciver?
For me, when I try to Add in OnAfterDeserialize() I get a DivideByZeroException...
I thought to take a peek at the HashSet code to see what might be up, but I am not seeing any divides at all in AddIfNotPresent which is where the exception comes from according to the log
Hello everyone, I am wondering if any person has an idea of how to arrange a number of objects in a straight line, but from the transform origin must be the center of the objects? Such as below. The number of game objects can range from 3 to 5, to 10. Many thanks for your help and sorry for my english, I hope I have explained clearly.
You just take the space you want between the center of each object then multiply by the number of objects, then divide by two. Then you simply subtract the result from the axis of the start position
Then of course iterate over the objects setting there position to be the start position + the offset per object
Sounds like someone's course work assignment :P
Is there a way to use math formula to generate animation curves. I want to enter a formula and it will generate animation curve that I can reference in script.
I am making a theremin and synthesizing audio. I want to exponentially increase frequency, I can do it in code but I was wondering if I can use Animation Curves. Like insert a math formula and whenever I wanted a value using evaluate().
The main reason I want to do this is because someone told me this is a faster way rather than calculating frequency along with soundwave in update.
Yeah, but how do I make that into AnimationCurve?
evaluate it at some range of x
oh wait now i see what you mean
No I still don't get it actually
If you wish to evaluate a formula for some value then insert that value in the formula and calculate it
If you're looking for some formula parser then it will be a lot more complicated
How/where do I enter a formula to get an equivalent curve in anim curve?
An animation curve isn't a formula. It's a series of points that are evaluated in succession
Look up Bézier curves
It sounds like you could get away with making a cubic one in your case.
I am doing that in code but someone told me it would be easier if you saved that formula as a curve and use evaluate to simply look up the value
Well in this case you don't. You can't construct an animation curve out of some formula simply because the animation curve is based on the Bézier Curve formula.
If you wish to make a graph of your formula on the other hand, you would have to sample for some range of X and draw it on a texture
I have no idea how to make a payload kart that turns on ramps. i tried multiple solutions with no results. is there any who can help me out?
https://pastebin.com/miWH8yDY
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.
That's kinda bummer. Thanks for the help.
If you're performance aware you could make a lookup table from your AnimationCurve. So you won't have to constantly evalute it.
But yeah, not sure what you need exactly
It's kinda a complex problem and I'm not too familiar with sound processing
That's exactly what I wanted to do. Enter a formula to make a curve and use the curve as look up table. But I guess that's not possible.
Anyway, thanks for the help
This is the formula and y_lin is float value between 0 and 1. I wanted to reduce calculation every frame
In this case can't you just make a function in code to calculate this for you? Or are you also looking for something like a string input field in the editor where you can input any formula and see what it spits out?
I guess that's me only plan now
Isn't it just cs private double GetThatValue(float x) { return 440.0 * System.Math.Pow(2, 120.0 * x - 53.0 / 12.0); }?
Yup
Then I don't think you should worry about performance, this will most likely be very fast
Has anyone done portable float binary serialization?
I'm confused as to how to handle endianness
or should I just handle it manually, by float definition
Whats your issue
you can do it manually too by float definition.
or you could use a struct with same field offset for float and int, then use bitshifting 4 times on int to get the binary data. dw about performance. structs are very fast and better than using BitConverter
so are you saying that float always has the same endianness as int?
but yeah, the definition is like my only idea
it's kind of annoying, but I can't think of anything else
Since 3 Days i try to use sql on android but why is this shit not working?
on pc its working perfect but on android it says "DLL sqlite3 not found" WHYYYY
float stores data as
sign-exponent-mantissa
1-8-23 bits respectively
each of them follows big endian where the most significant bit is placed at lower memory address
but in practice it might also change based on the hardware. normally you should code based on the endianess of the hardware architecture, which you can determine at runtime using BitConverter class, theres a property to determine it.
BitConverter.IsBigEndian or something like that
this approach is independent of the Endianess
WHY i cannot fix that T.T
Hello @midnight violet i did a for loop on objects in the api i got 20 outputs in the console but how do I get them shown in text game objects inside the game
the dll is properly setup to work with android?
but it doesnt work on andoird
ys
it
is
i have 3 types x64 x86 and ARm
but it doesnt work :c
are you gone? :/
show your code
also whats the file extension of the plugin? android expects .so instead of dll
Okay, i revert my dont mention me, I see I answered you. But still, this is not advanced code question. #💻┃code-beginner or #archived-code-general is your place
yeah it is .so
code is coming
this is the problem method
and this is the newest error
Note that the error message mentions libsqlite.so while you have libsqliteX.so, this might be an issue?
i had downloaded witheout the x but nothing changed
Chill ok I'll ask there if you know please help me with that
I'm not experienced with mobile, that was a guess
oh
Seems like it can't find a lib named sqlite3, can you download something like that?
it is in the folder
Or maybe it's bundled within libsqlite idk
did you by any chance rename the so file? you shouldn't rename the so files normally after its compiled. how are you loading the so file. show the code which does dllimport.
your dll import name shouldn't include .so aswell. just the file name without extension
ist just downloaded sgliter from the assets store lol
WAIT
i tested it in another program and there its running :o
nervermind
the problem is not the importing the problem is soemwhere in the code ```cs
List<Device> devices = new List<Device>();
IDbConnection connection = new SqliteConnection(dbName);
connection.Open();
string where = "";
if (id != null) where = " WHERE `Geraete_UD`= '" + id + "'";
string sql = "SELECT Geraete_ID, Geraete_Typ, Geraete_Hersteller, Geraete_Bezeichnung FROM `Geraete`" + where + ";";
IDbCommand command = connection.CreateCommand();
command.CommandText = sql;
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string ID = reader.GetValue(0).ToString();
var type_ = reader.GetValue(1);
string producer = reader.GetValue(2).ToString();
string name = reader.GetValue(3).ToString();
string type;
if (type_ == null) type = "";
else type = type_.ToString();
Device device = new Device(ID, type, producer, name);
devices.Add(device);
}
This Error comes from this line of code but whyYY????
Can I ask for people's opinion on the age-old LINQ debate? Take this use-case, for example: https://pastebin.com/s1JfHgXq
Assume that allContainers has been populated with entries and their MyConfig properties have been assigned valid values.
Which is "better": BuildListWithLinq() or BuildListWithoutLinq()?
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.
Hello, I have a recurring problem when writing code which needs to assign slightly different values to some variables based on some input. I usually do it via switches/if statements.
Often, I need to write functions in which a translation of some kind needs to be mapped to offsets for some coordinates. E.G. if translation == (1, 1), then offset1 = (-1, -1), offset2 (-1, 0).
I always know the amount of different combinations the translation can have as well as the offset values for each combination. The translation and offset values, however, change based on the context they need to be implemented for.
The problem I have is expressing this logic cleanly via code for all combinations. Ideally I would map all translation values to a switch with constant struct values and set offset values per case. Clean and simple. However, switches don't support const structs outside primitives like int, float, string, etc.
For some functions I have mapped the struct values to a single integer since a const int can be used in switches. E.G translation = (1, 1), (1, 0), (0, 1), (0, 0), then state_value = 0, 1, 2, 3 for each accordingly.
With this solution I can then declare an enum or many named const integers for each case to make the code more readable by making the translation mapping to an integer which regulates the switch state easier to understand. Though this solution still feels hacky and dirty.
Worst case I had done to express this type of logic was to do it with if statements. It leads to a lot of nesting and a mountain of code if doing ifs per single field value. E.G if (translation.x == -1) {if (translation.y == -1)}.
Specially when the data combinations increase in amount as well as field count for a struct.
Lastly, a chain of if else statements for testing every combination remains.
My question is, is there another way which is cleaner that I may have overlooked?
Hey there. I'm having a problem where I'm using a shader to simulate a black hole distortion and rendering the image from a camera to a render texture. I'm instantiating various black holes during the game but the distorted image is updating to the most recent black hole placed instead of each of them render to it's own texture
is there a way to solve this?
if you need more insight, I can try to explain better
I had a similar problem with a button on the experimental SVG image on a world space canvas. I think it's multiple layers of logic incompatible with each other, perhaps lazily programmed
what code are you using? you should pass the already distorted texture to the next BlackHoleSimulation shader
so, something like:
var texture = GetRawTextureFromSceneAsCameraWouldRenderIt(); // should return a copy
foreach (var blackHole in blackHoles) { Graphics.Blit(texture, blackHole.material); }
texture.Apply();
you can use switch (asdf) { case MyStruct m when m.x == 1 : { break; }
Still, some better implementation would be to math the shit out of it 😄
@hardy sentinel thanks, wasn't aware of pattern matching before.
The best way to do this is:
static readonly Vector2Int[] directions = new Vector2Int[] { Vector2Int.one, Vector2Int.right, Vector2Int.up, Vector2Int.zero}
Vector2Int GetDirection(int state) {
return directions[state];
}```
switch statement is way too much code and less performant too
i need help someone
any one have idea how to read keys if game window is out of focus i was taring this Keyboard.IsKeyDown(Key.Down) but error CS0103: The name 'Key' does not exist in the current context
Zenject question. How to inject class but keep the same reference across gameobject?
For example:
Hierarchy:
goA
childA
goA(1)
childA
That's two identical gameobjects (duplicates). Root and child obejcts has same inject reference. How to make 1 inject class for each gameobejct and let reference it to root and child?
You need a GameObjectContext on those root game objects. Then you can put an installer on each root game object that binds a shared instance for that context.
Hm, let met try. Saw about gameobjectContext but thought i can do this without somehow
If these are spawned at runtime, you can spawn them with an argument to be injected
this GO's placed manually
Yea, thats what i wanted, thanks. Feels like ScriptableInstaller will be good for this task (for example if i have integer that will be different on each object)
this will not even work if window is focused.
Keyboard.current[Key.Down].wasPressedThisFrame is the correct syntax.
check for the property name in your IDE once, might be slightly diff than what I typed but you get the idea
i was using System.Windows.Input
yea... don't do that
@tough tulip Keyboard.current[Key.Down].wasPressedThisFrame is not working for me because of what i trying to do
no
and maybe explain there what you are trying to do
Idk if that's possible. But if it is, it almost certainly requires the use of a native plugin
i gave you the correct syntax btw. which platform are you trying? i guess windows?
you need a native plugin for it to work in all cases
https://docs.microsoft.com/en-us/windows/win32/inputdev/raw-input?redirectedfrom=MSDN
@tough tulip i think i found it https://docs.unity3d.com/2021.2/Documentation/ScriptReference/Windows.Input.ForwardRawInput.html
bruh i need to change version to use it
@hardy sentinel No, read #📖┃code-of-conduct.
in HLSL I'm setting positions in an array like this positions[id.x] = float3(id.x, 0.0, 0.0);
I was expecting the position's x coords to go up by 1 each time. But instead it's doing some very...VERY weird things....
It seems that the x y and z all go up by 1 and idk why
Hey does any of you know if you can get the velocity of a gameobject in a direction that is not x,y,z ?? but between them?
huh?
Can you elaborate on what you mean
i'm curious how you expect direction to be expressed without a Vector3
a rigidbody component gives you the velocity on y axis, but what I need is the velocity in transform.up when the object is rotated xD
this sounds like a whole lotta XY Problem since none of it really makes any sense https://xyproblem.info/
Are you asking for how to get the velocity expressed in the object's local space instead of world space?
that would be cs transform.InverseTransformDirection(worldSpaceVelocity)
Thank you ❤️ sorry that I was so unclear, I'm too tired xD
haven't we discussed this?
or was that someone else?
use input system, which can listen to events while in the background
@undone coral i can t find it so probably not
im trying now to get image from copy buffer to unity and i cant get it to work and find something usefull
probably i will end up with opentk and writing some sketchy rendering engine
what is your objective?
what is the game/app
Keyboard.current... in Input System can directly replace your Input calls and supports background listening provided you check the right box
okay
where
you can read through the input system "how to migrate from Input" documentation
then search "input system background" in google and it will show you the checkbox
however, i don't know if specifically the keyboard is supported
because it would be a security issue if any app in windows could read your keyboard
try this approach - https://www.youtube.com/watch?v=FpvJAG6R99k
Hello anybody and welcome to a Tutorial/Showcase on image effect shaders using shadergraph in the universal render pipeline
Github Repository: https://github.com/BattleDawnNZ/Image-Effects-with-Shadergraph
Tutorial For The Blit I Used: https://www.youtube.com/watch?v=joG_tmXUX4M
use tuples of the form
now only getting image from clipboard
foreach (var (transformCompare, offset) in new[] {
// transformCompare, offset
( -1 , new Vector3(-1,1,0)),
( 0 , new Vector3(0,0,0)),
( 1, , new Vector3(0,5,0))
}) {
if (myValue.x < transformCompare) {
myOffset = offset;
break;
}
}
@fossil bloom does this make sense?
i found setting
yes but you must change to input system completely
you cannot use Input anywhere anymore
u mien this #archived-code-advanced message i have wrong unity version 🙂
are you using something from the asset store that is specifically tested on android?
you might need to visit #archived-code-general for further help
i will just make console app
are you sure sgliter is properly installed and works on android?
i just use file to transfer data i was digging for 4h in google
Hey im working on equipping weapons in my game. The functionality is there but I'd like the player to be able to see what weapons are equipped when viewing the panel of guns with a little check mark or something. The only way i can think of to do this would be to have a game object in each weapon's child panel called "GunNameHereEquipIndicator" and say find object in hierarchy with name = gunName + "EquipIndicator"; Which is inefficient on its own, but worse, Id have to deactivate all the rest of the object check marks too. Is there a much better way to do this that doesnt seem so cluttered and inefficient.
I just want the gun that i have equipped to have some indication of it and remove that indication otherwise. For clarification i have one panel with all the weapons on it and you can click on each one to bring up an inspection screen where u can upgrade and equip it. Id like the equipped gun to indicate its equipped on the panel with all the weapons on it
if im understanding correctly it sounds like the checkmark should be a feature of whatever component you're using to render the weapon icon
which is to say that your weapon thumbnail, icon, name, etc, should all be under the control of some component you write / have written
that's how i would do it
that way the component can have a reference to the checkmark set outside of runtime
Sorry not sure I follow. So like i could have an image component with the checkmark as a child of each of the gun panels in the first pic, but I dont know a more efficient solution of checking which is the equipped one than looping through each, checking if it is equipped, and if it is set the checkmark active. (and if not set inactive)
that's fine
It seems very inefficient and id have to keep an array of all the panel checkboxes in my editor/code which is already bulky enough
the slow part is the Find()
the rest is just necessary, you can't know what's equipped without going to the player and asking
but you can remove the Find by storing the reference to the checkmark outside of runtime
How hard would it be to make a rending thing where I could have an object moving around the map and working like a lidar, creating a dot cloud like real life lidars do? I am thinking of a script that uses raycasts in specific FOV, for each point it hits it creates a vertex which in shader can be enlarged and rendered as a dot, additionally that list of vertices could be stored in a ring buffer. Though firing hundreds of raycasts per frame could be kind of expensive, not including the vertex creation part. I want a result just like in the image I attached
Did u mean checkmarks plural because I can't figure out how to have one checkmark that just places itself on whichever ibject in hierarchy i want
Ideally you'd do it in a compute shader (which runs on the GPU). It's basically raytracing, just with a smaller number of rays and different ray sources.
are u using like a bespoke ui for all the weapons?
I don't have much experience with shading, especially compute shaders, any guide where I could start with that?
each one of these "slots" should have a copy of a "WeaponSlot" script on it. And that script should handle everything within that slot: the name shown, the gun model shown, and anything else like checkmarks etc..
Actually nvm, I forgot I have google
if this is the case i'd recommend changing to use like a reusable ui component
that's the way i do things with much of my UI
and then i'll write my UI component
you'll throw the references to your desired name, icon, and checkmark into there
and that lets you use tthem all in a generic way
Currently its all just buttons with a sprite for each weapon and then the button calls the function to bring up the panel with the stats of the weapon with an index supplied to it
time to refactor everything!
you can half-ass it though
if you don't feel like refactoring
write a component that stores the checkmark reference
attach it to each instance of your weapon button
and have it control the checkmark for that weapon index
it's not like nice but it'll work just fine
if i am understanding correctly i feel like redoing it all into what @sly grove recommended of each button getting its own script would be just as involved as this writing a component solution. Only thing stopping me from that idea is i still cant conceptualize how to update each equip "checkmark" other than in an update function which i haven't really used at all in my game yet. If i change it on start and on equipment change would that work even though the game objects are inactive at the time of setting?
so uhhh
firstly
you wanna be conceptualizing the ui here as like
individual instances of a prefab
like any kind of prefab object you expose references through the inspector like the image you want to use and the name of the weapon
and then u can drag and drop them into an objeect to set that all up by hand whhich is similar to what you've already done anyway
those objects are going to run Start() when they get instantiated into the world and that's where you'd do your checking and updating of the check mark
that will be enough i think
and then taking that further would be removing the manual set-up entirely and just instantiating the whole objectset through code but hey that's not strictly necessary here
@sly grove i'm not sure if im explaining this effectively
I see how that would be more effective but this took me a good 3 days to build out and my brain is starting to get fried so i dont know how much im willing to rework here for the equipped indicator. My question would be, if i make the checkmark on each of the buttons and then make a new script that i make as a component for each button, is there a way to call a function in each of them at the same time to do a simple check if (primaryWeapon.gunName + "indicator" == checkmark.gameObject.name) { checkmark.setactive(true) }
You should have some kind of event system with an event like OnEquippedWeaponChanged. When that event triggers, each WeaponSlot will receive a callback and run a method to update its own checkmark. The OnEquippedWeaponChanged event can pass in the newly equipped weapon to that method, so the WeaponSlot can just check whether the new weapon is the same as its weapon. If it is, it sets its checkmark active. If not, it sets its checkmark inactive.
(This is in response to "updating everything in Update()")
ultimately your solution with Find() will work, it just won't be efficient, as you said
you can still do it if you like, and you can probably minimize the impact if you're only calling the find one time for each object (8 objects -> 8 calls)
and like, setting it up so it only calls once can be done a number of ways and is really up to you
you can leverage start()
or you can write a component that does it
or you can make methods and have something call them
Im thinking i may just bite the bullet with another big array of 20 game objects each being the Text field for equip indicator on each weapon in the panel. Then on start and on equip change i call a function that loops through each one and if the name of the text field equals what i want i set it to say "1" or "2" for either slot, and blank if not equipped in either slot. This seems much more efficient that find, simple enough that i know what im doing, and just unfortunately not very cleanm especially for adding new weapons
hmm
i think that if you were to bite a bullet you'd want to be biting the one that's all about making the UI generic
it'll save you time
which solution are u referring to lol. sorry there were a lot of options
essentially this:
- make your UI into prefabs that serve one purpose
- write small controllers for each UI prefab
- expose any references that change things
instantiate those prefabs at runtime and they kinda do their thing in a way where noone else needs to be concerned with their internal structure
by instantiate them though, do you mean i have to set them via code on start, rather than have the prefabs lined up how i want in the hierarchy previously
yes
actually you can have them lined up by hand too,
they'll still run Start() and do their thing at the moment they get loaded into the world
working example:
these are all the same object
so do i still need some kind of event handler to check them again each time equipment is changed? Im not really sure how to make an event with event system. Ive been mostly using input system
when i use this pattern i often find it advantageous to destroy ui elements when i no longer need to show them on the screen.
and if you do the same thinng then you can create them each time you need them, which means they'll run start() at that moment and you put your stuff in there.
ah so destroy them all and when reinstantiated they run a start function
that's one way, yea
alternatively, if you have them always present you can i guess try to keep references to them all so that you can run some kind of checking method but that's more complex i think
this is kinda all structural and it's really up to how you wanna do it but the important part is you have some specific moment where you make them check
makes sense but idk if its feasible to line them all up in the horizontal layout groups i have them in through code. it was very complicated with the settings since im doing some weird stuff for phones with a notch
well you could also put all those thumbnails inside another prefab and then instantiate that prefab
they will all run start() just the same
I see. Thank u for the pointers. I wrote a couple options down to look at later and see which i will go with. I need to get a break for now. Thank u tho
When using ASMDEFs, if I just leave Any Platform checked for all of them, that shouldn't affect the compilation time right? Or will narrowing down the Platforms section actually decrease compilation time?
No, I am only coding it for standalone windows platform and nothing else. So no need for directives and such. My question remains, will leaving Any Platform checked increase compile times over specifically selecting my platform for EVERY def?
Alright. Thanks
Hi,
I was looking at the newer mesh apis, and I want to set the vertex colors with https://docs.unity3d.com/ScriptReference/Mesh.SetVertexBufferData.html
I don't want to adjust any of the other properties of the mesh.
In the example in the docs, it only shows how to set full descriptors and full data for the mesh.
Am I right with the assumption that if I only set the data for the specified stream, it should work? because every Descriptor in the VertexAttributeDescriptors array seems to have a dedicated stream index?
also do I need to check for the VertexAttributeFormat of the colors attribute separately (which I assume is the .dimension property) and take some conversion steps when it is not VertexAttributeFormat.Float32 or is that automatically handled? In the example, the format for the tangent is UNorm8 but a regular Color32 value is used in the struct so I guess it should be fine?
here is the code I have, haven't run tests yets:
private void UploadColorsToMesh(Mesh mesh, Color[] vertexColors, bool skipIndicesValidation = true)
{
int stream = 0;
MeshUpdateFlags updateFlags = MeshUpdateFlags.DontResetBoneBounds | MeshUpdateFlags.DontRecalculateBounds;
if (skipIndicesValidation)
{
updateFlags |= MeshUpdateFlags.DontValidateIndices;
}
int numberOfAttributes = mesh.GetVertexAttributes(attributeDescriptorsTemp);
for (int i = 0; i < numberOfAttributes; i++)
{
var attribute = attributeDescriptorsTemp[i];
if (attribute.attribute == VertexAttribute.Color)
{
stream = attribute.stream;
break;
}
}
mesh.SetVertexBufferData(vertexColors, 0, 0, vertexColors.Length, stream, updateFlags);
}
Zenject question. I have two classes that wants inject 2 references. 1 reference is a base class, 2nd inherited from the base class.
How to sync this inject and let classes reference on one Bar class.
public abstract class Foo{}
public class Bar : Foo
Class A
{
[Inject] Foo
}
Class B
{
[Inject] Bar
public var argvar;
public Bar(argvar)
{
this.argvar = argvar;
}
}
//What I tried
class Installer : ScriptalbeObjectInstaller
{
override void InstallBinding()
{
Container.Bind<Foo>().To<Bar>().AsCached().WithArguments(argvar).NonLazy();
Container.Bind<Bar>().AsCached().WithArguments(argvar).NonLazy;
}
}
there is an extra folder for android so i think so
There are some voxels, they are combined into one mesh. I would like to remove repeated vertices in that mesh.
The common and efficient way is to define a 3d array and keep indices of vertices inside? or define a dictionary but accessing is not optimal in a dictionary
Some kind of spatial hash like quantising or an octree, and better to not add vertices than to add them then remove later
How to change the max size of a downloaded image?
as in, resize it? or expanding it with more whitespace? there's Texture.Resize(..) if that's what you're after: https://docs.unity3d.com/ScriptReference/Texture2D.Resize.html
i mean this setting here
ah.. that should be in the import settings if available.. let me take a look
thanks
that should only be available in editor actually. Doable with something in this context:
class ImageImp : MonoBehaviour {
public Sprite spr;
public int maxSize;
[ContextMenu("ChangeSize")]
void ChangeSize() {
var spritePath = AssetDatabase.GetAssetPath(spr);
var importer = (TextureImporter) AssetImporter.GetAtPath(spritePath);
importer.maxTextureSize = maxSize;
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
probably no options to change max size of asset downloaded at runtime
but you CAN have a template texture for each max size and render a custom texture to it with a shader or Graphics.Blit
Anyone could help me please, I totally new to DnSpy and I tried to load a file resource called ReanimationOST.ogg as an AudioClip, I tried this code but it didn't work, anyone could help?
AudioClip result;
using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ReanimationOST.ogg"))
{
ushort channels = BitConverter.ToUInt16(new byte[manifestResourceStream.Length], 22);
int sampleRate = BitConverter.ToInt32(new byte[manifestResourceStream.Length], 24);
result = AudioClip.Create("Reanimated", (int)manifestResourceStream.Length, (int)channels, sampleRate, false);
}
range.gameObject.GetComponentInChildren<AudioSource>().clip = result;
I have seen this ability but forgot. How can I add an offset to all vertices when creating a mesh?
Might require more details … otherwise I would just answer just add an offset on your vertices. Maybe you can look at procedural meshes to understand how it works
PSA: Do not use BufferedRTHandleSystem in Core RP Library 13.1.
Although the documentation is there, it is merely autogenerated from their comments and there are 0 references to it in Unity's source (meaning that THEY haven't even used it themselves!)
I don't think they tested it, and its own AllocBuffer function is incapable of referencing its own m_RTHandleSystem, which breaks it.
There is also ZERO talk about it on their own site so don't get roped in by the docs.
I wasted a day implementing it.
So, I have to add that offset to each vertex in a loop. I do not want it.
Suppose there is a vertex array and I would like to add an offset to each vertex without any loop over the entire vertices.
I think there is a method (a method of mesh class) to add an offset to all vertices
Also, I have removed repeated vertices and use shared vertices, it is OK but normal maps are not calculated correctly. How can I figure it out? I should use shared vertices, it reduces vertex count.
What does mesh.Optimize() do? If it removes repeated vertices itself, I can utilize it
mesh.Optimize() simply optimizes the mesh for rendering purposes
doesn't really do anything to the mesh itself
iirc
The only way is to calculate normals for shared vertices manually?
? Mesh.RecalculateNormals(). What are you trying to do exactly?
hey, ive been looking for a good math library for matrix math, cuz im a math guy and i like to reduce things to matrix math or regular math whenever i can cuz i can really really remember and conceptualize information and mechanics when part of it involves math
the problem is I cant find a matrix library that actually can function in unity. they all throw runtime errors everywhere and have alot of code marked as unsafe.
does anybody know of one that functions in unity?
cuz the internet has been no help to me thus far. maybe im just bad at googling
what is wrong with unity's math library?
And whats wrong with unsafe code?
There doesn’t seem to be method like that as you may see https://docs.unity3d.com/ScriptReference/Mesh.html. And even if there was, that would obviously just loop over the vertex array under the hood. And what comes to normals, you could elaborate in what way they doesn’t work correctly. In case you want to make flat shaded mesh, you can’t share vertices because you can have only one normal saved per vertex. For both flat shaded (shared vertices) and smooth shaded (individual vertices) RecalculateNormals does pretty good job.
why does changing the texture format of my sprite renderer turns it into blank?
Why do protected interface members can be used only in inheriting interfaces. Why not also in inheriting classes? What is its use?
can you send an example, im not entirely sure what you mean?
interface IInterface
{
protected void a();
}
interface ICar : IInterface
{
void b(){ a(); } //valid
}
class MyClass : IInterface
{
void MyMethod()
{
a(); //invalid
}
}```
that example is flawed in one way or another, MyClass doesnt implement any interface
an interface is a contract, you only specify the method, not the implementation itself. It makes no sense to want this, the interface methods are public by design
otherwise you couldnt expose your interface methods
there are defualt implementations in newer c# versions
If you want to specify specifics in an interface you should just be using an abstract class or polymorphism to extend a base class
I genuinely have no idea why you would ever want to have a default implementation of an interface like this, (as a fallback when editing things???)
For example to add some method to all derived classes
Without creating extra interface
That is the entire point of an interface, i mean the protected property
Also I code with newer C# version which permits default implementation for methods in interfaces so your note is unreliable
aah just googled it, im still not sure what your question is. A protected property by definition is only accessible to the class around it. I see no reason why it should be different here
you're confused between interface vs abstract, I think
why not just make it public if you want to expose it to the instances that implement it?
Protected property is accessible to the class and its inheritors
Not sure
My question is the reason why I can't use protected method in a derived class but can in a derived interface
not sure if c# differentiates that but maybe because IA : IB is actual inheritance and SomeClass : IA is "implements"
Any better ideas?
this seems to be a new feature that really hasn't been fully realised or thought out yet
It almost seems to me they are working on a track to merge interfaces and abstract classes
Note the part I marked red; they don't have a clear use case described here at all imo
the virtual in interface been a while added, since 8 if I'm not mistaken
very useful
Im not sure why you would want a protected member in an interface though? Just for the default implementation?
There is no point imho
i see zero use case for this
I guess the reason is that interface members are supposed to be used by external forces (classes, etc) so it would be stupid to add protected modificator to let member be used in a derived class, so it is used to prevent external forces from using the member (as with private) and also to let derived interfaces to use the member. What do you guys think about this theory?
For me it even fundamentally goes against the idea of interfaces
the use case would be to have common functionality that can be used in derived interface default implementations
the entire concept of a default implementation in an interface is flying right past me if im honoust, I would think it's not the responsibility of an interface to have a default implementation at all, so this seems kinda weird to me.
100%
i feel the same way
Read it guys
We have abstract clases that do it we dont need interfaces to take on roles from that
All a interface shoul do is guarantee me that a given class has a implementation of a given set of methods
Nothing else
why not?
It is how you use them, not all their capabilities
I feel like i would only use a specific interface if it is generic enough, if i wanted to hide certain parts of an interface to a class i would say the class should not be inheriting from the interface
since we can already use multiple interfaces i would make a second interface for the more specific scenarios, and use that for the classes that are more specific
it would be used when you have an ICar and an IPlane interface which both inherit from IVehicle.
there is probably some functionality both ICar and IPlane could use in some default implementation but noone should be able to call the base functionality directly on the class that implememnts the interface
Then what about making APIs? Hm?
so i would say protected stuff in interfaces isnt hidden from implementing classes because it doesnt relate to that class but simply because it shouldnt be used on its own
Nice vision
It has almost the same meaning as my theory
which would also explain Telovs initial question about why it works the way it does
So I think I can write this theory down for myself and use it in future
could you give an example method or property? Im still not entirely sure tbh
I think it depends a lot on a fundamental discussion about how interfaces are used if im honoust, it seems that Uri and me have a bit of a different view than you guys (which is fine of course)
sure give me a sec
just as a disclaimer i have never used that functionality, its just after googling what i think is the intended use case
im not entirely sure what you mean by this, it wouldn't influence APIs right? (as in you can still achieve the same things without that access modifier)
Rephrasing Sejadis' words: interface members marked as protected are supposed to be used not by classes but by interfaces.
Gonna give you an example wait
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yeah, nice example
@fleet lion
You are not going to let your API's users to DoLowLevelStuff by extending ICar, right?
another disclaimer the runtime version im targeting doesnt support default implementations so there might be syntax errors
Saw somewhere that C#8.0 is supprted since unity 2020.2 or a bit later one
(not sure if AnActualCar is how you would write classes with default implementations)
This is a great example, I see what you guys are saying
With your use case I 100% understand and this makes perfect sense, a fair question for sure!
so instead of inheritance chains you can build functionality by implementing multiple interfaces
I feel like an elder explaining something in this channel
The thing is, i would choose to use an abstract class for this myself as I dont define functionality in an interface
yeah it would be useful if you want to mix and match functionality
and not create a subclass for every specific thing
I may be a bit more of a purist in that sense, I think an interface is a contract, and should not contain any functionality in any way, just specify what an inheriting class can or cannot do
like add IBoat and IBike but stuff can be a boat and a bike and maybe a plane too
yeah that is a fair point for sure
no need to create a shit ton of classes for every possible combination
just implement whatever interfaces you want
and honestly i wasnt to sure what default implementations would be used for either but this discussions was also useful for me 😄
I think your understanding is a bit limited, to contracts, but it is up to you
You can inherit from only 1 class, so making such interfaces is nice to me, I have the problem with it right now
So need interfaces
given that you work in a unity version where this is supported, can you copy paste my code for a sec and see if it is syntactically correct?
that's fine. Can't agree on everything haha.
It's a frustrating issue if you want to tackle that SO thing like this for sure, best of luck. Feel free to ping me if you have a solution. I'd be interested in seeing it 🙂
Unless we work on the same project haha
Guess one of us will have to be lead 😉
nah the boss is a third person who has no idea and everything will be different 😉
The problem is not with protected modifier but with inability to inherit more than one class. Read to the end if interested.
Generally, I have interface IUsable which has methods void Use() and bool Usable(). Usable is supposed to be recursive so that you check all conditions needed to use something. So instead of returning true in every base class which inherits from IUsable I want to somehow return true by default but I think it is impossible
oh no, what i meant is copy my example into your project and see if/what errors there are. as my unity version doesnt support it i cant control if that would be correct
Do you have any solution for my problem btw?
hmm whats the problem there? any error messages? logically that should be doable with default implementaitons?
1 issue: someCar var should be of type ICar, everything else is fine (I mean works as we think)
Default implementations are a bit complicated, generally you don't inherit anything from interface, including methods with default implementation, so you can't access default implementation from a derived class itself
hmm sry, as i havent used default implementations i dont think i can really help there
Ok bye
Hi everyone, is there a way to modify scenes before building ? (But modify them just for the build, and don't change them completely?)
I would like to modify them only for the build and do not change them in the editor ^^
I did not get it. When should I use it? I create a procedural meshes, voxel based meshes
Yes, exactly, for voxels, games usually use flat shaders, right? so, I do not need several vertices in one point, keeping one vertex for each point is enough.
afaik splitting the vertices is still the default way to do it. you could use partial derivatives to reconstruct the flat shaded normals from smooth shaded mesh but i'm not sure how performant that is. usually for low poly meshes, the vertice count is so low anyways few vertices here and there doesn't make much difference
Not really. I use this pattern, but I don't particularly like it:
public ref T TryGet<T>(out bool isValid);
ref var matrix = TryGet<Matrix4x4>(out var isValid);
if (isValid) { ... }
Annoying thing with this pattern is you will always need to return something, so when it's not valid, I return some private static field.
hey, i saw that you can run a script at the startup, you can add something on the player loop, but, is that possible but is it possible to do something after "start" (and also awake)
i havent seen the actual playerloop dump in a long time so cant say if awake/start are separated but you certainly can inject your init before first update, which will be after start
yes approach it as ECS
as what ?
just flag your object as "processed"
or remove it from initialization list
or whatever there are many approaches to this
yep ahah, i'm just falling deeply in unity and the doc is not everytime clear as i expect 😂
Hi. I need to get the bytes associated with a SerializedProperty, it can be of any unmanaged value type
// This one I have created myself, it keeps the new value.
SerializedProperty localProp;
// This one I have got as a parameter in my property drawer,
// it has a _bytes fixed size byte array.
SerializedProperty byteBufferProp;
// I just want to copy the value of localProp into byteBufferProp.
// localProp.CopyTo(byteBufferProp);
// My only idea is like this currently:
object localPropValue = typeof(LocalPropWrapperType)
.GetField(selectedPropName)
.GetValue(localPropAsObject);
var bytesProp = elementProperty.FindPropertyRelative("_bytes");
int length = bytesProp.fixedBufferSize;
// Reuse a single buffer to generate less garbage.
_cannotUseStackallocWorkaroundBuffer ??= new byte[length];
// Binary serialize the object into this buffer.
// ?? How to keep this behavior in sync with SerializedProperty?
// What about the struct alignment? Does everything have to be custom??
// I'd like to reuse their system, manual things like this feel more like a burden.
// localPropValue.WriteBytes(_cannotUseStackallocWorkaroundBuffer);
for (int j = 0; j < length; j++)
byteBufferProp.GetArrayElementAtIndex(j).intValue = _cannotUseStackallocWorkaroundBuffer[j];
// Maybe like is there some function that does the following:
// That would be perfect for my usecase (as long as there is a way to cast it back).
BlockCopy(localProp.bytePointer[0 .. localProp.byteLength], _cannotUseStackallocWorkaroundBuffer);
My code so far
Has anyone tried making unity think a byte buffer is of some particular type?
It feels to me that is impossible
(in context of a serialized property)
how do i add a head to the main camera
link's dead
also dead
Weird, it shows up to me
is there a way to get the move direction to be 0 or 1 and nothing in between?
atm i'm getting my move direction by
rigidbody.velocity.normalized
is there a way to only allow 0's and 1's?
so I know clearly where it's moving
Do you know what normalized is?
not really tbh
It makes it 1.
So you are asking, im doing this which makes it 1, how can i make it 0?
What you want is, check if 'rigidbody.velocity.magnitude > 0'
If there is some velocity. Probably you want > 0.1 for some wiggle room
(note this is code-advanced, normalizing vectors is a bit more basic)
eyyy >:(( but true from a mathical perspectiv I guess
that makes sense, ty
Im sorry, its hard to know what is advanced and what is not.
that's true.
thanks!
I want to draw the predicted path of a Rigidbody2D object, is there some way to get the position of it x frames in the future?
In general or for trajectory prediction?
In general, I think you can simulate it. Sounds like pain, never done it. This looks like the way I've heard it can be done: https://austin-mackrell.medium.com/unity-trajectory-prediction-simulation-method-5b441ee1604
For trajectory, there are many tutorials on doing it in Unity. Just google "Unity trajectory prediction"
Hey, would really appreciate the help here:
Any idea on why the camera drifts upwards or towards the left or right depending on where you're moving?
https://codeshare.io/4em9qj
Willing to pay for this
Hey! What's an optimal way to sort a list by property in csharp/unity?
LINQ is one nice way to do it
@soft hollow can you post a video of it happening?
is your camera parented to anything else
and this is the only place your camera is referenced?
Sure thing, give me a second
Yes, the camera is inside the head bone
Yes
@granite viper
@soft hollow you're rotating your camera using a LookAt -- I don't know how m_headTarget is set, but I'm guessing it's probably a word position
so as you move your body the camera is continuing to LookAt m_headTarget
oh nevermind, it's a Transform
so yah, if headTarget is a transform in the world it'll just keep looking at it
you're also moving the camera before updating the headTarget position
What can I do to fix the drifting then? @granite viper
don't do what you're doing lol
try moving the LookAt after you update the headTarget position
but that's not how I'd do a first person camera
Yes, sorry, I mean what are my options for fixing it
I'd just set the camera rotation directly
What would happen with the IK then?
I haven't worked with IK before -- is that why you have a headTarget transform?
for the IK?
Yes
if headTarget is used for IK, then you should set the camera rotation and then set the headTarget from the rotation
rather than the other way around
That would still make the headtarget drift wouldn't it?
no?
the issue you're having isn't drift
it's the fact that the camera is looking at a fixed point in space
yeah -- the headtarget is a fixed point in space
Gotcha
I mean I could be interpreting your code somewhat incorrectly but I think my point still stands
having two things relying on each other for state is a bad idea
have your dependency hierarchy be camera -> headTarget -> head IK
rather than camera <-> headTarget -> head IK
first try moving the LookAt under the headTarget update function
++
Now it just spins around like crazy lol
question about dealing with generic types. I've got a class Conditional<T> where T is whatever value type of I pass into it that return a bool. I have a single list of these of various Conditional types (via a common interface, IConditional); I also have a list of another interface, ICriteria, which can be of any implementing type. What I want to do is take the list of ICriteria for loop through it, submitting each one to any IConditional of the matching type. The attached code breaks because "Conditional<criterion.GetType()>" doesn't seem to evaluate properly.
Conditional<criterion.GetType()>
This is indeed not possible, because generics are checked at compile time. They are constant, this is a variable.
What you pass in there cannot change
The only way you can do this if you add the T in Value.
Value<T>(List<ICriteria> criteria)
You'll notice that then you could also pass in a Value<T>(List<Conditional<T> crit)
you need a non-generic base interface for Conditional that has a method or property that returns a Type
then implement that interface and property in your generic class and return typeof( T )
oh you already have an interface
so add it to IConditional
then you can do something like
foreach( IConditional condition in conditionals ) {
if( condition.type == criterion.GetType() ) {
// do your thing
}
}
Whats the thing then? You cant easily cast the IConditional to a Conditional<T> in that case.
Thats what he's trying to do, and thats impossible. You'd modify your interface to accept an object parameter?
you'd make a non-generic overload that takes the interface and cast it in the generic
I misunderstood your initial question, you are correct
he's already doing that since he's passing in ICriterion into Test in his snippet rather than the actual type
not the most efficient for hot code to have the boxing/unboxing but w/e
Hence, if its possible, make the Value<T>
yes that would be ideal
running into the casting issue now. Not sure I follow w/r/t Value<T>
This
thanks. Gimme a minute to try to decipher it 😛
for ex.
public int Value<T>( List<T> criteria) where T : ICreteria {
// etc.
foreach( T criterion in criteria ) {
foreach( var condition in conditionals ) {
if( condition.GetType() == typeof(Conditional<T>) ) {
pass &= condition.Test( criterion );
}
}
}
}
if you don't know what value T should be at your calling site then you're out of luck
and you'll need to do my version
There's a newer syntax which is kinda nice
if(condition is Conditional<T> conditionalT)
makes a new variable immediately for it
yeah good tip, I missed the cast in my snippet
I feel like it would almost be saner to just test for the specific Types that might otherwise implement ICriteria
Is there a way to scope VS to include the packages folder in unity so I can get better syntax highlighting/error checking?
is that the way to add something on the player loop right ?
var loop = PlayerLoop.GetCurrentPlayerLoop();
for (int i = 0; i < loop.subSystemList.Length; ++i)
{
if (loop.subSystemList[i].type == typeof(FixedUpdate))
{
loop.subSystemList[i].updateDelegate += LoadScene;
break;
}
}
PlayerLoop.SetPlayerLoop(loop);```
hey i noticed that i can make script-changes in runtime without restarting the scene, which i usually cant do without errors because of object pooling or something. if im debugging externally and the debugger is set to pause and i edited the script, the debugger continues when i hit play, but the compiling of the script edits/changes happen after i stop the debugger and return to unity right?
Anyone know how to turn a .wav byte array into an AudioClip before?
I am trying to make an asset that blocks the main thread to not do so, but cause i may be behind a bit on things i wanted to ask my fellow programmers on their thoughts
Currently im just thinking of converting that asset to use ValueTasks to offset the load and let it do what it needs in the main thread when it needs to do so, but what are your thoughts? am i over complicating this perhaps?
I figured out what my issue was, my asemdef was incorrectly set up. VS recognizes the code if only the Any Platform box is checked. having any others made VS stop recognizing it. There's probably something I could have changed in VS to fix it but this'll work for now
Yeah that would be my goto but was wondering if there was an efficient way, cause I heard LINQ is not optimal?
https://docs.unity3d.com/ScriptReference/AudioClip.Create.html like described here?
yes
Any one knows the difference between GL.IssuePluginEvent and CommandBuffer.IssuePluginEvent ?
Under my testing, both of them can trigger native rendering event, but it seems the native event are triggered in different time. I could not find any documentation describe the difference...
// Option 1:
GL.IssuePluginEvent(getRenderEventFunc(), 0);
// Option 2
CommandBuffer cmd = new CommandBuffer();
cmd.IssuePluginEvent(getRenderEventFunc(), 0);
UnityEngine.Graphics.ExecuteCommandBuffer(cmd);
It's supposed that Option 1 is equals to Option 2, but actually is not. I want to figure out why...
Commandbuffers usually are scheduled to the camera using cam.AddCommandBuffer
what is the benefit of IJobParallelFor with respect to standard Parallel.For?
IJobParallelFor is how you define a parallel job in UNity's job system
Parallel.For is a C# thing
that has nothing to do with Unity
I know. I mean both have similar approaches to execute independent procedures parallel
I have multi dim array with some calculation. Which one do you choose to handle it?
Jobs can be scheduled with other jobs as dependencies that are resolved efficiently. Also, jobs can be compiled with Burst.
IJobParallelFor uses Unity's job system. Parallel.For uses some internal C# thread pool. It won't take advantage of Unity's burst compilation or integrate with Unity's job system at all
with Burst, OK thanks
I would like to use it minimally without Burst. As I mentioned, there is a multi dim array, inside it, calculate some addition, multiplication, there are some if/conditions and finally store them in an array/list.
Is it suitable to use IJobParallelFor for this scenario?
Parallel.For(0,length,(i)=>{
//...
})
yeah that is likely burstable
Let me say, I have tested Parallel.For, it is disappointing in my scenario. I mean the execution time is worse
Array size 32*32*32
Parallel length 32
Maybe because the size is small.
Even with Partitioner
Hi ! I'm having a little problem, with some math on the calculation of a specific angle and would need some help on that if anyone around is Good with this.
Here is some code
private Vector2 mousePosition;
private Vector2 fromVector2M = new Vector2(0.5f, 1f);
private Vector2 centercircle = new Vector2(0.5f, 0.5f);
private Vector2 toVector2M;
And then in Update run this part :
mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
toVector2M = new Vector2(mousePosition.x / Screen.width, mousePosition.y / Screen.height);
float angle =
(Mathf.Atan2(fromVector2M.y - centercircle.y, fromVector2M.x - centercircle.x) -
Mathf.Atan2(toVector2M.y - centercircle.y, toVector2M.x - centercircle.x)) * Mathf.Rad2Deg;
if (angle < 0)
{
angle += 360;
}
CurentMenuItem = (int) Mathf.RoundToInt(angle / (360f / menuItems));
The issue is, it's not targetting well on X elements
Why would you want to avoid using Burst? It's literally just adding a [BurstCompile] attribute on the job struct.
OK, I test it, hopefully get better result.
I would like to know if it is useful for small 3d array size.
32 length array of (32*32)
it's useful for any array size
That depends on how much work you're doing for each element. There is some small overhead with both scheduling jobs and using Parallel.For.
Also, there are 3*3*3 chunks for example. I run them using Task.Run for each.
Maybe, I should get rid of it too and use Job for it as well.
My game is voxel based.
Each chunk has size 32*32*32
true, but you can easily just manually 'batch' it
For Jobs especially, you may need to convert the data to a NativeArray if it isn't already prepared that way.
But you'll definitely get better performance with Jobs and Burst than manual threading or Parallel.For.
Assuming you adapt your data structures to it
So, it is weird why my code with Parallel.For was worse or at least the same result
before going with Jobs or Parallel, you need to decide first on what youre going to do. both do the job, but which is efficient can be done by only testing it.
Jobs might be faster to process, but might also be slow on allocation. because it depends on where you get your array from. if youre using Parallel, you have the freedom to continue using the managed array which is already allocated. so just profile them both if your code has a tight budget
@sage radish So worth to test, thanks.
@drifting galleon thanks
@tough tulip thanks
@sly grove thanks
you don't necessarily have to reallocate anything for jobs. often you can just take the managed array and reinterpret the memory
depends on the use case yes.
NativeArray constructor takes a managed array. allocates native buffer, and copies the managed array to native array
Main problem.
Generate mesh for voxels 🙂
easily doable with jobs
is this for big macroscopic voxels minecraft style?
have you been implementing something from the literature? i forget, you've been asking about this for a while right
what is your objective?
it really depends what's in the //... part
take a look at UniTask, it has a way to do this
ExecuteCommandBuffer is synchronous with camera rendering and supports batching
huh?
don't use Conditional<T>, use
interface ICondition {
bool Evaluate(IContext context);
}
class ComparisonCondition : ICondition {
ArithmeticOperator operator;
IValue leftOperand;
IValue rightOperand;
bool Evaluate(IContext context) {
var left = leftOperand?.GetFloatValue(context) ?? context.leftOperand.GetFloatValue(context);
var right = rightOperand?.GetFloatValue(context) ?? context.rightOperand.GetFloatValue(context);
switch (operator) {
case ArithmeticOperator.GreaterThan:
return left > right;
...
}
}
}
does this make sense?
context can be "current value" instead of left and right operand
don't use generics
class ComparisonCondition : ICondition {
ArithmeticOperator operator;
IValue leftOperand;
IValue rightOperand;
bool Evaluate(IContext context) {
var left = leftOperand?.GetFloatValue(context)
?? context.currentValue.GetFloatValue(context);
var right = rightOperand?.GetFloatValue(context)
?? context.currentValue.GetFloatValue(context);
switch (operator) {
case ArithmeticOperator.GreaterThan:
return left > right;
...
}
}
}
another way of thinking about it
do not write a signature into Evaluate
add fields to a "context" that can be interpreted however you need by conditions
or whatever little meta-programming thing you're trying to do
if i were you i would avoid metaprogramming at all and directly script
So - the background here is that I want to award the player "Action Points" that can be used in specific circumstance: IE, 1 Action Point to use in North America only; or 1 Action Point to use on a Diplomatic Action; or 1 Point to use on a Territory where the opponent has at least 1 point. I want to do this generally rather than code up each card. So the question is, how can I submit the context of some spending of those action points to evaluate if this point is eligible for that purpose.
var greaterThanFive = new ComparisonCondition() {
rightOperand = new ConstValue(5),
operator = ArithemticOperator.GreaterThan
};
...
i get what you are going for and you're modeling it poorly 😦
OK. I don't think I have an intuitive high-level understanding of the initial code you posted, could you kind of describe what's going on there?
Hey @granite viper
you can use
class CustomIsPlayable : ICondition {
bool Evaluate(IContext context) {
var currentAction = context.currentAction;
if (currentAction == null) {
return false;
}
return currentAction.target.region == Regions.NORTH_AMERICA
|| currentAction.type == ActionTypes.DIPLOMATIC
|| context.GetScoreFor(Players.OPPONENT, currentAction.target.territory) >= 1;
}
}
im asking what would be the best way to get started with converting a sequenced code into a parallel one
but i am having some trouble to see if there is a better way to do so
like per example, atm i used ValueTask to try and leave the main thread free
OK. What this seems to be getting at is that instead of submitting Type <T> into the Evaluate() function as I did with test, but to instead pass in an IContext; this gets away from the generic typing altogether.
part 2:
bool CanPlay(IContext context, Action action) {
var toEval = context.Clone();
toEval.currentAction = action;
return toEval.GetAllApplicableConditions(action)
.All(condition => condition.Evaluate(toEval))
&& action.cost > context.currentActionPoints;
}
you don't need generics because you don't need to express any comparisons except between floats
a float is a superset of everything you would want to compare
so no point in making it generic
part 2 could be made simpler if you put the code where you need it to be so to speak
it's easier to enumerate through lists of enums in the right places
than to have a general crappy-version-of-LISP thing going on
does that make sense?
Uhh I wish I could say it did. Not sure how a list of enums enters into play here?
suppose this card was titled "The Imperialist: Gain a free action in North America; or a free diplomatic action; or in any territory where your opponent has at least 1 point"
bool CanPlay(IContext context, Action currentAction) {
EnchantmentEnum[] enchantments = context.GetAllActionEnchantments();
// check cost, do a bunch of stuff
return enchantments.All(e => {
switch (e) {
case EnchantmentEnum.THE_IMPERIALIST:
return !context.GetPlayerHasEnchantment(Players.FRIENDLY, EnchantmentEnum.SPENT_THE_IMPERALIST) &&
(currentAction.target.region == Regions.NORTH_AMERICA
|| currentAction.type == ActionTypes.DIPLOMATIC
|| context.GetScoreFor(Players.OPPONENT, currentAction.target.territory)) >= 1
...
}
});
}
then the code for The Imperialist would be
var theImperalist = new Card() {
title = "The Imperalist",
description = "At the start of every turn, gain a free action in North America; or a free diplomatic action; or in any territory where your opponent has at least 1 point",
cost = 1,
friendlyActionEnchantments = new [] {EnchantmentEnum.THE_IMPERALIST}
};
which can be encoded directly in a scriptable object
so when something is complicated, don't make a metaprogramming thing. just declare an enum, and check for it in the right places @golden saddle
in this implementation The Imperialist would need to put another enchantment into play indicating it was spent this turn
alternatively you can create an enchantment token tracker if this is a common thing you do in your game
I think I can un-genericize the code and move on from that approach, but shifting everything into scriptable objects with enums is probably too big of an overhaul for the scope of the project right now.
it can be whatever you need it to be
not a scriptable object
but more like, don't inject code
coordinate around an enum
that corresponds to the effect
this thing that you are doing, this particular card, it's really hard to do
there's a lot that would go into its implementation and you are not going to make something bug free via meta programming
it's a really complicated card lol
I'm doing implementations of the board games Twilight Struggle and Imperial Struggle, just FYI. Picking them because they are hard 😛
hobby projects. but hopefully one day soon.
is this the first time you've tried to make this kind of game?
sort of. Each time I start I run into some basic architecture problem, then I restart using the lessons from the last attempt. So this is maybe evolution #5.
lol
good good
you are on a good journey
have you looked at the source to XMage?
Finger's X'd. Those games have a reputation for being "difficult" so I figured if I can figure those out, I can figure out any type of turn-based game.
I have not seen or heard of Xmage
okay
https://github.com/magefree/mage/blob/master/Mage.Sets/src/mage/cards/u/UktabiKong.java @golden saddle here's an example
this is really complicated
Need some help with importing a native unity plugin
I get this error
Failed to load 'Assets/Plugins/Native/Utilities/download_file.dll' with error 'The specified module could not be found.
despite the fact my dll exists right where it says it does
usage:
private const string DownloadFileLibrary = "download_file";
[DllImport(DownloadFileLibrary, EntryPoint = "download_file")]
private static extern Memory DownloadFileRaw([MarshalAs(UnmanagedType.LPStr)] string url);
[DllImport(DownloadFileLibrary, EntryPoint = "free_memory")]
private static extern void FreeMemory(Memory mem);
[DllImport(DownloadFileLibrary, EntryPoint = "download_file_async")]
private static extern ThreadedTaskMemory* DownloadFileAsync([MarshalAs(UnmanagedType.LPStr)] string url);
[DllImport(DownloadFileLibrary, EntryPoint = "free_threaded_task_memory")]
private static extern void FreeThreadedTaskMemory(ThreadedTaskMemory* task);
here is the code for the .dll
the .dll is only targeting the editor
also, I have to use unity 5.6.3 unfortunatly
thank you!
you forgot to add .dll to the dllimport,
why do you HAVE to use 5.6.3???
oof
Adding the .dll produces the same results unfortunately
It’s worse than “oof”
....not modding the game is always an option XD
XD
oh, uhm, you have not added the absolute path to your file
you have to specify the search directory
tried that
private const string DownloadFileLibrary = "Assets/Plugins/Native/Utilities/libdownloadfile.dll";
[DllImport(DownloadFileLibrary, EntryPoint = "download_file")]
private static extern Memory DownloadFileRaw([MarshalAs(UnmanagedType.LPStr)] string url);
[DllImport(DownloadFileLibrary, EntryPoint = "free_memory")]
private static extern void FreeMemory(Memory mem);
[DllImport(DownloadFileLibrary, EntryPoint = "download_file_async")]
private static extern ThreadedTaskMemory* DownloadFileAsync([MarshalAs(UnmanagedType.LPStr)] string url);
[DllImport(DownloadFileLibrary, EntryPoint = "free_threaded_task_memory")]
private static extern void FreeThreadedTaskMemory(ThreadedTaskMemory* task);
didnt work
you need to specify an ABSOLUTE path
Application.dataPath might be the correct one, but i'm not entirely certain. would have to look it up to be certain
aaaa
there's also this if you have a lot of DllImports: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.defaultdllimportsearchpathsattribute?view=net-6.0
cant use it cause it aint const 😦
MSDN is always based
i think this is impossible then
I moved the dll to a path which is relitive to the script
would that work?
Hey, did anyone ever work with GoogleSheetsAPI on Android?
you're going to spend a lot of time wheedling on authorization to do that
it's telling you what the error is
but the dll is right there
bruh
they are tho
i literally copied and pasted
have you tried closing and reopening the editor?
yes
?
I can't figure it out, thats why im asking lol
Yeah thats my issue just getting through the credential process with GoogleCertificate.
removing the .dll and the path gives me 2 new errrs
The problem is that I cant find any working examples of reading the credentials.json on Android, no matter its location
why do you need to access a google sheet from a game?
I'm using Playfab to store the upgrade levels for each gun in my arsenal to a player's cloud account. The player can select 2 weapons, a primary and secondary to take into a battle. When they enter the battle i need to know how much damage the weapons should do and how much fire rate, etc, based on the upgraded amount for each stat of both guns.
What is the most efficient way to do this. Obviously im not going to make an api call every time the player switches weapons to grab the levels for each stat of the selected gun, but what is better than that. All i can think of is setting 8 variables on awake in my game manager script that correlate to the 4 stats of each weapon, and then every time i switch guns i have to have a flag that says whether the player is switching to primary or secondary gun and set the new stats based on that. But this seems super inefficient as far as clean code.
Is there a way to make like 3 objects or something with 4 stats that return the damage, fire rate, reload speed, and mag size and i can set 2 objects to be primary stats and secondary stats, and just switch either object in for the 3rd object that would be current gun stats? I think this would be cleaner but not sure how to implement that. I was told its a bad idea to store data in a scriptable objects but that might have just been for long term data storage
Okay so if its okay to manipulate data in a scriptable object, what if i simply add 4 variables to my scriptable object for each gun which hold the 4 stats to use and dont touch them outside of the Game Scene, but on start of a new game, i set the 4 variables equal to the base stats plus whatever level the stat has been upgraded to? Would that work or is this bad practice and i shouldnt be manipulating scriptable objects on start of every new game
yeah that would work fine
if its just readonly
it wouldnt be too slow
Awesome I'll try that out. If im just setting them via code and not in the editor, should i make them private variables?
been a while since i took a class in college on OOP. oops
OOPs
figured out the issue
my libnrary was linking with libcurl
but i was dynamically linking
not static
create a single object that describes the entire User data that should be stored / fetched from the server
retrieve it when your user has logged in. keep it updated whenever your client changes it
@wispy epoch use UniRx to make this easier on yourself
ReactiveProperty<User> m_User = new ReactiveProperty<User>();
IReadOnlyReactiveProperty<User> user { get; }
void SetUser(User user) { m_User.SetValueAndForceNotify(user); }
// whenever you need to keep the UI updated
user.SelectMany(u => u.weapons)
.Subscribe(weapons => {
// update the weapons UI here
})
.AddTo(this);
// whenever you need to change something
var userDoc = user.Value;
userDoc.weapons[2].level = 3;
SetUser(userDoc);
// to set up saving automatically to play fab whenever you modify data
user.Subscribe(async u => {
await playFabApi.SaveDocument( u /** or whatever .... **/);
})
.AddTo(this);
// get the initial data
var userDoc = await playFabApi.GetUserDocumentOrWhateverTheApiIs();
m_User.SetValueAndForceNotify(userDoc);
does this make sense?
no scriptable objects
they don't make sense
just have one object represent the entire thing you need
if you need to scriptable object that garbage do
class MyScriptableObject : ScriptableObject {
public User user;
}
and declare User [Serializable]
this is what my playfab data currently looks like and im just grabbing the levels when the player opens the inspect window for that gun, and changing the levels for that gun if the user completes an upgrade purchase. You're saying i should have all the data present in the playfab data but isnt this inefficient because the base damage and damage increment and icon and so on all are specific to each gun but unchanging
it'll be way too clunky to do this
your player data should just be 1 key and the value should be the entire user document
that seems more clunky and hard to read to me than what im currently doing
you're already experiencing the clunk
there's no value in optimizing 50 bytes versus 5,000 or whatever
it will never matter
if that stuff mattered to you you wouldn't use JSON
you are getting a huge amount of clunk from having all these keys
and then you will eventually have a different type in there
and you'll have to keep track of the type
it's meaningless
this is coming from someone who's written multiplayer games
the pattern i showed is bulletproof - you'll always have the latest values locally and saved on the server in all but the buggiest cases
you already made a big mistake by using scriptable objects as something you also change in the game
if i understood correctly
you need 1 object (or a collection of them) representing your game state when you make networked games
well no i havent been manipulating the data in my scriptable objects up until this point. Thats my question is im trying to figure out the easiest way to get the levels from playfab when you start up a game, for the 2 guns equipped, and it all seems very clunky bo matter what method i go with
so it goes. model your game as 1 object (or a collection of identically typed objects)
the data in my scriptable objects is constant but there's s a lot of it for each weapon. about 12 variables
Hey ive seen this problem before and not sure what i did to fix it, i think switching to URP, but when the player moves quickly and enemies are following also going at decent rate of speed, when the camera is following the player, the enemies become blurry. The blur goes away when the player stops moving.
Now this is the same game i had the original problem with but URP made it go away in the editor as well as on my 4 test devices, (3 models of iphones and 1 android). I thought the problem was fixed but now im getting reports from one of my beta testers that the issue is happening for them as well. This is 1 user out of 20 and they are using a 22. Why could this be? I asked if this was an issue broadly for the model of phone they are using (brand new) and they said this is the only game they see it happening for but maybe other games aren't using the same visuals where enemies chase after the player? I doubt it but it seems like a rendering issue in game, just dont know why it would only be happening for this user.
For extra context this user is the only android user ive sent the build too. Ive tested it personally on my android test device but this is the only tester its gone out to on the platform
We are doing levelTesting and we want to stream data from it at runtime with this for further adjustments.
Can't you just put it in resources?
Also, why not use the oauth api instead and let the user sign in with their own id that has access to the file
ServiceAccount auth isn't really for apps, it's for headless services that run on e.g. your build machine
I've tried putting it in resources, but a new error arises where the constructor for the GoogleCertificate is not found. We don't want to use OAUTH api, since we are developing mobile and we don't want testers to deal with that.
That sounds like you didn't include all dependencies
https://answers.unity.com/questions/1778812/googleapiexception-parameter-spreadsheetid-is-miss.html
This was the error iirc, I didn't want to go as far as link.xml since then I need a seperate system to strip it from release builds, etc.
I was actually hoping that this would work out of the box. Supposedly this person: https://github.com/UnityAdventureES/GoogleSheets-For-Unity/blob/main/GoogleSheetsForUnity.cs made it work
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Idk, sounds like they would still need a link.xml or something basd on that repo
To be honest I could just do it via GET/POST requests, but I really wanted to use the api for this. Makes it a whole lot less clunky...
How could DateTime.Now.ToLocalTime().ToString() become 4/3/2022 8:31:39 a. m. ? I've never seen a space in-between a. and m. like this before and I can't parse the the string back into a DateTime correctly because of this
DateTime.Now.ToLocalTime().ToString("dddd, dd MMMM yyyy")
Did you try with any of these https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1?
Yeah, in retrospect, I should've specified the format >< Thanks
How could DateTime.Now.ToLocalTime().ToString() become 4/3/2022 8:31:39 a. m. ? I've never seen a space in-between a. and m. like this before and I can't parse the the string back into a DateTime correctly because of this
turns out that systems with Spanish localization like to doa. m.at least I know the problem now
Hello,
I am setting up a CI/CD pipeline with TeamCity for a unity project to automating build.
When I make a build, it fails with an error that UnityShaderCompiler could not connect ipc like below.
"Shader compiler initialization error: Failed to get ipc connection from UnityShaderCompiler.exe shader compiler! C:/Program Files/Unity/Hub/Editor/2021.1.7f1/Editor/Data/Tools/UnityShaderCompiler.exe"
could somebody please tell, what can be a solution for this ?
Could be a firewall problem. Have you see any administrator popup appear on the build server?
Actually, it seems this error occurs when the build agent is run as a service.
https://forum.unity.com/threads/solved-failed-to-get-socket-connection-from-unityshadercompiler-exe-shader-compiler-on-teamcity.476421/
Hi guys! Anyone knows how to run pod install in a c# script?
maybe this is more of a question for here: #archived-code-general message
Just destroy your player and recreate it based on the latest save data?
ah interesting idea, I don't use any saves (apart from a leaderboard) but I could reinstantiate a prefab
thanks
Thank you @sage radish . I increased the windows desktop heap size limit for the pc. and after restart it was able to make a successful build. For now this seems to be working well.
I will keep this link saved for future in case it happens again.
Anyone used to work with Wwise ?
On a project, i can't get the sounds to play with Wwise on Unity, note that the integration has been made by a sound designer, so it should be fine.... but sadly when i play the event it's saying that the sound doesn't exist, and that i should check my settings, thing i have done already 10 times but still no clue about how to make it work on my end without downloading Wwise