#archived-code-advanced
1 messages · Page 36 of 1
Oh genius
Define the offset inside the feature and pass the reference in the constructor
I got it, thank you @sage radish
Sync enabling/disabling a game object via a bool with the client and the server
Aka multiplayer code
why did you get rid of the event subscription stuff
Wasn't the tutorial just changing colors?
All you had to do was change the Model from using a color to a bool, and then change the "change color" method to enable/disable the object from the new value
you should not have removed the whole event subscription paradigm
I tried this, but I got an error when trying to subscribe/unsubscribe events
what error
I’ll try to recreate the error give me a minute
I’m in a different device right now
If I recall your original error from two days ago it was you were trying to do += on a bool
Yeah it was that
which meant instead of just changing the type of event you were using
you deleted the event
and had a plain bool variable
which... doesn't make any sense to have done
Yeah you’re right
I’m going to retry this since I’ve learned a bit from my errors
i didnt mean to type that here
yes but what is the game
Like the genre/story?
"it's a casual environment to walk around in multiplayer in vr"
oh sorry
or "it's an RTS with three asymmetric factions" <- that's starcraft
"Short single player horror story game"
making what multiplayer? a pre-existing game?
There will be singleplayer and multiplayer options
and it works fine I can connect and either be by myself or with another player
i see you're making Deafening Pines multiplayer?
Yes
i mean real people not discord people
Give me a minute
Oh I fixed it
My mistake was wrong on my end
I had it right the first time but I forgot to put this
I'm having a hell of a time trying to make async/await work in WebGL - would appreciate any pointers.
I have a large piece of code that uses async/await.
When I call it in the editor or standalone builds, it works fine.
In WebGL builds, it gets stuck after one async function returns - it never continues executing.
My best guess is that somehow, there's a deadlock in Unity's WebGL single threaded code..?
Any thoughts on how to continue debugging this?
For additional, but probably not useful, information, I'm using the Nethereum SDK with a custom Interceptor to make requests thru my own code.
Here's the line of code where I never see any logs past in its execution chain: https://github.com/0xsequence/web3-unity-sdk/blob/2551b3c0c5de67fad4908b7e97ef4164cd9fd28f/Assets/SequenceSDK/SequenceSharp/Scripts/SequenceNethereum/WalletConnector/SequenceInterceptor.cs#L22
I've tried switching all my code to UniTask (except that code that needs to satisfy Nethereum's pre-existing Task interfaces), but it didn't help.
ayo wtf i think i fixed it by removing all my .ConfigureAwait(false)
what is your goal?
you should use unitask for async/await in unity
can i ask you some frank questions about skyweaver?
I got a horrible issue. Trying to send some byte arrays to google plays cloud, but I get some warning saying it's bytes are obselete? That I need to use sbytes instead? Could anyone help?
This is what I am trying to send. PlayerData is a class with some integers and a list.
why not show the line that is showing the warning?
yeah, sure! 😁
i did not end up fixing it, lol
Sure! I used build and run on my phone, with profiling.
i tried converting all my code to unitask, but Nethereum itself has an interface that returns an async Task, and that's one i can't convert to unitask :/ and that's also where it's hanging
this is a red herring
What does that mean exactly?
this line where you are saying it hangs
await web3.Eth.Accounts.SendRequestAsync()
from https://github.com/0xsequence/web3-unity-sdk/blob/2551b3c0c5de67fad4908b7e97ef4164cd9fd28f/Assets/SequenceSDK/SequenceSharp/Scripts/SequenceNethereum/WalletConnector/SequenceInterceptor.cs#L22
does it use UnityWebRequest as the underlying transport?
and that's where my async tasks stop running
i mean.. i guess i could fork nethereum and try a unitask-only version, lol
can you show me where it uses UnityWebRequest?
it doesn't
but can you show me where you think it does?
it clearly uses HttpClient which doesn't work in webgl
oh, sorry - I'm not actually using unitywebrequest or HttpClient.
await web3.Eth.Accounts.SendRequestAsync()
is intercepted by my SequenceInterceptor, before it gets into the native Nethereum provider code.
This lands here,
if (request.Method == ApiMethods.eth_accounts.ToString())
{
var addr = await _wallet.GetAddress().ConfigureAwait(false);
return new string[] { addr };
}
which calls into the Wallet class here:
return ExecuteSequenceJSAndParseJSON<string>("return seq.getWallet().getSigner().getAddress();");
it intercepts the calls that Nethereum would have made and lets me override them with my own logic
do you see those calls?
yes, i see the calls.
what is a web3.Eth.Accounts? It's not an HttpClient?
It's a class that will end up calling the Inteceptor that i've made
i'm 100% sure it's getting called, sec
else if (request.Method == ApiMethods.eth_accounts.ToString())
{
Debug.Log("Getting address!");
var addr = await _wallet.GetAddress();
Debug.Log("got address!" + addr);
return new string[] { addr };
}
there's the log from the interceptor
but i never hit this log
so the problem is that somehow, the SendRequestAsync() is bailing... but...
you make a good point - maybe for some reason, or some how, it's trying to use an HttpClient, even though I have the interceptor
and i have to signal that the interception is successfull, or something
it's a good thought, i'll look into it
like the .eth.accounts?
i didn't clone the repo
what is it?
what is its type?
it says got address, so it's working?
you wouldn't be in so much jeopardy as to swallow exceptions
your interceptor is working fine
but from what i know about programming, when something is named an interceptor
it intercepts
it doesn't replace
it says got address, but never logs "extension success"
so that async function is never finishing
well
but yeah - i imagine if i called into an httpclient it could bail like that
my guess is that it is running your interceptor, clearly
👍
i'm just asking what the type is lol
what is it?
what is an Accounts object? you didn't name the class
what is its name?
pulling it up
okay
does RestEasy / HTTPClient / something like that implement an IClient?
i don't know what generates json rpc client stubs*
usually people who are using json rpc have no idea what they're doing 👀 sorry nethereum guys
yeah im looking for the actual requestor
the eth wallet communication protocol is json rpc lolll
yeaaah okay i see lots of stuff about http clients
that seems like it's most likely it
okay
i will do some more debugging, but really really appreciate it
gotchyu
:)
btw happy to answer skyweaver questions, tho u should probably dm so we don't clog the channels!
lol
it's okay
i just went to the website and was flabbergasted by the headcount
i too once worked on a virtual slot machine
but even then that was like 3 people
ah 😅 yeah, big team, but we make a live service videogame, a web wallet, a whole backend stack that indexes multiple evm chains, a smart contract wallet backend for our web wallet, a meta transaction relayer, a SFT token marketplace with a smart contract backend, a dashboard for people to work with those tools...
a lot more than just a game :)
well eventually your bosses will have to reckon with when the coin tosses on the opposite face
we actually have like 70+ people at the company now 😅
hahahaha
as far as i know the game itself is nowhere near profitable :P
😂
it's a fun tcg though 😁 probably my 2nd favorite aside from MTG
lotta strategic depth & cool deckbuilding
really proud of the work we've put into it, the core gameplay is way more than a slot machine
did some more digging - the interceptor does, in fact, replace the original httpclient stuff, so i'm not calling into any httpclient stuff. I do see a ConfigureAwait(false) which i'm worried might be doing some funky shit, mostly because i stilll don't really understand how that works
okay. usually i do not configureawait.
you shouldn't need to do it, provided you never do Task.Run anywhere
yeah - nethereum does it internally, and i'm scared that's what's breaking it 😂
if anything, it should be ConfigureAwait(true)
yeah i agree
context seems important here
welp
i'm pretty stuck 😓
gotta figure out how to attach a debugger to my wasm at this point
the unitask synchronization context is much better written than the default unity one
so in principle
i will see if i can finagle nethereum to work with unitask
await X() on a unitask-run async method (e.g. via UniTask.Void(async () => ...) or by simply calling Method().Forget() on a method Method that returns UniTask)
will have the best results on webgl
there shouldn't be any other synchronization contexts, so in my opinion you will probably get no change
there is probably a bug with how nethereum handles interceptors, or it expects you to call like .Next() on something
to signal that the next interceptor should be called
even if it appears to correctly replace the httpclient code, it may be that you are actually not signaling correctly that the interceptor is done
so it only appears that none of the httpclient stuff is called
rather than waste your time dealing with webgl, you should be able to step through and see this directly in the editor
maybe with a dummy interceptor, to ensure that you have used the api correctly
oh yeah, and see if the httpclient stuff gets called
fwiw this all works perfectly in-editor
but yeah
yep, same interceptor
also works on standalone builds for desktop, ios, android
it's only webgl builds that break here
hmmh, I wonder if there is common android bug in recent unity versions, we are seeing similar crash stack traces with 5% of android users after updating 2020.3.17 -> 2020.3.41
In the post another guy has tried 2020 and 2022 and one reply is with 2021
https://stackoverflow.com/questions/74543651/android-application-crashes-after-migrating-unity-2019-2021
okay I guess its this one https://issuetracker.unity3d.com/issues/freeze-slash-crash-on-memoryprofilerstats-unregisterobject-when-downloadhandlertexture-is-used-and-texture2d-is-already-destroyed
Reproduction steps: 1. Open the attached project “ReproProject” 2. Open the “SampleScene” Scene 3. Enter the Play mode 4. Wait a few...
you're in a much better place to debug this in your editor than i am, i haven't cloned the repo 😦
it is really painful to step through in webgl. i believe it all still works if you build to asm.js
i don't recall if debugging the wasm target ever really worked
or if it works now
it is likely you are running into a unity bug
unfortunately
Hi people! Does having empty game objects, with script components and UI Documents attached to them, handing only Awake() and Input System callbacks, costs performances?
I mean, if the scripts don't handle any kind of Update, are they still eating CPU time or count as idle?
It's better than having an empty Update method, but nothing is free in that sense
You probably don't have to worry about it though
I see. I don't know how the messaging works under the hood and the little I read online is not enlightening yet, and I was thinking if it's better to try to widen the responsibilities in order to have less scripts around, when possible, or if it doesn't matter
If you don't need the event method, don't add it to the script
iirc unity caches the event methods on the Component the first time it "looks" at the object, and then uses that cache to lookup if is has the event message
Pretty sure that's all handled on the c++ side though
Sounds nice. Thanks
Btw, do you have a reference to lookup if I want to learn more about this?
Not really, sorry. Pretty sure you can out more about if you google
Like I mentioned, it's also probably not something you need to worry about. Implement the logic you need, then test for performance
This sounds a little bit like premature optimization, but it depends on what you are doing
Sure, thanks for the hints!
Just trying to figure out a clean way to work with input system actually
I don't like the "delete this stuff and add that other stuff" to handle navigation as it's shown in several tutorials out there
I was thinking about using a game object for every part of screen and just toggling the display style or something
But thay means that I'll end up with a prefab with hell knows how many gameobjects and attached scripts standing there and doing almost nothing for the majority of time
Unless there are a huge amount of them I wouldn't worry about it unless you have very tight performance requirements
If your prefabs have a very large amount of scripts on them, I would think about pooling them to avoid the large amount of allocations each time you instantiate one
But again, it's impossible to say without actually profiling it
Performance is not an issue for now and I don't want to do premature optimization, just trying to avoid issues before they become annoying to solve
Thank you for the insights!
how important to you is it that this works
Hey guys, getting a little bit of an issue with my player movement. It seems that whenever I move my character to the right or backwards, my player seems to slide. Even if it stop pressing buttons, it keeps moving. I am assuming it has something to do partially with the relation to the camera, but not too sure how to go about fixing it.
void HandleMovement()
{
movementDirection = (cameraObject.right * movementInput[0]) + (cameraObject.forward * movementInput[1]);
movementDirection.Normalize();
//movementDirection.y = 0f;
//Note that movementVelocity = movementDirection * respective scalar (handled within state machine)
characterController.Move(movementVelocity * Time.deltaTime);
}
100% important, it's necessary, or i have to rewrite all of nethereum myself
definitely not. Stick to the single responsibility principle.
Isn’t that because of velocity? I would think that’s the case
Player movement is relatively simple, there are some extremely thorough tutorials online on both rigidbody and character controller movement, check them out
hi, i want to create a hash from a string that might be around 100KB.... any idea which is the fastest or the most appropiate method for unity and mobile?
the reason is for my saving functions i save different fields, and from save to the next save some of them might have not changed, so i thought of keeping a hash of the last saved one to compare.... and if they have changed then i update, if they dont then i dont need to send an update to that field
There are many ways. I think I used MD5 for this in the past:
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=net-7.0
It's not guaranteed to avoid a collision, but I guess that's true of all hash functions.
thanks a lot, i found Hash128 in the unity api
Oh cool, didn't know about that
I won't tell you that
heheh+ç
Because I don't know
But there's more info here maybe? https://stackoverflow.com/questions/800685/which-cryptographic-hash-function-should-i-choose
If you don’t need what cryptographic hash functions provide, you can use non cryptographic hash functions instead which are generally faster.
Murmur3 is one I have heard people talk about, haven’t used it myself though.
But 100 KB is tiny, I wouldn’t worry too much about it unless you actually identify a performance issue due to it.
If the code is well written it should also be very easy to swap out the hash function and try different ones for performance
I think you need to question why you want do to this. Any hash function you implement will need to process the data so unless there is a really good reason, i.e. network or IO bandwidth, then I think this is unnecessary overkill
Hmm, so I have a Render Pass that actually modifies the camera's transform, however I'm also using Cinemachine and it seems to override my transform, my render pass only works if I set cinemachine to manual update, if I set it to all the other modes, it seems to always run after my render pass, which is not something I'd like to happen. However if I set the camera's transform just as I do inside my renderpass, but into a script inside a method subscribed to "beginCameraRendering" it works
How can I get my render pass to set the transform of the camera overriding the one set by cinemachine without cinemachine messing my stuff up ?
HAHAHAHAHA @undone coral I FIXED IT let's GOOO
instead of using an interceptor, I just made my own impl of the base class
:D
I basically need an equivalent implementation of OnBeginCameraRendering but inside a custom renderer feature
injecting at different render events doesn't seem to change anything, cinemachine's update is still executed after my feature finishes changing the transform, so I don't get my desired transform positions on my camera.
okay good
yes i really think it was Intercepting
and it worked in editor because... httpclient works in editor
i mean.. the code where it calls the interceptor clearly shows it's not intercepting, but i can't think of any other reason why it wouldn't have worked
maybe it did some funky task.run or httpclients shit yeah
yeah
i believe the highly surprising reason is that it is probably using one of the two C# dependency injection mechanisms
i am not super familiar with those
they exist though, and the pattern of the library matches how one of them works
that's omega cursed :D
I want to add some code on my phone game that i'd like not to be there on release builds for security
I know the clause #IF UNITY_EDITOR doesnt include in the build what's inside
is there any other clause i can make use of for this purpose?
Something that i can have enabled when I build in a certain way
and disabled and unreacheable when i build on another way?
maybe something like release mode?
https://docs.unity3d.com/Manual/PlatformDependentCompilation.html
you can also define your own symbols
so i can make my own clauses?
ohhhhh really nice
so I have a Render Pass that actually modifies the camera's transform
you can't do that
what are you trying to do?
what is the effect?
hello
Guys.. I let a version on Google Play which plays with ARCore, yet while it is on my phone - all working well, but the version from google play seems like freeze when enter in AR mode
maybe it is something related to camera persions or something.
Do You had this issue, and how did You solved it ?
if you created and installed an aab onto your phone, the thing you get on your device is almost exactly what you get from google play. only the signatures will be different. this is a complex problem to diagnose
i am installing it with Build and Run and it is working on my phone.
once I put it on Google Play - and istall it from there - it doesnt
well i think the first place you should start is looking at the logs @true solar
i don't think google play has anything to do with this. i think it's that you have a lot going on, and you don't know what the issue is yet
it is probably telling you somewhere
you just told me that the sun is shining. thanks for illuminating me with this eternal wisdom.
🥺
snapping the camera to pixels
aka pixel perfect camera inside a render feature
is the camera pointing orthonormally? e.g. its forward is vector3.forward or vector3.down or vector3.right ...
My friend is attempting to use unity and create a new 2D project but is given this error and is booted into safemode to fix the script for the unity built in 2D package
Library\PackageCache\com.unity.2d.psdimporter@6.0.6\Editor\PSDPlugin\PDNWrapper\PDNDecodeJob.cs(17,16): error CS0246: The type or namespace name 'DecodeType' could not be found (are you missing a using directive or an assembly reference?)
I've tried and failed to help fix this, Removing PSDPlugin works but then 2D isnt available in gameobjects as it depends of it, Reinstalling the package also causes the same error
make sure all packages are updated to the latest "verified" version in the package manager (not newer, not older), remove all experimental features and delete the libary folder for good measure
Can some help me with the mess of my code https://gdl.space/yuzodoyeda.cs ? The main issue is that the gameobject moves between the tiles. Its a AI script which uses breadth-first search.
each tile in a hex grid has 6 neighbours, why does your direction array have 8?
I already tried changing it. It changed nothing.
i think it incorrectly generates the path. For example this goes from a tile to a different tile and back again, with the same problem above. It should need another tile so that it goes around that problem.
It also only happens sometimes. Its just really weird
you might find https://www.redblobgames.com/grids/hexagons/ helpful
I'd guess your coordinate definitions might be getting mixed up
that redblobgames link is literally the best primer on hex grids i have ever seen
also the trick of using Vector3Int coords makes working with them so so much easier
The dfs algorithm looks mostly ok although:
newDistance < distance[neighbor]) this feels to me like you're trying to read something before it's populated sometimes.
I would say your problem almost definitely lies in GetNeighbors
Do note that unity uses a pretty unusual cell coordinate system for hexes, I don't think it matches any of redblob's exactly
How do I know if my game can run on a 32-bit system?
Or is there specific code paradigms I need to follow so that it works on a 32-bit system?
do you mean windows 32 bit? android 32 bit?
windows 32-bit, my bad
the steam hardware survey shows <1% 32bit windows so it's not meaningful to support anymore
I have a default implementation for an interface, but I am not able to call the method on classes that implement the interface.
public interface IModify<T> {
public T Modify(Action<T> func) {
return func((T)this);
}
}
for the class
public class RetrievalSettings : IModify<RetrievalSettings> {
public bool defaultTags = false;
public bool autoInject = true;
public bool retrieveFromRoot = false;
public bool createInstance = true;
}
I should just be able to do
var setting = new RetrievalSettings().Modify((x) => {
x.defaultTags = true;
})
But Modify() is not showing up on available methods for RetrievalSettings...
You need to cast it to interfaces if you want to call default implementation
uhg, why would they design it like that...
Because classes don't inherit from interface
but it is default implementation, I just simply don't want to have to write
public T Modify(Func<T, T> func) {
return func((T)this);
}
a thousand times, and inheriting from a class is too much for such simple/generic functionality. C# is pretty stupid sometimes.
Here is the ugly workaround
public static class MyExtensions
{
public static T Modify<T>(this IModify<T> target, Action<T> action)
=> target.Modify(action);
}
Yeah, what I was trying to avoid.
Like the functionality is in C# just they desinged it poorly.
Some of them maybe, I can understand the reasoning tho
Not sure if you solved it but, but each row has different neighbours. see https://docs.unity3d.com/Manual/Tilemap-Hexagonal.html
e.g. one row has neighbors (-1, 0) (-1, 1) (0, 1) (1, 0) (0, -1) (-1, -1)
and another (-1, 0) (0, -1) (1, 1) (1, 0) (1, -1) (0, -1) . Using a combination of direction will give you false paths.
Does anybody know if the new awaitable keyword can be used for Unity's script lifecycle methods? Namely Awake, Start and such https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.html
Yes
Do you happen to know where they document this?
I tried looking into the changelogs but I can't find it there either
I don’t think there is documentation about the overall system yet
I didnt solve it. But i found a video about A* Pathfinding.
So im probably gonna use that
It's an 2d ortographic camera
hey, having some struggle with math.
i'm trying to figure out a google spreadsheet formula for the total cost of something, in this case skills.
ex.
level 1 of a skill costs 250 currency. next level costs 500 currency, then 750, then 1000 and so on...
how would i calculate the total amount spent for something like this?
"Max upg" is the maximum amount of times you can level up something
That would be base cost + (increase cost * levels)
Ah wait, no, the cost increases per level
the total spent is levels * base cost + (levels * (levels - 1)) / 2 * increase cost
Yep that's more like it
amazing, thanks you so much, this was giving me an headache
im trying to understand why its working, whats going on in (levels - 1)?
math ¯_(ツ)_/¯
sum of n integers is (n * (n + 1)) / 2 but the base cost means you only need to count to n-1
cool stuff, still trying to wrap my head around it but i sorta get it
will probably 100% click tomorrow when i look at it again lol
an intuitive way to understand the sum of integers is to consider, say, 1 + 2 + 3 + 4 + 5 + 6
then take one number from the front and one from the back, pair them up, and then take the next pair, etc, e.g, 1 and 6, 2 and 5, 3 and 4
each pair sums to the same value and in this case is 7, (or n + 1 where n = 6)
since we are taking two at a time, we only have 3 pairs of them, (or n/2 where n = 6)
so there's n/2 pairs of n+1, or n * (n + 1) / 2
it needs a little more thought to consider what happens when n is odd, and when it's not just +1 each time, but you can apply the same reasoning to deduce a formula for your scaling
What are you using facade for? Why do you need to call GetComponent and Initialize while you can directly inject into them?
Sure that's up to you
Point is loose coupling and inversion of control
If you bounded them with installer
You might wanna look into IInitializable as well
You can split them into IDamageModuleData etc
Then implement each interfaces from SpawnModuleData
If you want that kind of structure
Then you can bind and inject those interfaces to each module of yours
I mean it is slower but not like too slow to afraid about
you can change the projection matrix of the render context instead of changing hte camera transform
rendering is one way
render passes execute on a render thread. you shouldn't be modifying anything substantive about the scene in them
for this particular effect, i'm not sure why you're doing it as a render pass yet
it really depends what the goal is.
i'm sure there's something sophisticated going on
as someone who operates a pixel art game, and i've studied this a lot, i can help you
Through Menu UI, I would like to catalog different materials that I can make an object in the scene
Evening!
trying to load a new scene during runtime and the entire editor is crashing.
provided the log (took my name out n stuff) but i cant find a reason.
im using the ".net Framework" api compatibility level as i need full access to .net for the project.
any help would be great, thanks!
2022.2.1f1 is version
the code too:
public void PlaySelectedLevel(string lvlName){
DatabaseConnectionController.CloseConnection();
using (StreamWriter writer = new StreamWriter(Application.dataPath + "/ActiveLevelPackage/activeLevel.txt", false)){
writer.Write(lvlName);
writer.Close();
}
SceneManager.LoadScene("GameScene");
}
was initially using a static class to store the whole level, thought that was the problem so wrote the name to a text file instead and still not the problem
You don't need to close the writer since you're using using.
Potentially the freeze is from an infinite loop in a script in the new scene
Well is it crashing or freezing?
Try not to make it more complex than it should be. You can always pass extra arguments on DiContainer.Instantiate from factory
I can't seem to find a solution to these errors, I suddenly can't build anymore, even after undoing my latest changes to a state where I could build it before
In fact, I'm now building an empty scene by itself and it still gives me the same errors.
Rolled back away from 2023.1.0a24 to 2022.2.1f1, now works fine without issues
I thought you said it happened "all of a sudden"
Or did it happen when you upgraded unity?
Is it possible make a script that generates a bitmap texture and modifies it during runtime in Unity?
I was thinking being able to make some effects like this 6502 assembly effect I made. (to see it, copy and paste it's text into something like Easy6502 )
Hello. I was working on my 2D tactics game today. Each character has a Vector2 variable "Facing" that points at one of the XY cardinal directions. I am attempting to spawn an effect relative to the facing of the character, like having shields on their right and left. I resorted to building a quaternion and using it to rotate the relative vectors, but I am wondering how someone would be able to do it arithmetically, assuming a 2D plane.
Nevermind. I found some good information at https://answers.unity.com/questions/9919/how-do-i-create-a-texture-dynamically-in-unity.html and I got it working no problem!
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.
Hi, does anyone have experience with referral links? I can't find a nice solution for both iOS and android to reward a player by sharing it to his friends
You mean rewarding a player for sharing it to their friends?
I guess
You're looking for something that the current user can generate a URL, pass it to their friend, they browse to it, it goes to your server, marks the player id the referral came from, then redirects to the appropriate store (Google Play or iOS) right? The problem is that the install is entirely in the control of the user and the store, and nothing gets passed into it for your data, afaik, so it's really hard to incentivize referrals like that.
Incentivizing gifts to the players, though, is more likely. So...maybe your app registers a URL handler for your site (IIRC that's doable) and if the user hasn't installed your app, it goes to the store page for your app. If they have installed your app, the URL handler gets picked up, and it redirects into the app, in which case the URL parameters do get passed to your app. So the first time, folks are invited to install. The second time they click on it, it passes the data into your game, and you connect with the inviter. (Also include stuff like unique ids, server-checked duplicate detection, expiry times, etc., in the URL parameters, but that's table stakes.)
That's roughly how I would implement something like that, but there's a lot of unknowns in there...sorry.
Thanks for the answer, really appreciated
Does unity have an URL handler?
can't find it
So...I did this a while ago on macOS, and I think I had to write a (very small!) external method that I linked in and called from Unity code. Something like this https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app probably will help. I don't know if Android has something similar, but this: https://developer.android.com/training/app-links/deep-linking#adding-filters looks kind of like it.
some assets help you with that shit
at least the one from the app side
im using voxelbuster's one
and set up the universal links in less than 20 min client and server side
i recommend you to take a look to this
here they explain how to set theapple-app-site-association
Absolutely! The 'Deep Link Services' should work for that. I wrote it myself, because I am a masochist, but that's a great asset for this kind of thing.
some writen apple documentation around is deprecated and it made me waste of time
this is how it works now, let me know if you need help
i was coincidentially into that this week
That's the thing, I still built with v2023 before that and it worked fine
I got a Jobs question.
I have a set of jobs that I need to execute sequentially, this of course can be done by passing the jobHandle from one to another as a dependency. The issue is that for some jobs I need to use the results from one job to setup the data for the next. But I am not sure the best way to go about doing this. Any suggestions?
Can the setup between jobs also be done in a job, or does it need to be on the main thread?
Oh, you know what I think it could. But in case I come up with something that can't, and for future reference. Can you think of any alternative ways to do it?
I think that's always going to be difficult. The main thread has to be the one to check whether the job is done yet, so it becomes a question of how often you want to stop the main thread to check on the job status. If you know that the first couple of jobs finish pretty quickly, you could call .Complete() on it right after scheduling them so you can prepare the next data and schedule the next jobs.
So either you stall the main thread until it's complete by calling .Complete(), or you check if it's complete occasionally, which might mean it will take a while after the jobs finish before the main thread checks it and schedules the next one.
Yeah, my thinking was to check the jobHandle.IsCompleted in a component Update method
Is there a way to not recreate new color every time to change the alpha of an image object on Unity?
I have been trying to use pointers, but it doesn't seem to allow me to use the reference of the object color
colorPointer = &GetComponent<Image>().color;
idk if there is another more practical way to do it.
good evening everyone. i created a thread, if anyone is willing to take a look. i would be really grateful 🙏 "Through Menu UI ecc"
Hi, could someone recommend some resources to start learning how to make custom renderer features, and shaders?
no, creating a new one is the best way
and you generally don't use pointers in C# unless you are an advanced user doing something very specific (definitely not for something like this)
I just find it irritating to regenerate 4 variables each frame for multiples colors and wanted to see if there was a better way to do it on Unity.
make an extension method
Color is value type and will not allocate anything on heap
Thank you @gentle topaz and @jolly token !
Need help!
Somehow not a single collider works in my project and the "Edit Collider" Button is missing - how can i fix that?
?
I have an in-game debugging tool for reviewing content.. I can access this tool by collecting a keypress on the windows build. I'd like to have some sort of "secret" way to access this tool in the mobile builds.. Any nifty ideas?
Either some gesture like touch with 4 fingers
Or clickable mini label on the corner of screen
Yeah I might do something like 4 finger touch & hold
I didn't wanna mess with anything showing up in the UI if possible
I mean you are gonna disable the feature on release build right?
Yes (and I hope to not forget this) :p
Do #if DEBUG before forget 😄
oh, that's actually a good idea.. duh
Don't even need to make the gesture too obscure in that case - just single four finger click is enough, really
Probably
#if DEVELOPMENT_BUILD
if (Input.touches.Length == 4)
{
_sceneManager.GoToScene(SpaceGameSceneManager.SceneType.CutsceneReviewScene);
}
#endif
ezpz
i could probably even just whip up a debug menu with buttons for whatever debug tools the user wants to visit
hey guys i have a question on how to approach a thing. i am programming a sort of mining production chain game and i want to include workers in the mine (one worker per station).
Now i'd like to player to be able to buy workers.
You should press a button (i know how to do that, don't worry) and you get a worker with a random generated name and an attribute (for example: mining speed x2). all your bought workers should get added to a sort of workers inventory (a list) from where you can assign each worker to whatever mine you want.
I was wondering what i could use to generate random workers ranging from common (low multipliers for the mine) to rare (high multipliers) in a sort of inventory and how i could assign them.
I thought of scriptable objects but they are static and can't be randomly generated(right?)
https://docs.unity3d.com/ScriptReference/Random.Range.html
don't overcomplicate - try implementing it and if you get stuck post a more specific question with what you've tried and why it's not working how you want
And got another jobs question. I have a bunch of Splines/NativeSplines which I want to use in a job, the issue is that of course the NativeSplines each contain a NativeArray of Knots, and nested native collections is not allowed in Jobs. So, is there any solution besides just having a single job per spline? If not that is going to be pretty rough. I would have to do possibly 100s of jobs at a time.
I've built a weighted list library that you could use if you needed something optimal
thanks thats useful!
now the only thing i'd need how to make a list. i can use the libraby to assign rarity to stats. but i need a thing to give these stats to. hm maybe i'll to a mockup in photoshop because i'm desperate and stuck on this mechanic
Probably more of a code-general question, but since you're here already..
You'll need to google up how to Instantiate() objects. Then you'll want to create a data object that holds stats (current/max/etc) of your miners. Then you'll have various prefabs that can display them in some way. Then get your data object from a weighted list (or perhaps just get an enum to reference a scriptable objects to contain their stats), and do what you need to with it.. hold it in memory, render it in one or many prefabs, and so on.
There's a lot of parts to this feature, and your question is a little broad, so break it down and you'll do great (but you probably ought to ask the specifics in #archived-code-general or maybe even #💻┃code-beginner since, unless I've misunderstood what you're asking, this is pretty rudimentary stuff).
I've placed Rule Tiles with gameobjects attached to them in a tilemap and it all works as it's supposed to, but I now want to remove the tiles through code.
Writing tilemap.SetTile(position, null); doesn't work, because it gives me the error:
Destroying GameObjects immediately is not permitted during physics trigger/contact, animation event callbacks, rendering callbacks or OnValidate. You must use Destroy instead.
But I of course can't use Destroy() as you can't destroy a single tile with that, is there some solution to this problem?
What is your Unity version?
2021.3.14f1
Hi, sorry for the late reply! This bug should have been fixed. For the 2021.3 LTS, it has been fixed on 2021.3.15f1.
Yeah try that
I think I read that dynamics aren't supported in Unity, but I've heard mixed messages about that. I'm trying to figure out if the crap I'm trying to do with system reflection and delegates is screwing me up or if it's the dynamic types or something else.
Here's the method where weirdness is occuring:
public Dictionary<string, Func<dynamic, dynamic>> GetScriptableMethods()
{
// Create the dictionary that will hold the scriptable methods
Dictionary<string, Func<dynamic, dynamic>> scriptableMethods = new Dictionary<string, Func<dynamic, dynamic>>();
// Get a list of all methods in the class
MethodInfo[] methods = this.GetType().GetMethods();
// Iterate through the list of methods
foreach (MethodInfo method in methods)
{
// Check if the method starts with the scriptableMethodPrefix
if (method.Name.StartsWith(scriptableMethodPrefix))
{
// Get the name of the method without the prefix
string methodName = method.Name.Substring(scriptableMethodPrefix.Length);
// Create a func delegate for the method and add it to the dictionary
Func<dynamic, dynamic> methodDelegate = (Func<dynamic, dynamic>)Delegate.CreateDelegate(typeof(Func<dynamic, dynamic>), this, method);
scriptableMethods.Add(methodName, methodDelegate);
}
}
// Return the dictionary of scriptable methods
return scriptableMethods;
}
}```
anyone here have exp with static batching in runtime ?. i tried to do it but not work ...
Thank you for the help! Updating Unity fixed my issues
I use Oracle ODP in Unity to Query my db. This Exception only occurs in a Unity Script.
TypeLoadException: Invalid type OracleInternal.Common.ColumnDescribeInfo[] for instance field OracleInternal.Common.SQLMetaData:m_columnDescribeInfo Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Boolean requery, System.Boolean fillRequest, System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0) Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0) (wrapper remoting-invoke-with-check) Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader(System.Data.CommandBehavior)
Code:
using (OracleConnection connection = new OracleConnection(conString))
{
OracleCommand command = new OracleCommand("SELECT * FROM PERSON", connection);
connection.Open();
OracleDataReader reader =
command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Console.Write(reader.GetString(0));
}
reader.Close();
}
-Expectation was a simple SELECT Query Output. Maybe it has something to do with .NET Versions?
-Other Ideas how to query a Oracle db?
@timber flame so, are you trying to replicate the screen you showed?
Or will you be able to zoom out tenfolds?
anybody using apple cloudkit? I'd like to make sort of a group with people using it to share knowledge
?
https://www.youtube.com/watch?v=noOScGO21Bc
Terra Nil.
First, do you think it is a tile map? how can we optimize meshes in these games, triangle count, combining faces, etc.?
The only optimization is not to render invisible faces?
Terra Nil is a reverse city builder about ecosystem reconstruction. Turn a barren wasteland into an ecological paradise complete with different flora and fauna. Then clean up, leaving the environment pristine. Subverting the builder genre, Terra Nil is about the restoration of a ravaged environment.
Terra Nil on Steam: https://store.steampowere...
some models give a RedAlert vibe 😄
What?
dont you know the game RedAlert
one of the first real time strategy games
from the 90's
check some buildings in terra nil
and check those
homage?
or simply lack of imagination
😄
how do they optimize 3d tiles? or do not
Pure cubes, combining faces of same voxels.
I think it is pointless because almost always neighbor voxels differ and have different textures
What do you mean? You can generate texture atlas of some sort so you would be able to combine the meshes as well, even with different textures.
you don't have to optimize it further, if this is the map size you are aiming for, just make sure most of the tiles are in the same drawcall
the gpu can handle millions of vertices
Combining is ok
My problem was not draw call.
I would like to reduce triangles, vertices
I guess it depends.
If the game is like minecraft with many same voxels, I can combine faces to reduce triangles
But games like Terra, it is pointless and cannot combine neighbor faces because they are not equal
30*30*30=27000 cubes
27000*12=324000 triangles
It is huge
If it is like minecraft. Disconnected Voxels are valid but in tile games usually the tiles are connected and placed on top of each other
So, the triangles reduce dramatically.
Right?
super curious, I want to pass an argument via a c# event.
Example:
I have an event manager with an event called OnItemPickup that takes in a ScriptableObject.
I want to then in the pickup script pass a scriptableObject through the onItemPickup event to all observers/listeners to do with the scriptable Object whatever they want. i.e Update inventory, update stack size, store in inventory databese etc.
Is this possible ?
Sure, use a delegate type that takes in an argument, like Action<T>.
Here, it would be
event Action<MyScriptableObject> ItemPickedUp;
Then invoking it you would pass the arg: ItemPickedUp.Invoke(so);
And the subscriber methods will be forced to have a param of type MyScriptableObject
Action is defined multiple times for you to be able to pass up to 7 arguments if I remember correctly
Yeah, as SPR2 says. I've done some event driven stuff with ScriptableObjects before. Basically, create a class with the correct type of parameter:
public class FloatEvent : UnityEvent<float> {
}```
Then you can create an event system based on the FloatEvent. Like so:
```[CreateAssetMenu]
[Serializable]
public class EventObjectFloat : ScriptableObject {
public FloatEvent OnTrigger;
public void AddListener(UnityAction<float> action)
{
OnTrigger.AddListener(action);
}
public void RemoveListener(UnityAction<float> action)
{
OnTrigger.RemoveListener(action);
}
public void Invoke(float value)
{
OnTrigger.Invoke(value);
}
}
Of course, float can be any type 😄
🥹 thanks for the help!!
Nice you now have two ways of doing it, the raw C# one with pure events, or the more Unity one with a custom UnityEvent implementation, that would appear in the Inspector if you'd like to subscribe from the Inspector directly
I want to go the pure c# event route. Less clutter in the inspector
I wonder if overloading applies to delegates.
Nah delegates just store "a pointer to a method" so if you want overloads you need multiple events with multiple delegate types
If the argument type is a base class though, you can pass child classes as arguments
The reason for the questions is, My code is so tightly coupled together and I feel that, should the code grow, there will be situations where I would need to change something , but can't. So, I am trying to fix my mistakes before they get to out of hand.
This might actually work.
have the Item SO as a base and then if I need the weapon, utility or consumable , I can just cast to that type based on base type. ItemSo as WeapnoSO or something like that
Sure, or to have more type safety you would not cast but instead declare an abstract method in the base class, each child class overrides.
When you'll call the method from the event handler, it will select the correct implementation based on the actual type of the argument
That's a cool idea.
I am rather new to SO's events and delegates but this will really come in handy. Much appreciated
Btw, in case you were not aware, you no longer need to create a concrete class of UnityEvent to use it.
(Maybe it was just copy-paste code or just playing it safe on versions, but thought it was worth mentioning still)
public class WeaponSettings : ScriptableObject
{
#region Attachments
[Serializable]
public struct Attachment
{
public GameObject Prefab;
public Vector3 Position, Rotation;
}
[Header(" Attachments")]
[Header(Utility.SeperatorLine)]
public Attachment VerticalForegrip;
[Header(Utility.SeperatorLine)]
public Attachment ExtendedMag, LaserSight, Supressor;
public void AddAttachment(Attachment attachment)
{
Transform ParentTR = nameof(attachment) == nameof(ExtendedMag) ? player.Wep.MagModelTR : player.Wep.BaseGunModelTR;
var newAttach = Instantiate(attachment.Prefab, ParentTR);
newAttach.name = attachment.Prefab.name;
newAttach.transform.SetLocalPositionAndRotation(attachment.Position, Quaternion.Euler(attachment.Rotation));
player.Wep.Attachments.Add(AttachmentFormalNames[attachment]);
}
#endregion
public static Dictionary<Attachment, string> AttachmentFormalNames = new Dictionary<Attachment, string>();
public static Dictionary<Sight, string> SightFormalNames = new Dictionary<Sight, string>();
private void Awake()
{
AttachmentFormalNames.Add(VerticalForegrip, "Vertical Foregrip");
AttachmentFormalNames.Add(Supressor, "Supressor");
AttachmentFormalNames.Add(ExtendedMag, "Extended Mag");
AttachmentFormalNames.Add(LaserSight, "Laser Sight");
SightFormalNames.Add(ACOG, "ACOG Sight");
SightFormalNames.Add(RedDot, "Red Dot Sight");
SightFormalNames.Add(Reflex, "Reflex Sight");
SightFormalNames.Add(Holographic, "Holographic Sight");
SightFormalNames.Add(SniperOptic, "Sniper Scope");
SightFormalNames.Add(TwoXOptic, "2X Optic");
SightFormalNames.Add(FourXOptic, "4X Optic");
}
}``` I don't know why the dictionary is empty
I also have set the script execution order above the other related scripts just in case
Becasue SO’s Awake is no magic and not get called until you actually load that specific SO
but aren't SOs basically scene independent MonoBehaviours without having a need for a gameobject?
No who said that? They are assets
public class Weapon : MonoBehaviour, MyInterface
{
public WeaponSettings WepData;
}```
I have the SO referenced to my MonoBehaviour, I have no idea what you mean by loading the specific SO in order to call Awake()
And is that Weapon on the scene or is that prefab?
it is on the scene
ah so what I've understood from a post is:
you have to do ScriptableObject.CreateInstance() for its Awake() to be called
drag & dropping the SO through the editor won't trigger Awake()
I assume it's because your domain reloading is off for entering play mode
it was
hopefully it will work now
ScriptableObject is a persistent (in editor) asset and shouldn't really rely on it's lifecycle events
when using kUnityRenderingExtEventUpdateTextureBeginV2 and kUnityRenderingExtEventUpdateTextureEndV2, do I need to allocate memory inside Begin and free inside End? or can I create like a circle buffer and just cycle?
i really dont know what to do, so the idea is, i want to move animated object on the left, towards object on the right, as in the picture, both of its anchored position are 0(vector3) so icant just tween the anchored position, without able to tween everyting came with its, using local Position also didnt help, i know exactly i need to calculate everything first, with regards of its pivot, and anchor min max, size delta etc, but i dont know where do start, is there any tutorial of web explaining about this, or for more simple how to move rect transform toward other rect transform thanks
Gotcha. The question I wanted to know is if I have a script that is reference by two other scripts, if I change script 2 which refences script 1, will script 3 reload as well.
The next question is if I have an assembly definitions defined. If I use the "using (assembly name);" tactic, will that fix all the reference problems that usual happen.
Are you using DOTween? If so, just get the transform as RectTransform and use DOAnchorPos().
For your first question, you'll need to get up to speed on what it means to "reference" a script. You should start by reading up on "by reference" and "by value" (just generic c#/programming concepts).
Then you'll want to get up to speed on what it means to have a "script" in unity. If it's a static script or singleton that's not a monobehaviour - it just exists in memory, and you need a way to reference that single copy. If it's a monobehaviour in your scene, you get a handle to it via Unity (in a variety of ways - you can use FindObjectOfType or GetComponent or explicitly link it in the inspector or keep track of it if you Instantiate() it).
For your second question, I'm hesitant to answer it because based on your other question, it sounds more like you might be doing something incorrectly. In general, though, Unity can handle your asmdefs automatically - just drop the DLL you need into the /Plugins folder. If you're needing something more complicated or something's not working, then you should probably ask specifically what the issue is (with code and/or screenshots of the errors). Especially if you're getting errors with missing system classes or libraries.
Does anyone have a smart idea how to get a comment on a component? It doesnt need to be the xml-comment, but it should be multiline text. and just shown, not serialized.
Header
Shown from where? Inspector?
I want it on the component/class, not the fields. Some of them don't have fields.
Yes.
Thanks for the response. I realise that my phrasing is a bit misleading. The questions I was asking were regarding assembly definitions and how they seperate your code during recompile in the editor. I have gotten an answer so for my question so I thank you so much for your assistance
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html This page is pretty good - I've referred to it a number of times over the years
That would require me to create a custom editor, doesn't it?
It does
Assembly is unit of codes that compiled into single dll file. using is for namespace not assembly. Assembly references are defined on asmdef.
My options so far for component comments:
- Use a field with Unity attributes. Multiline with linebreaks, gets serialized, so the shown text is a serialized copy that will be out of sync
- use a field with NaughtyAttributes-attributes. Visible, readonly, nonserialized. However, no linebreaks in text and thus unreadable
- write a custom editor, ...must either not use NaughtyAttributes-editor or it collides.
- rewrite NaughtyAttributes-editor. Result is nice, however i can't use the package version but have to include the project and need to manually reimplement the change every time NaughtyAttributes gets updated
If you are already doing NaughtyAttributes then this with any dummy field
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/info_box.html
Probably the best. Too bad the InfoBox doesn't show on private fields with NaughtyAttributes.ShowNonSerializedField and goes gray on gray barely readable with the NaughtyAttributes.ReadOnly attribute, but it's probably the best without rewriting NaughtyAttributes.
So i **solved ** my comments-on-behaviours problem by inheriting from the NaughtyAttributes-Inspector and adding a new attribute type.
This is what it looks like and here is the code just in case anyone is interested ~
https://gist.github.com/CortiWins/bfa6e66acb280692b1865b45bdfaac32
If you don't use NaughtyAttributes, just inherit from default Editor type.
repost from general but i just scrolled down in this server for the first time lmao
does anyone know a better way to do this? this pattern kinda sucks
var op = LocalizationSettings.StringDatabase.GetLocalizedStringAsync("Cafe", questInfo.localeKey);
if (!op.IsDone)
op.Completed += x => descriptionDialogue.text = op.Result;
else
descriptionDialogue.text = op.Result;```
yield return op;
With coroutine
oh neat! thank you
also is there ever a case where its that instant, and you can not just listen to Completed?
im not sure, ive had weird erroneous errors when not doing async localization stuff
For completeness, if you use async/await pattern (warn: not supported in WebGL)
string result = await LocalizationSettings.StringDatabase.GetLocalizedStringAsync(...).Task;
i want to incorporate that more into my style
would need a method that returns a Task for that and is async
my only trouble is that i struggle to figure out how to fit it in with the regular crowd like Update and OnEnable
you can have a async void OnEnable or Update
well Update would be harder
but you get the idea
yeah, i guess i really dont have an excuse not to though since performance is what i need rn
oh thats awesome i had no idea you could make them async!
async does not mean it performs better
i mean if you can use multithreading safely it will probably run faster unless you're doing something small
it heavily depends on what you are doing
querying a database is prolly a prime candidate for it, thats for sure
just using async methods and tasks just means concurrency
if you have having performance problems put your effort into profiling and figuring out why and where
for us, it was scripting, we had this algorithm that was absolutely horrid for performance
we have since replaced it, but the game doesnt quite run at 60 yet, that could just be from running it with usb debug though
still a lot of things to go over but our game is 2D so im skeptical that anything but scripting would cause issues
still got tools to tell you whats the issue
and the deadline is sometime next week lol
will tell you even what functions are the problem, or if its graphical what if its like fillrate or some other issue
yeah i used profiling to find out it was that algorithm
it was actually taking more time than the camera render which is a bit mind boggling
Does anybody know how to implement matchmaking system or room / lobby system in Mirror Networking? I need to use a Lobby Code, like ABC123, and with menu where the host can start the game?
If no one knows, point me to the right course/tutorial or something.
well most algorithms with some smart data structure usage and caching can be sped up a lot
Not sure about mirror unfortunately
So is it possible if I have a state machine to store the possible states in a variable?
I'm considering refactoring my server ( 🤮 ) to a web app instead of a networked console app. My interface to the app is primarily standalone calls anyway. I'm not sure how I'll push info out to clients [yet]. It would make scaling horizontally a bit easier instead of needing to orchestrate between console instances and the database.
Anyone have any big picture guidance on ramifications/shortcomings in using WebClient in Unity and a whole schwack of async calls to DownloadStringTaskAsync()?
Any ideas on how I could push data to (presumably-connected) clients?
Anyone have any big picture guidance on ramifications/shortcomings in using WebClient in Unity
does it work in il2cpp on ios and android?
i haven't tried using it in a very long time, but that was before they brought up netstandard2.1 support to an accepting level of quality
yeah so far so good on il2cpp/android - don't know about ios yet, but i'm currently using it for a single call to ipinfo.io for client IP address information
there is no easy answer for streaming responses from webservers
typically people use websockets
i use grpc in my games, but that will be very arcane
grpc supports bidirectional streaming. grpcweb, which unity clients are much easier to create for, supports server-to-client streaming
grpc is still http/2 so it is compatible with the way web servers are scaled and load balanced
you can also use SignalR
if you are pure c#, this is one of your best options (really magiconion from cysharp)
if i had to do this, i would use betterhttp/2 and wire it up to the real dotnet grpc client,w hic other people have done
the unity webclient doens't support all the features http2 needs for grpc
dotnet signalr and other rpc technologies that m$ supports are all migrating to grpc anyway
it has won
it is almost the best rpc technology
Hm.. I'm thinking perhaps the easier approach (I've been talking about this with someone else on slack for a few minutes) is just going to be to throw more hardware at each individual container until things start breaking, and if it's REALLY bad then build a lobby server orchestrator that hands off connections to "shards" and just manually scale up the size and quantity of those shards.
what is the actual issue you are observing?
are you doing 1 thread 1 player
and doing rpc over tcp?
an ad-hoc rpc
do you have a test that runs many hundreds to thousands of clients concurrently against your server?
Sorry for the delay - couple convos at once
I don't have any specific issue right now, but I have a single point of failure (the server). It's robust, and automatically restarts, but it's disruptive if people have battles in progress (the clients just drop to the connection screen and all the post-battle reward stuff never gets awarded).
I'm still building my bot/load testing client, so I'll be able to hammer it more soon enough
yeah
So far the server container itself uses negligible cpu/ram/bandwidth, but... it keeps me up at night that I don't really have a way to scale it if we go bananas at launch (think Among Us).. I mean, good problem to have, sorta, but.. you know, leaving money on the table etc
the client can be a dummy client in C#, that plays randomly, but over real networked rpc
you will only know with tests
the reality is passing a large concurrent number of users tests is hard
you will discover a bajillion problems once you author that
Yeah.. I'm just worried that if the tests reveal .. i dunno, imagine the server could only handle 100 concurrent users or something.. that's a big problem
we can talk about what those problems likely are but it's better to write the test first
Yeah, that's fair
it's only going to handle only 100 concurrents if you are doing all your stuff ad hoc
like if you are starting a thread for each user
I'm just sorta mentally exploring potential technology pivots.. So far the best idea I've heard is "throw more hardware at it" and if that fails, "lobby server orchestrating connections to shards"
no thread for each user, nothing as bad as that 🙂 and honestly, the numbers even under internal load tests look great - 1kb/sec bandwidth, 100kb ram steady, 0.0 cpu
this was the origin of this work - a completely random spike and failure
so i guess my takeaway based on that is
when i authored this test, it's my most important test, it reveals the most bugs
it reveals them all
it's very hard to pass
every user just gets tossed into a dictionary of connections, and whenever they send a message, i do what needs to be done - but "send a message" also means "disconnect" or "timeout" .. and sometimes other users act that requires sending a message to them (the battle mode, obviously)
okay well since there is a very specific implementation here
before brainstorming ways to change it
besides a mass concurrent players test
i suggest using toxiproxy to test disconnects
https://github.com/Shopify/toxiproxy This? On the server? client? both?
you can take a look at the spellsource tests for an idea for my opinion of the minimum number of tests
the server will be proxied by toxiproxy. then your test will cause the connection between the client and the server to drop as though it were a network failure
cool, this is interesting
https://github.com/mdevilliers/Toxiproxy.Net seems relatively straightforward
And yeah - I have your spellsource server tests in my "review this shit later" folder of bookmarks haha
I was like, I think I read this recently!
yeah I gotta get around to doing proper testing and benchmarking instead of my current ad hoc approach
"apply more hardware"
well
actually more importantly - i'm chasing ghosts since I don't actually know the failure points right now
yeah
it's just that simple right now
like i said there are bugs
there isn't a performance issue
there are going to be other bugs, like concurrency bugs
it's going to be stuff like having a database connection pool that is too small
or misusing an api, and you wind up with blocking io somewhere
there's going to be bugs with the bot, if it's a smart bot
which when i see a turn based strategy game with suddenly a huge spike in memory usage
that's a bot bug
Yeah. So far those bug surfaces are small-ish, but .. I know what you're saying. The ones that are gonna bite me are not what I'm expecting and I'm only gonna find out after throwing some serious traffic at it
your test should not start a unity binary
The huge spike in memory usage is really strange though because I make that exact same call dozens of times per second in normal operation
Yeah, my test framework is a console app
I shouldn't say "framework", I mean "bot"
it should be a c# class
the fake client
it should just connect and do the whole life cycle, and then play randomly
in the test, in memory of the test
over the network
1 process
Yeah. I imagine I'm going to want to run the toxyproxy thing on the unity client as well and see how well the client responds to lag/PL
well.. it's way too clunky to do that
you're just not going to have the bandwidth to do that when your hair is on fire
or whatever
Fair enough
OK back to work! (btw launch date on/around feb 6.. it's crunnnnnnnnch time)
How to properly maintain CI and tests in custom package?
Because to run tests i need a UnityProject but package itself is not a project.
Should CI create new project, import the package, then run tests in it with
"testables": in manifest.json? (I'm using GitLab)
Is there a way to force start or awake to trigger even when the object is disabled when the scene loads ?
Just make a dedicated test project with having the package as submodule
you mean git submodule or just get package with unity package manager
I meant git submodule in Packages folder
Easier to manage that way imo but up to you
What I did is use git subtree to create branch that only contains the package and create releases from that
While the main branch also has a project + tests and stuff
it really depends what you are testing
why are you you using gitlab? what does the package do and what do you want to test?
gitlab is just my company policy and there are playmode and editmode tests simply
what does the package do?
it looks like you've been asking about this for a while @true cosmos
okay, and what do you want to test
@undone coral do you know something about custom preprocessor directives?
Do Unity scripts run in the same order for different PCs.
Example:
On my PC, Script A and B want to add something to a list of Script C. Script A adds first and then Script B.
Is there a possibility that Script B would add something to Script C first on another PC
yeah
hjahahah
if i do #define NAMEOFMYCUSTOMCLAUSE
does that mean that one is true?
i mean....
there's no guarantee on script execution order unless you specify it using the defaultexecutionorder attribute. however, all else being equal, it will be the same order everywhere
i build the game in 3 different modes which i set using a ScriptableObject
Debug, Beta, and Release
yes it will evalute to true, but... only inside that file
Thank you
i would like to depending that value in the SO
okay
'Debug, Beta, Release'
to have custom clauses
#if CUSTOM_DEBUG
etc...
so stufff i dont want in code (dangerous for non admins) ends up in release builds
how would i approach that? something like....
the simplest pattern is
static class Configuration {
static bool isDebug =>
#if UNITY_DEBUG
true;
#else
false;
#endif
}
if you want to prevent code from ever shipping it is really hard to achieve this
without introducing this everywhere. in that case you should use interfaces and an assembly
the only one who prevents that is UNITY_EDITOR as i am aware?
i actually do this for appmana
you can specify the #define SYMBOL using the field in player settings
which field?
or on the assembly definition file
it's called like custom scripting defines or whatever
it depends how pervasive this code is and what you mean by dangerous
then i can give a specific suggestion
but with that i can avoid certain chunks of code to be included in builds?
yes
well... its admin features i would not like the users to end up accessing to them in any concept
that lets you create custom stuff
they should be on a different 'god app' maybe but for the moment they're still there
and how do i modify the value of the SYMBOL? thats what i dont get
like... im gonna build okay? how do i say if the symbol is debug, build or release?
i was reading this
C# - Preprocessor Directives, The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
but there doesnt say how is the code modifying the values of DEBUG or VC_10
i guess is taking it from the system
unless i can do something like....
if(MySOConfig==Debug)
{
#define MY_CUSTOM_DEBUG
}
then that would make sense
oh
you can't do that
shit
it either exists or it doesn't
and ...
hmm
okay so in each build i have to declare if it exists or not
so that means....
i should be able to include, remove, it from here on each build
is that correct ?
that way if i include.... #ISRELEASE in that before build, the clause #isRELEASE will be true
correct?
and then find a way to, when i build for debug remove it
yes
okay that seems easy
it depends how well contained this is
you can put all your admin / testing code into its own asmdef
and then you don't have to litter your code everywhere with scripting defines
you can reference / dereference the assembly, including using a scripting define (which is the simplest way to do it)
unity's "service loader" (if you are familiar with java) is [RuntimeInitializeOnLoad]
you can use this to inject your admin script into the scene. so to clarify
create an asmdef called Admin
put all yoru admin code in it
i understand the concept but no idea how to do it
okay
asmdef its another assembly as i understand
make it "alive" by declaring [RuntimeInitializeOnLoad] on a component inside of the assembly. observe now that code runs when the player starts.
yeah first i'd need to separate this 'admin functions' into another assembly right
now you have many ways to turn this code on and off
- declare it inside a Package, and add remove this package via
manifest.json. this makes leaking admin code very very very hard
oh i see
- use the inspector on the asmdef (the asmdef settings) to only include the assembly if a scripting define is set elsewhere
okay thanks for the idea, ill have to read more about that 🤣 since i always avoided work with this shit but i appreciate it a lot
i architect stuff to be Zero Trust so i have admin code shipped to everyone
they have no way of using it
i don't think it provides meaningful insights. however it is rewarding for enthusiasts to find
anyway you should create a single repository that contains everything you need, including the test project, for testing purposes
that project should reference the package via "com.pablo.utilities": "file:../../com.pablo.utilities"
i wouldn't use git submodules, git subtree, etc.
use submodules if you have a mix of public and private repositories or if you're referencing a repository you don't control
since you fully control all this code, make it as easy as possible on yourself and put all the files in one place
you can operate a custom unity package registry, but it is probably simpler for your end users to reference a repo via a git url. that said, it is really painful to use private repo urls, especially on windows and especially in CI
so in my opinion, unless your goal is to maximize billable hours, you are overengineering this
you haven't really told me what this package does. when you say utilities, what do you mean?
is there anything actually sensitive about it?
it will all be made easier by making the package public, on github.
but in my opinion, packages shared among projects for utilities is very very low yield.
you wind up using 1 utility, a different one, in every different game. you might as well have just copied and pasted the little snippet of code, and eliminated all this maintenance burden. this is also why i'm confused there are tests
if this is an accounts management UI, you will also be in a lot of jeopardy
for starters, you shouldn't have that UI inside unity. @true cosmos so you can't just pick and choose which things you want to do "the right way."
single repo for both unity project and package sounds cool
i dont want to get involved into what exactly the package does, but i saw many public packages that have tests in them, thats why i wonder how do these devs test them
i dont want to get involved into what exactly the package does
my friends joke that NDA stands for Not Doing Anything
😛 cool joke i admit 😛
it sounds like it doesn't do anything useful
there isn't anything possibly sensitive about what a unity package does.
it has literally never been the case here, in this chatroom, that i've messaged in for years, that the thing the person didn't want to talk about turned out to be sensitive. more often than not, it turned out to make absolutely no sense
i'm not trying to bully you but seriously if you want good advice - if you want to ascend in your life as a programmer - you have to be able to say what the thing is
otherwise i'll just guess
okay
it just doesnt matter. Just testing package seems like generic topic to me 🙂 i plan to work a lot on custom packages
it sounds like this is some kind of package for doing shared office space / virtual lobbies to me
like the habbo hotel idea.
is that correct?
it's not readyplayer.me but something adjacent. like you are building little interiors and having 3d characters move around them
@true cosmos is that right?
i dont get it
your project, your company or whatever, it is something something The Metaverse something something VRChat-style casual 2d/3d spaces inhabited by custom player avatars. and i guess you can design these spaces in the game / editor / something
it's not super clear to me why this is sensitive
it just doesnt matter.
well you will ascend a little bit once you realize that it does
anyway that's what it sounds like it is. what is the game? is it a pay to earn game idea?
I'm trying to update my players boat's rotation to align with the mesh collider normal of a low poly wave, but nothing ive been trying has been working. Any Ideas?
This is what I have been trying to do so far for the rotation
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint (transform.position);
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);
if(Physics.Raycast(transform.position + new Vector3(0, 35, 0), -transform.up, out hit, Mathf.Infinity, Water))
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(hit.normal.x,-angle+90,hit.normal.z)), Time.deltaTime*2.15f);
}
Quaternion.Euler(new Vector3(hit.normal.x,-angle+90,hit.normal.z) You're mixing up euler angles and a direction vector
that's nonsensical
Is there some proper/easy way to buffer inputs with unity's new input system? Currently I have a monobehaviour implementing the generated IGameActions interface, that dispatches c# events in the callbacks. I then have 2 game objects that listen for those events. Trouble is, they might animate for a couple frames, and in that state they ignore other input. This system seemed robust and flexible and allowed me to write an "AI" player that dispatched the same events, but now I'd like to introduce an input buffer and I feel like I'd have to throwaway much of it, cause now it seemed a "classic" way of checking for input in update would be easier to add a buffer. (plus I don't like that I have to add buffering separately to the different event subrcribers) Is there some established proper way to handle input buffering?
Use a Queue to buffer anything basically.
yeah, but if I have 2 controllable things reacting to events, I need both of them to have their internal queues. Alternatively if I maintain a single "input queue" I need to move away from an event based callback input, and instead each thing/controllable has to poll the input system in it's update call.
can't the event based callbacks just put things into the queue?
sorry I'm not super clear on the details of what you're trying to do tbh
to give some context its a puzzle game where you control the "board" and a "piece" - you can move both, so they just subscribe to their events currently. I'm a solo dev with a programming background, so instead of gameplay I maybe focus on things being "nice" in the code... and in this scenario the idea of having separate command queues for both the board and the piece doesn't sit well with me
(cause I feel like there should be a single input buffer, but I'm not sure how to pair it with callbacks on different objects)
I just wondered if there is some standard thing, maybe the new input system has some concept of bufferred input to lead me to a solution.
are you trying to say you want to debounce some commands?
okay, it sounds like you are using state machines, when you should not 🙂
I feel like there could/should just be a central command dispatcher. It reads the input queue and tells the appropriate objects to move
when you say "animating for a couple frames and in that state they ignore other input"
rather than the objects all subscribing to different queues/events
if you are using unity animation controller, you have to allow transitions to be interruptible, and it's better that if the user makes an input, the thing reacts immediately. since this isn't a fighting game, that's the expectation
yeah, so adding an intermediate object/layer that grabs all of unity input system, queues it up and dispatches/moves the objects. I guess this approach would also seamlessly work with my "ai" commands too.
idk about "all of unity input system", but at least the "move objects" action map
there are lots of ways to do this. when i have some finnicky input code i need to author, i reach for unirx. especialyl because it provides literal semantics like Buffer and Window which may interest you. something you might also need is Amb
if you could be more specific
i can write an example
a nice thing about unirx is it's really succinct
oh, thanks. since this is a learning hobby project, I also enjoy procrastinating / "reseaching" how things are done.. so while often trapping myself in analysis-paralysis, I'll check unirx and amb!
Amb Buffer and Window are operators from ReactiveX (which unirx is like a library for, with unity bonuses)
@undone coral since you mentioned windows and fighting games, can you recommend some standard way to handle "fighting game input" in unity?
(I also wanted to rotate my puzzle pieces with controller sticks, which lead to surprisingly messy code translating stick position to directions, holding that in ringbuffers with timestamps, etc to detect circular motion)
since you mentioned windows and fighting games, can you recommend some standard way to handle "fighting game input" in unity?
this is a big topic. since fighting games are an old tradition, you will only see implementations built around anUpdateloop even though you can achieve the same feel with less code, more succinctly and with greater clarity other ways
etc to detect circular motion
so would an idea be
to rotate the piece, the player
- moves the joystick from neutral to a fully extended position
- as the joystick is dragged along its housing's edge in a circle motion, rotate the piece some discrete amount per arc made with the joystick
- cancel the rotation when the joystick is released back to neutral position
or do you mean
to rotate the piece, the player
- moves the joystick from a neutral to fully extended position
- the direction pointed to by the joystick is now the orientation of the piece
- moving the joystick orients the piece in its direction
- rotation is canceled when joystick is back to neutral
So I'm trying to not over do it, since it's NOT a fighting game, currently my code just emits a cw or ccw event if the stick is dragged along for a set amoult of time. (this also means, that a simple "up" motion is delayed, because my code has to wait to make sure it's not really a ccw / cw motion)
I was actually curious if such a "simple" mapping of joystick positions with a small lag can be achieved using unity's "input processors"? I ended up just grabbing the stick vector2 and doing everything in the input event handler.
in my opinion the input processors are not very useful because they are stateless
but let's stick to a specific example
so i can show you why UniRx is really well suited for this
unirx being reactivex for unity
if you're familiar with rxjs / rxjava
🙏 just skimming unirx docs looking for examples, but if you have time I'd appreciate a top level "how you'd do it"
or rxnet
okay
so let's say we have a stream of joystick positions
we're going to do the rotation becaus eit's simple
unfortunately, I have zero rx experience. I'm familiar with how webbrowser events work (to an extent I knew what a debounce was and that it wasn't what I wanted)
first let's turn it into an observable
[SerializeField] private InputActionReference joystick;
void Start() {
IObservable<CallbackContext> inputStream =
// this very arcane and a consequence of C# syntax,
// all it's doing is converting a c# event into an IObservable
Observable.FromEvent<CallbackContext>(handler => joystick.action.performed += handler, handler => joystick.action.performed -= handler);
...
now we have an input stream we can use linq methods and RxNet operations on
let's say i wanted the "non-neutral joystick positions"
var joystickVector = inputStream.Select(ctx => ctx.ReadValue<Vector2>());
var notNeutral = joystickVector.Where(v => v.magnitude > 0.8);
okay, now i want to "start" and "end" with a sequence of not neutral joystick positions
var continuousStreamOfNotNeutrals = joystickVector
.SkipUntil(v => v.mangitude > 0.8)
.TakeWhile(v => v.magnitude > 0.8)
.RepeatUntilDestroy(this);
and now i want arcwise diffs of the joystick positions every frame*
var joystickEveryFrame =
continuousStreamOfNotNeutrals.CombineLatest(
Observable.EveryUpdate(),
(joystickVector, _) => joystickVector);
var diffs = joystickEveryFrame
.Pairwise()
.Select(pair => {
var curr = pair.Current.normalized;
var prev = pair.Previous.normalized;
var arc = Vector2.SignedAngle(prev, curr);
return arc;
});
now i want to rotate only if the user has done at least N degrees
i want to turn this into discrete rotations
and the idea is, i will gather up the diffs
and whenever those diffs exceed some threshold, do the rotation and reset to 0
I can already see this is cool, although it would require some practice to get your mind to think in streams like that.
var discreteRotations =
diffs.Scan(new JoystickRotationState(), (state, diff) => {
// we will fill in the ??? in a second, because
// this represents the state of our rotation detector
state.total += diff;
// if we have rotated more than 90 degrees
if (state.total >= 90f
|| state.total <= -90f) {
state.emitRotation = Mathf.Sign(state.total) * 90;
state.total = 0;
return;
}
// reset the rotation emission
if (state.emitRotation != 0) {
state.emitRotation = 0;
}
})
.Where(state => state.emitRotation > 0)
.Select(state => state.emitRotation);
struct JoystickRotationState {
float total;
float emitRotation;
}
(I kind of want to nitpick because I was actually disappointed with how SignedAngle worked for me.. but perhaps I had some bug in my implementation, and went for Math.Atan2 and then converted radians into a 0 - 8 direction "index")
anyway, how would you introduce timing into this, and how do you control what "Latest" means in combineLatest?
there are lots and lots of ways, Delay, Timestamp
Scan on Timestamped elements
i am doing time via observable.everyupdate
because it is the simplest
finally in this example: actually ortate the object
void Start() {
...
discreteRotations.Subscribe(rotation =>
transform.DOLocalRotate(new Vector3(0,rotation,0), 0.3f))
.AddTo(this);
}
i think in this particular problem you don't need to know the times
you think you do but you don't
you just want to accumulate the motion of the joystick
until it passes a certain threshold
so the real science here is scan
it is really clunky to do scan in an update loop
scan is like reduce in map reduce, except it gives you a result for each new item
oh, so combine latest everyupdate just collects all the input joystick events that happenned every frame?
it's a "running reduce"
no, it just emits the latest joystick position seen every frame
the joystick position is stateless
if it were joystick position deltas that wouldn't work
this particular kind of input you want to do
this problem you are trying to solve
it doens't care about time
it cares about time in the sense of being responsive to the user's joystick input changes
but it doesn't use time to make any decisions
ok, just to carry this tutorial, if we did care (so we only wanted rotation moves if someone rotated the stick in the last 0.5s ?)
combinelatest will take the latest value of these two streams, a stream of every frame and the eventful stream of joystick inputs, and give you a chance to emit something that works on the latest value of both of these streams
i know, but think about it. that doesn't make sense
it will be a bad control
you can come up with something where time does matter
for example, holding a button for at least 3 seconds
which input system actually already has a field for
so that's sort of a bad example
you can do, holding a joystick position in a certain direction for a minimum number of seconds
like only if you long-hold it right for the last 3 seconds
I'm just trying translate what my shady system does... ok so ignore the time for a second. If on top of the rotation, we wanted to also support a "flick" up or down on the stick? we can make separate observable streams on the same joystick input?
yes
you can make separate streams
// sequences of holding right
var holdingRight = joystickVector
.SkipUntil(v => Vector2.Dot(Vector2.right, v) > 0.8f)
.TakeWhile(v => Vector2.Dot(Vector2.right, v) > 0.8f)
.RepeatUntilDestroy(this);
// sequences of holding right that
// last at least 3 seconds
var holdingRightAtLeast3s = joystickVector
.SkipUntil(v => Vector2.Dot(Vector2.right, v) > 0.8f)
.TakeWhile(v => Vector2.Dot(Vector2.right, v) > 0.8f)
.Window(TimeSpan.FromSeconds(3))
// emit a dummy value instead of a list of vector positions
.Select(_ => true)
.First()
.RepeatUntilDestroy(this);
unforutnately unirx hasn't implemented window, so you have to make that yourself. i have
this does look super interesting. can we jump to a fighting game example, cause you mentioned windows..., we could instead of doing that accumulating just translate each vector into a cardinal direction: n, s, e, w, ne, nw, sw, se? and operate on a "stream" of those? but in that example we would want to timestamp those inputs?
ah...
i just copy and paste it out of system.reactivex
no more timestamps
you don't need timestamps
you can easily add a timestamp to stuff
but you don't need it 99% of the time
every time you are doing timestamp you are reimplementing Buffer, Window or Delay
you can Select to turn the inputs into something logical like a direction
same as linq
presumably you will want to SkipWhile you are animating. in a fighting game, the way inputs are or not buffered is complicated
it's super traditional
i can't tell you exactly what they are
you just copy whatever it is that the audience likes
i don't think it necessarily is Right or Wrong
so if you talk about fighting games, it's not really applicable to anything else
if you think it IS applicable then you need to update your opinions to mine
these are just opinions.
if you want the stream of inputs you've "missed" since the emission of some other event, you can Scan
Scan solves everything
I just meant how would you word it in unirx if you wanted to check if last inputs in the stream were "n, ne, e" for example?
var cardinalDirections = joystickVector
.Select(v => {
foreach (cardinalDir in
new [] {Vector2.up, Vector2.right, Vector2.left, Vector2.down}) {
if (Vector2.Dot(cardinalDir, v) > 0.5) {
return cardinalDir;
}
}
return Vector2.zero;
});
// actually do something with it
cardinalDirections
// we want something where the user expressly does fighting game style
// motions. distinct until change will return the first in a sequence of identical items,
// until it changes. so this means this will emit "right zero right down" if that's what the user
// does with their stick, it won't emit "right right right right"
.DistinctUntilChanged()
// now remove the "zero"
.Where(dir => dir != Vector2.zero)
.Subscribe(dir => {
character.LocalMove(dir);
})
.AddTo(this);
How to access Unity's API when I am in another thread created by UniTask?
(so, I don't need timestamps, because the events in the streams are implicitly timestamped, hence we can do something like Window(TimeSpan.FromSeconds(3))
sure
the example i am doing will work
the trick is to use DistinctUntilChanged in order to achieve something like "the sequence of fighting-game style stick flicks"
you can also require that the stick goes to neutral
suffice it to say unirx is way more expressive
for building up these interactions down to the detail
you can use window to gather flicks that were emitted within N millis of each other, which i think is what you really want.
or to complete a sequence if n millis have elapsed since you've received an element
it's complicated
you will have to learn a lot of stuff
but it's expressive and bug free
that was super interesting, I think I expected something like that from unity's input processors. I might try to rewrite what I have as unirx ar an exercsise)
way fewer bugs than update loops
input processors are stateless
they can't do this stuff
timeout is the right choice for fighting game direction inputs
there's a lot ot learn
so one more technical question, you skipped over it ar it was obvious that we can just take one joystick position from every frame. But in theory input can happen at a higher rate, right? from your experience this isn't an issue?
you gotta use a concrete example
you wouldn't use a higher rate in this case
it wouldn't make sense
so what is the concrete example where you think you need a higher rate?
in the fighting game example, you don't "miss" any inputs, and there are no timestamps
there's no rate
ok, what if we're processing mouse or touch gestures instead. and we want to detect "circular motions", lets ignore the details of gesture detection, but say we also want to draw a trail - in that case we want all the positions to draw an accurate trail, and not just one from every frame?
you shoudl be using 1$ gesture recognizer for things like that
if you wanted to implement your own gesture recognizer, which i think is a bad idea because again, it's a problem with a huge number of traditions
you wouldn't need a rate, it will come out however frequently input system gives it to you
which is whenever the mouse emits an event, which for something like position is whenever it moves
input system can be configured to emit events from the input thread, i.e. as soon as they are emitted
then you can use ObserveOnMainThread after you've done your transformation to transition the events to the main thread
yeah, so is it possible that the combinelatest ( everyupdate... line, will "miss" some of those mouse events?
i only used that for the really specific example
you owuldn't use combinelatest everyupdate for this problem of recognizing gestures
because you're trying to recognize the shape of a drawing
you are only interested in when the finger lifts up from the touch screen and you have a shape
if you wanted to do it something in between, you can use a lot of approaches to get the first N millis worth of mouse movement or wahtever
your joystick controller circular motion
it has nothing to do with gestures with mice and touch screens
do you see that now?
they do not translate
so stop trying to make things easier for me to understand lol
you are actually going backwards, because you're making less sense
ok. so, in the joystick case, could we alternatively, instead of building the joystick event stream and then combine latest, build the stream "manually" by reading the axis positions once per update?
if you're asking "can i implement this in Update" yes
do what you need to do
good luck out there
all of input system can be used from Update
Hi, Im making a sim crane system, I have a container prefab (parent cube with the triggers, scr and all)
I was asked to implement a "save position to all objects after the play session is over, then load the new position to each one when a new session starts"
I tried with an Interface and binary but when saving it says something like error when parsing binary.
tried with other way but just one is saving, I read something about dictionaries could work, so
How can I get trans.pos for each object, save them and then load?
Update that touches a field on the component is a dual of Observable.EveryUpdate().Scan()
you're getting really caught up on Update and you're not seeing it is idiosyncratic to your particular problem
of using the joystick to rotate a puzzle piece
which is alway sgoing to be true
it's awlays going to be specific to what you wanna do
#💻┃code-beginner maybe look up a saving asset / save game tutorial
@undone coral really appreciate this. thank you for the detailed example and explanation!
yes. everything can be made to look like osmething you do in Update
it's up to you how you want to author it
you wanna do Mouse.current.position.ReadValue you can
it all works
it's not going to matter for your use case
you probably want to just use Input and Update
all this stuff i am talking about it's way too complicated
or, imo, use the arrow keys
you already have a discrete direction input on your computer
or the d pad
if you want to rotate, bind it to x and y on the controller, or the triggers or whatever
don't overthink this
no one is going to be like, man i wish this game had more innovative ways to rotate puzzle pieces
it's not worth it
Well I already have all that implemented anyway, but I'm now tempted to rewrite it to have cleaner code and learn something useful.
"worth it" is subjective when making games in unity after hours...
I didnt found one :c