#archived-code-advanced

1 messages · Page 36 of 1

sage radish
#

Sure, the feature can be the shared object. Then you'd just pass it as a constructor argument in both passes, passing this in the feature when you're making the passes.

formal egret
#

Oh genius

#

Define the offset inside the feature and pass the reference in the constructor

#

I got it, thank you @sage radish

undone coral
#

what are you trying to do?

#

what is your game?

abstract sinew
#

Aka multiplayer code

sly grove
#

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

abstract sinew
abstract sinew
#

I’ll try to recreate the error give me a minute

#

I’m in a different device right now

sly grove
#

If I recall your original error from two days ago it was you were trying to do += on a bool

abstract sinew
#

Yeah it was that

sly grove
#

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

abstract sinew
#

Yeah you’re right

abstract sinew
abstract sinew
#

i didnt mean to type that here

abstract sinew
undone coral
abstract sinew
#

oh sorry

undone coral
#

or "it's an RTS with three asymmetric factions" <- that's starcraft

abstract sinew
#

"Short single player horror story game"

undone coral
#

why are you using normal

#

for a single player game

abstract sinew
#

Basically find parts build car escape

#

Im making it multiplayer

undone coral
#

making what multiplayer? a pre-existing game?

abstract sinew
#

There will be singleplayer and multiplayer options

#

and it works fine I can connect and either be by myself or with another player

undone coral
#

i see you're making Deafening Pines multiplayer?

abstract sinew
#

Yes

undone coral
#

okay

#

have you talked to the people at normal at all?

abstract sinew
#

I have

#

And I think i fixed my issue

#

I need to try it

undone coral
#

i mean real people not discord people

abstract sinew
#

Give me a minute

abstract sinew
#

Oh I fixed it

#

My mistake was wrong on my end

#

I had it right the first time but I forgot to put this

clear wedge
#

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.

GitHub

Web3 Unity SDK. Contribute to 0xsequence/web3-unity-sdk development by creating an account on GitHub.

clear wedge
#

ayo wtf i think i fixed it by removing all my .ConfigureAwait(false)

undone coral
#

you should use unitask for async/await in unity

undone coral
echo timber
#

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.

undone coral
clear wedge
clear wedge
echo timber
clear wedge
undone coral
echo timber
#

What does that mean exactly?

clear wedge
#

and that's where my async tasks stop running

#

i mean.. i guess i could fork nethereum and try a unitask-only version, lol

undone coral
#

it doesn't

#

but can you show me where you think it does?

#

it clearly uses HttpClient which doesn't work in webgl

clear wedge
#

oh, sorry - I'm not actually using unitywebrequest or HttpClient.

await web3.Eth.Accounts.SendRequestAsync()

from https://github.com/0xsequence/web3-unity-sdk/blob/2551b3c0c5de67fad4908b7e97ef4164cd9fd28f/Assets/SequenceSDK/SequenceSharp/Scripts/SequenceNethereum/WalletConnector/SequenceInterceptor.cs#L22

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 };
}

https://github.com/0xsequence/web3-unity-sdk/blob/2551b3c0c5de67fad4908b7e97ef4164cd9fd28f/Assets/SequenceSDK/SequenceSharp/Scripts/SequenceNethereum/WalletConnector/SequenceInterceptor.cs#L199

which calls into the Wallet class here:

            return ExecuteSequenceJSAndParseJSON<string>("return seq.getWallet().getSigner().getAddress();");

https://github.com/0xsequence/web3-unity-sdk/blob/2551b3c0c5de67fad4908b7e97ef4164cd9fd28f/Assets/SequenceSDK/SequenceSharp/Scripts/JSInterface/Wallet.cs#L479

undone coral
#

an interceptor, that just intercepts doesn't it?

#

does it?

clear wedge
undone coral
#

do you see those calls?

clear wedge
#

yes, i see the calls.

undone coral
#

what is a web3.Eth.Accounts? It's not an HttpClient?

clear wedge
#

i'm 100% sure it's getting called, sec

undone coral
#

it's okay

#

if you're sure it's fine

clear wedge
#
            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

undone coral
#

what is the object?

#

what is it actually?

#

an Accounts?

clear wedge
#

like the .eth.accounts?

undone coral
#

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

clear wedge
#

so that async function is never finishing

undone coral
#

well

clear wedge
#

but yeah - i imagine if i called into an httpclient it could bail like that

undone coral
#

my guess is that it is running your interceptor, clearly

clear wedge
#

i will 100% debug from here

#

yeah, exactly

undone coral
#

and it is also an httpclient

#

well

clear wedge
#

👍

undone coral
#

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?

clear wedge
#

pulling it up

undone coral
#

okay

clear wedge
#

which.. sec

undone coral
#

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

clear wedge
#

yeah im looking for the actual requestor

clear wedge
undone coral
#

yeah

#

no surprise there

clear wedge
#

yeaaah okay i see lots of stuff about http clients

#

that seems like it's most likely it

undone coral
#

okay

clear wedge
#

i will do some more debugging, but really really appreciate it

undone coral
#

gotchyu

clear wedge
#

:)

#

btw happy to answer skyweaver questions, tho u should probably dm so we don't clog the channels!

undone coral
#

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

clear wedge
#

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 :)

undone coral
#

well eventually your bosses will have to reckon with when the coin tosses on the opposite face

clear wedge
#

we actually have like 70+ people at the company now 😅

#

hahahaha

#

as far as i know the game itself is nowhere near profitable :P

undone coral
#

hold on to my information

#

yeah yeah

clear wedge
#

😂

undone coral
#

i mean c'mon dude

#

i know

clear wedge
#

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

undone coral
#

i know

#

it's good

clear wedge
#

<3

#

anyways, thanks again for the lead on httpclient

#

i'm on it 😁

clear wedge
# undone coral gotchyu

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

undone coral
#

you shouldn't need to do it, provided you never do Task.Run anywhere

clear wedge
#

yeah - nethereum does it internally, and i'm scared that's what's breaking it 😂

undone coral
#

if anything, it should be ConfigureAwait(true)

clear wedge
#

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

undone coral
#

the unitask synchronization context is much better written than the default unity one

#

so in principle

clear wedge
#

i will see if i can finagle nethereum to work with unitask

undone coral
#

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

clear wedge
#

oh yeah, and see if the httpclient stuff gets called

#

fwiw this all works perfectly in-editor

#

but yeah

undone coral
#

hmm

#

in editor, does it use an interceptor at all?

clear wedge
#

yep, same interceptor

#

also works on standalone builds for desktop, ios, android

#

it's only webgl builds that break here

drifting hawk
#

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

undone coral
clear wedge
#

hehe that's what I'm trying to do 😁

#

thanks again for your help though

undone coral
#

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

clear wedge
#

😭

#

maybe i will try in unity 2022

oblique obsidian
#

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?

west scarab
#

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

oblique obsidian
#

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

west scarab
#

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

oblique obsidian
#

Sounds nice. Thanks

#

Btw, do you have a reference to lookup if I want to learn more about this?

west scarab
#

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

oblique obsidian
#

Sure, thanks for the hints!

oblique obsidian
#

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

west scarab
#

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

oblique obsidian
#

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!

undone coral
topaz plaza
#

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);
}
clear wedge
sly grove
chrome timber
icy basin
stuck onyx
#

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

kindred tusk
#

It's not guaranteed to avoid a collision, but I guess that's true of all hash functions.

stuck onyx
kindred tusk
stuck onyx
#

and used for testing

#

but if you tell. me md5 is better...

kindred tusk
#

I won't tell you that

stuck onyx
#

heheh+ç

kindred tusk
#

Because I don't know

stuck onyx
#

i guess there wont be too much difference

#

oh thanks a lot!

scenic forge
#

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.

west scarab
#

If the code is well written it should also be very easy to swap out the hash function and try different ones for performance

upbeat path
formal egret
#

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 ?

clear wedge
#

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

formal egret
#

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.

undone coral
#

yes i really think it was Intercepting

#

and it worked in editor because... httpclient works in editor

clear wedge
#

maybe it did some funky task.run or httpclients shit yeah

undone coral
#

yeah

clear wedge
#

i can't think of another reason even though the code disagrees 😂

undone coral
#

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

clear wedge
#

that's omega cursed :D

stuck onyx
#

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?

stuck onyx
#

so i can make my own clauses?

undone coral
#

what are you trying to do?

#

what is the effect?

true solar
#

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 ?

undone coral
true solar
#

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

undone coral
#

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

true solar
#

you just told me that the sun is shining. thanks for illuminating me with this eternal wisdom.

undone coral
#

🥺

formal egret
#

aka pixel perfect camera inside a render feature

undone coral
mental dock
#

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

compact ingot
dapper cloud
obsidian glade
dapper cloud
#

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

obsidian glade
#

I'd guess your coordinate definitions might be getting mixed up

brisk pasture
#

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

sly grove
#

Do note that unity uses a pretty unusual cell coordinate system for hexes, I don't think it matches any of redblob's exactly

shadow orchid
#

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?

undone coral
shadow orchid
#

windows 32-bit, my bad

undone coral
#

the steam hardware survey shows <1% 32bit windows so it's not meaningful to support anymore

shadow orchid
#

thank you

#

totally forgot steam hardware survey for that..

velvet rock
#

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...

jolly token
velvet rock
jolly token
velvet rock
#

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.

jolly token
velvet rock
#

Like the functionality is in C# just they desinged it poorly.

jolly token
#

Some of them maybe, I can understand the reasoning tho

mortal gust
random dust
random dust
#

I tried looking into the changelogs but I can't find it there either

compact ingot
#

I don’t think there is documentation about the overall system yet

dapper cloud
#

So im probably gonna use that

formal egret
next walrus
#

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

fresh salmon
#

That would be base cost + (increase cost * levels)

#

Ah wait, no, the cost increases per level

devout hare
#

the total spent is levels * base cost + (levels * (levels - 1)) / 2 * increase cost

fresh salmon
#

Yep that's more like it

next walrus
#

amazing, thanks you so much, this was giving me an headache

#

im trying to understand why its working, whats going on in (levels - 1)?

devout hare
#

math ¯_(ツ)_/¯

#

sum of n integers is (n * (n + 1)) / 2 but the base cost means you only need to count to n-1

next walrus
#

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

obsidian glade
# next walrus cool stuff, still trying to wrap my head around it but i sorta get it

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

jolly token
#

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

jolly token
#

I mean it is slower but not like too slow to afraid about

undone coral
#

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

fading quiver
#

Through Menu UI, I would like to catalog different materials that I can make an object in the scene

timber palm
#

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

sly grove
#

Well is it crashing or freezing?

jolly token
#

Try not to make it more complex than it should be. You can always pass extra arguments on DiContainer.Instantiate from factory

tulip lichen
#

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.

tulip lichen
#

Rolled back away from 2023.1.0a24 to 2022.2.1f1, now works fine without issues

kindred tusk
#

Or did it happen when you upgraded unity?

tawdry eagle
#

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 )

jolly token
#

Not for factories

#

Sure something like that

tender solar
#

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.

tawdry eagle
# tawdry eagle Is it possible make a script that generates a bitmap texture and modifies it dur...

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!

celest mica
#

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

coral folio
coral folio
# celest mica 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.

celest mica
#

Thanks for the answer, really appreciated
Does unity have an URL handler?

#

can't find it

coral folio
stuck onyx
#

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

coral folio
stuck onyx
#

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

tulip lichen
urban warren
#

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?

sage radish
urban warren
sage radish
# urban warren Oh, you know what I think it could. But in case I come up with something that ca...

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.

urban warren
#

Yeah, my thinking was to check the jobHandle.IsCompleted in a component Update method

empty shell
#

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.

fading quiver
#

good evening everyone. i created a thread, if anyone is willing to take a look. i would be really grateful 🙏 "Through Menu UI ecc"

humble valley
#

Hi, could someone recommend some resources to start learning how to make custom renderer features, and shaders?

gentle topaz
#

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)

empty shell
gentle topaz
#

make an extension method

jolly token
empty shell
#

Thank you @gentle topaz and @jolly token !

random shell
#

Need help!

Somehow not a single collider works in my project and the "Edit Collider" Button is missing - how can i fix that?

misty glade
#

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?

jolly token
misty glade
#

Yeah I might do something like 4 finger touch & hold

#

I didn't wanna mess with anything showing up in the UI if possible

jolly token
#

I mean you are gonna disable the feature on release build right?

misty glade
#

Yes (and I hope to not forget this) :p

jolly token
#

Do #if DEBUG before forget 😄

misty glade
#

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

jolly token
#

Probably

misty glade
#
#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

frosty summit
#

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?)

obsidian glade
urban warren
#

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.

misty glade
frosty summit
misty glade
#

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).

spare mural
#

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?

spare mural
jolly token
spare mural
#

ah so just updating Unity should fix it?

#

will do 👌

jolly token
small torrent
#

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;
    }
}```
tawdry mirage
#

anyone here have exp with static batching in runtime ?. i tried to do it but not work ...

spare mural
white bronze
#

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?

idle pilot
#

@timber flame so, are you trying to replicate the screen you showed?

#

Or will you be able to zoom out tenfolds?

stuck onyx
#

anybody using apple cloudkit? I'd like to make sort of a group with people using it to share knowledge

timber flame
#

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...

▶ Play video
stuck onyx
timber flame
stuck onyx
#

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

#

😄

timber flame
#

All games are duplicated

#

😱

stuck onyx
#

yeah it was just a comment not a critique

#

just gave me vibes thats all

timber flame
#

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

frail kestrel
#

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.

idle pilot
#

the gpu can handle millions of vertices

timber flame
#

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?

fallow dune
#

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 ?

fresh salmon
#

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

frail kestrel
# fallow dune super curious, I want to pass an argument via a c# event. Example: I have an e...

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 😄

fallow dune
#

🥹 thanks for the help!!

fresh salmon
#

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

fallow dune
#

I want to go the pure c# event route. Less clutter in the inspector

#

I wonder if overloading applies to delegates.

fresh salmon
#

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

fallow dune
#

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.

fallow dune
#

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

fresh salmon
#

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

fallow dune
#

That's a cool idea.

#

I am rather new to SO's events and delegates but this will really come in handy. Much appreciated

urban warren
fierce oracle
#
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

jolly token
fierce oracle
jolly token
fierce oracle
#
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()

jolly token
fierce oracle
#

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()

jolly token
fierce oracle
#

hopefully it will work now

jolly token
#

ScriptableObject is a persistent (in editor) asset and shouldn't really rely on it's lifecycle events

solar nacelle
#

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?

coral reef
#

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

olive python
#

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.

misty glade
misty glade
# olive python Gotcha. The question I wanted to know is if I have a script that is reference by...

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).

misty glade
# olive python Gotcha. The question I wanted to know is if I have a script that is reference by...

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.

little sluice
#

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.

olive python
#

Header

little sluice
little sluice
misty glade
olive python
misty glade
little sluice
jolly token
little sluice
#

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
little sluice
little sluice
#

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.

Gist

GitHub Gist: instantly share code, notes, and snippets.

burnt egret
#

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;```
jolly token
#

With coroutine

burnt egret
#

oh neat! thank you

brisk pasture
#

also is there ever a case where its that instant, and you can not just listen to Completed?

burnt egret
#

im not sure, ive had weird erroneous errors when not doing async localization stuff

fresh salmon
#

For completeness, if you use async/await pattern (warn: not supported in WebGL)

string result = await LocalizationSettings.StringDatabase.GetLocalizedStringAsync(...).Task;
burnt egret
#

i want to incorporate that more into my style

brisk pasture
#

would need a method that returns a Task for that and is async

burnt egret
#

my only trouble is that i struggle to figure out how to fit it in with the regular crowd like Update and OnEnable

brisk pasture
#

you can have a async void OnEnable or Update

#

well Update would be harder

#

but you get the idea

burnt egret
#

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!

brisk pasture
#

async does not mean it performs better

burnt egret
#

i mean if you can use multithreading safely it will probably run faster unless you're doing something small

brisk pasture
#

it heavily depends on what you are doing

burnt egret
#

querying a database is prolly a prime candidate for it, thats for sure

brisk pasture
#

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

burnt egret
#

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

brisk pasture
#

still got tools to tell you whats the issue

burnt egret
#

and the deadline is sometime next week lol

brisk pasture
#

will tell you even what functions are the problem, or if its graphical what if its like fillrate or some other issue

burnt egret
#

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

bitter kelp
#

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.

brisk pasture
#

well most algorithms with some smart data structure usage and caching can be sped up a lot

burnt egret
#

Not sure about mirror unfortunately

kindred hollow
#

So is it possible if I have a state machine to store the possible states in a variable?

misty glade
#

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?

undone coral
#

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

misty glade
#

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

undone coral
#

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

misty glade
#

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.

undone coral
#

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?

misty glade
#

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

undone coral
#

yeah

misty glade
#

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

undone coral
#

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

misty glade
#

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

undone coral
#

we can talk about what those problems likely are but it's better to write the test first

misty glade
#

Yeah, that's fair

undone coral
#

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

misty glade
#

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

undone coral
#

hmm

#

is every user a Task?

#

does every users create at least 1 Task?

misty glade
#

this was the origin of this work - a completely random spike and failure

undone coral
#

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

misty glade
#

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)

undone coral
#

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

misty glade
undone coral
#

you can take a look at the spellsource tests for an idea for my opinion of the minimum number of tests

undone coral
misty glade
#

cool, this is interesting

#

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!

undone coral
#

lol

#

java has a lot of testing tricks

misty glade
#

yeah I gotta get around to doing proper testing and benchmarking instead of my current ad hoc approach

#

"apply more hardware"

undone coral
#

well

misty glade
#

actually more importantly - i'm chasing ghosts since I don't actually know the failure points right now

undone coral
#

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

misty glade
#

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

undone coral
#

your test should not start a unity binary

misty glade
#

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"

undone coral
#

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

misty glade
#

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

undone coral
#

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

misty glade
#

Fair enough

#

OK back to work! (btw launch date on/around feb 6.. it's crunnnnnnnnch time)

true cosmos
#

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)

muted root
#

Is there a way to force start or awake to trigger even when the object is disabled when the scene loads ?

jolly token
true cosmos
jolly token
#

Easier to manage that way imo but up to you

flint sage
#

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

undone coral
#

why are you you using gitlab? what does the package do and what do you want to test?

true cosmos
#

gitlab is just my company policy and there are playmode and editmode tests simply

undone coral
#

what does the package do?

#

it looks like you've been asking about this for a while @true cosmos

true cosmos
#

its just backbone for a lot of projects

#

some base prefabs, scripts and assets

undone coral
#

okay, and what do you want to test

stuck onyx
#

@undone coral do you know something about custom preprocessor directives?

arctic lake
#

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

stuck onyx
#

could i write a short doubt about it?

#

well is just

undone coral
#

shoot me with it

#

shoot me in the face with it

stuck onyx
#

hjahahah

#

if i do #define NAMEOFMYCUSTOMCLAUSE

#

does that mean that one is true?

#

i mean....

undone coral
stuck onyx
#

i build the game in 3 different modes which i set using a ScriptableObject

#

Debug, Beta, and Release

undone coral
arctic lake
#

Thank you

stuck onyx
#

i would like to depending that value in the SO

undone coral
#

okay

stuck onyx
#

'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....

undone coral
#

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

stuck onyx
#

the only one who prevents that is UNITY_EDITOR as i am aware?

undone coral
#

i actually do this for appmana

undone coral
stuck onyx
#

which field?

undone coral
#

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

stuck onyx
#

but with that i can avoid certain chunks of code to be included in builds?

undone coral
#

yes

stuck onyx
#

well... its admin features i would not like the users to end up accessing to them in any concept

undone coral
#

that lets you create custom stuff

stuck onyx
#

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

#

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

undone coral
#

you can't do that

stuck onyx
#

shit

undone coral
#

it either exists or it doesn't

stuck onyx
#

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

undone coral
#

yes

stuck onyx
#

okay that seems easy

undone coral
#

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

stuck onyx
#

i understand the concept but no idea how to do it

undone coral
#

okay

stuck onyx
#

asmdef its another assembly as i understand

undone coral
#

make it "alive" by declaring [RuntimeInitializeOnLoad] on a component inside of the assembly. observe now that code runs when the player starts.

stuck onyx
#

yeah first i'd need to separate this 'admin functions' into another assembly right

undone coral
#

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
stuck onyx
#

oh i see

undone coral
#
  • use the inspector on the asmdef (the asmdef settings) to only include the assembly if a scripting define is set elsewhere
stuck onyx
#

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

undone coral
#

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

stuck onyx
#

actually is not super critical but...

#

better leave it out yeah

undone coral
#

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."

true cosmos
#

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

undone coral
true cosmos
#

😛 cool joke i admit 😛

undone coral
#

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

true cosmos
#

it just doesnt matter. Just testing package seems like generic topic to me 🙂 i plan to work a lot on custom packages

undone coral
#

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?

true cosmos
#

i dont get it

undone coral
#

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

undone coral
#

anyway that's what it sounds like it is. what is the game? is it a pay to earn game idea?

hushed sparrow
#

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);
        }
sly grove
#

that's nonsensical

tropic stag
#

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?

sly grove
tropic stag
# sly grove 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.

sly grove
#

sorry I'm not super clear on the details of what you're trying to do tbh

tropic stag
#

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.

undone coral
#

are you trying to say you want to debounce some commands?

#

okay, it sounds like you are using state machines, when you should not 🙂

sly grove
undone coral
#

when you say "animating for a couple frames and in that state they ignore other input"

sly grove
#

rather than the objects all subscribing to different queues/events

undone coral
#

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

tropic stag
sly grove
undone coral
#

if you could be more specific

#

i can write an example

#

a nice thing about unirx is it's really succinct

tropic stag
undone coral
#

Amb Buffer and Window are operators from ReactiveX (which unirx is like a library for, with unity bonuses)

tropic stag
#

@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)

undone coral
#

etc to detect circular motion
so would an idea be
to rotate the piece, the player

  1. moves the joystick from neutral to a fully extended position
  2. 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
  3. cancel the rotation when the joystick is released back to neutral position
#

or do you mean

#

to rotate the piece, the player

  1. moves the joystick from a neutral to fully extended position
  2. the direction pointed to by the joystick is now the orientation of the piece
  3. moving the joystick orients the piece in its direction
  4. rotation is canceled when joystick is back to neutral
tropic stag
#

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.

undone coral
#

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

tropic stag
#

🙏 just skimming unirx docs looking for examples, but if you have time I'd appreciate a top level "how you'd do it"

undone coral
#

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

tropic stag
#

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)

undone coral
#

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

tropic stag
#

I can already see this is cool, although it would require some practice to get your mind to think in streams like that.

undone coral
#
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;
}
tropic stag
#

(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?

undone coral
#

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);
} 
undone coral
#

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

tropic stag
#

oh, so combine latest everyupdate just collects all the input joystick events that happenned every frame?

undone coral
#

it's a "running reduce"

undone coral
#

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

tropic stag
#

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 ?)

undone coral
#

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

undone coral
#

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

tropic stag
#

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?

undone coral
#

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);
undone coral
tropic stag
#

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...

undone coral
#

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

undone coral
#

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

tropic stag
#

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?

undone coral
#
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);
flint geyser
#

How to access Unity's API when I am in another thread created by UniTask?

tropic stag
#

(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))

undone coral
#

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

tropic stag
#

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)

undone coral
#

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

tropic stag
#

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?

undone coral
#

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

tropic stag
#

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?

undone coral
#

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

tropic stag
#

yeah, so is it possible that the combinelatest ( everyupdate... line, will "miss" some of those mouse events?

undone coral
#

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

tropic stag
#

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?

undone coral
#

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

dense ore
#

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?

undone coral
#

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

undone coral
tropic stag
#

@undone coral really appreciate this. thank you for the detailed example and explanation!

undone coral
#

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

tropic stag
#

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...