#archived-code-advanced

1 messages · Page 188 of 1

whole quest
silk hare
#

Is it possible to include use the UnityEditor intermediate gui library in build? It would be really convenient for a our server/management application.

flint sage
#

No

compact ingot
#

You probably want some sort of voxel engine or displacement map (heightmap) based terrain

fresh basalt
#

I have a single 2d fighter game and i want to make it multiplayer - 1v1. Should i do it p2p or have a server to manage everything?

undone coral
#

when you say drag and drop objects... you can make rigidbodies non kinematic and also draggable

undone coral
#

if you need a UI for a server application

#

if you need data use prometheus

regal olive
#

Could anyone help me figure out plasticSCM? I've never used version control and I have 10 days left to finish my school game project and I'm dying inside from stress and I cant figure anything. I'd like to understand what merge and diff means and how to revert a changeset and hand pick only several things to apply from a changeset. I'd be very thankful.

dusk plaza
#

I am trying to save a RenderTexture into a Texture2D to use in interface, but when converting RenderTexture -> Texture2D, the colors get wrong, the Texture2D is tinted yellow, even though the RenderTexture is perfect in the editor. Anyone know what could be the cause?

tribal pivot
dusk plaza
#

Not sure what you mean, I am making the conversion because the RenderTexture is used to take a screenshot of a building piece, so the same RenderTexture is being used multiple times to take many screenshots to populate the UI

tribal pivot
#

You can just make a new RenderTexture every time

#

And use a RawImage to show the rt in the ui

dusk plaza
#

let me check

#

no

#

another requirement is that said screenshot to be saved to disk

#

and then the conversion will have to happen anyways

#

so there is no getting around it

spice axle
#

Hi Everyone, I have kind of a weird question : I'm making a lot of tools and a bunch of stuffs to make my coworkers' life easier but there something I can't figure.

I understand how Messages Like update, OnTriggerEnter, or Awake work but I have trouble to understand how to implement my own so my IDE knows how to implement it (like in the screenshot)

Does someone have any clues ? I checked in UnityEngine.CoreModule and In the PlayerLoop and I found the MessagingSystem with IEventSystemHandler but i would like to implement something without to have to make my classes inherits from an interface.

Thanks a lot

compact ingot
#

messages in unity are a way to call methods by their name: method != message

dusk plaza
#

Fixed by changing how I create my Texture2D
Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGBA32, false);
to
TextureCreationFlags flags = default;
Texture2D tex = new Texture2D(rTex.width, rTex.height, GraphicsFormat.R8G8B8A8_UNorm, flags);

spice axle
#

Yep that's what I thought too but in searching in the source code for monobheaviour I didn't saw any trace of an interface or of a method named start or update same for component and object

spice axle
fresh salmon
#

And yeah, it's the extension that comes when you install the Unity workload in VS, that provides those method completions.
Outside of Unity that isn't a thing, apart from when overriding

#

If you want something like that you'll have to make your custom extension as a VSIX others can install

peak copper
#

Hey i need help with raycasts in my 2d Project. Can someone maybe help me overlook my code?

tribal pivot
peak copper
#

ok sry

wide violet
#

hey i want to instantiate a first person character and got everything working except the camera, i cant seem to get the camera to attach

#

anyone can help?

modest lintel
#

certainly not with the amount of information provided

wide violet
#

i am using the advanced fpc asset and the main character uses a pov camera that is added to the script

#

when i made the player a prefab the camera cannot be called and does not attatch

#

i am trying to attach the camera via code but do not know how

#

i tried getComponent but cant seem to get it to add

#

i made the camera a prefab as well and that does not work either

modest lintel
hollow stag
#

Can someone help me create an infection script (when the infected player touches a non-infected player and they become infected, once all are infected the round restarts with a new infected player)

formal lichen
torn patrol
#

hey, if anyone is experienced with Mono.Cecil I'd like to ask one question

#

having RuntimeInitializeOnLoadMethod attribute on static method with an argument causes Failed to resolve assembly: 'UnityEngine.CoreModule' error, while having none, does not. what could be the cause

formal lichen
#

wait does CECIL let you modify DLL's and save changes within your project using the DLL?

hollow stag
formal lichen
#

did you install infected.dll?

formal lichen
#

that sounds like a useful feature for my workflow instead of opening up a second solution and building the DLL's and dropping them in

tall trail
#

hi, im doing a project with some tiles and i want them to become green when they are in the correct position, at the start of the game they are green but if i move them and put them back in the correct position they dont become green they stay transparent, what did i do wrong?

fickle mango
red osprey
#

One way to fix this is to, instead of incrementing 5% each frame (not even accounting for delta time), when you start the animation, choose an end time (either Time.time or Time.unscaledTime) and provide how far between the start and end time it is on the current frame.

#
var progress = (Time.time - StartTime) / Duration;
transform.position = Vector3.Lerp(StartPosition, targetPosition, progress);
``` something along those lines
tall trail
hollow stag
#

dm me the link

gray frigate
#

Does anybody have any experience with using socketIO with unity? I'm going out of my mind trying to figure out how to send an auth token and wonder if anyone can suggest a plugin that can actually do it correctly.

undone coral
#

plugin for socket io?

#

socket io is obsolete

gray frigate
#

I'm simply trying to connect to a socket.io server, which I've done successfully using firecamp so I know my path and auth tokens are correct. However, every socketio plugin I look at for unity doesn't seem to provide auth that works, I only ever get "auth is invalid" responses back.

#

this is also my first time hearing socket io is obsolete

undone coral
#

this firecamp?

gray frigate
#

yes

undone coral
#

auth tokens... passed in the query...

#

there's no standard for auth on websockets, are you saying socket.io invented one?

#

you typically use session cookies

gray frigate
#

I'm not saying anything, I'm merely confused because the plugin I linked has a specific way of doing it and it did not work

undone coral
#

i know what you are trying to say (?auth_token=fjidaosjfdiasofj)

gray frigate
#

The app I'm trying to connect to has documentation for a nodejs example, which looks like this:

#

const socket = io('wss://<url-here>', { path: '/third_party/', auth: { token: '<token-here>' } });

stark acorn
#

algorithm for generating a perfect hexagon with small hexagons?

undone coral
#

stuffing something into the URI query params?

gray frigate
#

Possibly, I don't know, because I don't understand socket.io

undone coral
#

you would have to see what that does

#

yeah

#

what is the app?

gray frigate
#

not a public one

#

can't say too much, under nda

undone coral
#

i really need an emoji for that

gray frigate
#

shrugs

#

The thing that's interesting to me is that firecamp lets you see what it's doing through different code and none of them ever include the auth/token part, even though it's required for the connection

#

so it probably is getting tacked onto the uri

undone coral
#

there's a guy who does hexagon grids online

#

as like his obsessive passion

#

have you found his blog?

stark acorn
#

if it's too complicated then I will just use hex tilemap for now

undone coral
#

he's like the foremost expert on grids

stark acorn
#

Adam yeah i will use tile map instead

#

but thanks, i will be reading those in the future for sure

jagged ledge
#

Please help

#

How do i get my ide to show up

humble leaf
jagged ledge
#

Nah bro it is advanced only above average coders know what ide is

#

But thanks anyways

undone coral
#

at least he didn't bruh us

honest hull
#

Hey so if I have 4 bytes packed into a uint32
How do I modify one byte of that without converting anything back to bytes?(so it can be done on the GPU)

regal olive
#

Definitely not advanced

jagged ledge
#

This is ide

#

I don’t know how to add it

tribal pivot
jagged ledge
#

Bro it doesn’t work

#

I don’t know where to find Common7 file

regal olive
jagged ledge
#

Nah bro only pros can know that they don’t have ide

regal olive
#

Stop trashing this chat just watch a tutorial on YouTube there’s literally hundreds of them

jagged ledge
#

I’m not trashing i watched on youtube non of them tell me how to get ide

regal olive
#

There no point of trying to prove that IDE is something for advanced coding

#

They do, they did to me clearly

jagged ledge
#

I downloaded visual studio code yesterday

regal olive
#

Alright I’ll ignore

jagged ledge
#

And i watched the man who teaches how to code

#

I saw he had a drop down below

thin mesa
jagged ledge
#

Oh thanks bro

#

You’re the real man

thin mesa
#

(this is information you were already provided by the way)

jagged ledge
#

Oh

#

I musta been on something back then

vagrant gulch
honest hull
ionic badger
#

Hey, so Im an old school C++, C# game developer from back in the day (90's-early 2000's) What would be a good channel for someone like me who is new to Unity?

jagged ledge
#

Bro ide doesn’t work

#

I don’t even need it

#

I’m just gonna program without it

thin mesa
#

still not an advanced issue, but it is required to have a configured IDE if you want help in this discord

jagged ledge
#

Yea i

#

I think I’m a beginner

#

If I can’t even configure a feature

#

Then tf am i

honest hull
# vagrant gulch You can use bit operations to mask and update the byte you want to modify.

so hang on so is this good for modifying the 4 components of a uint bytewise?

TempBVHNode.node_2x = (TempBVHNode.node_2x & 0xFFFFFF00) |  (uint)(floor((BBMin.x - p.x) / e.x));
TempBVHNode.node_2x = (TempBVHNode.node_2x & 0xFFFF00FF) |  ((uint)(floor((BBMin.x - p.x) / e.x)) << 8);
TempBVHNode.node_2x = (TempBVHNode.node_2x & 0xFF00FFFF) |  ((uint)(floor((BBMin.x - p.x) / e.x)) << 16);
TempBVHNode.node_2x = (TempBVHNode.node_2x & 0x00FFFFFF) |  ((uint)(floor((BBMin.x - p.x) / e.x)) << 24);
vagrant gulch
honest hull
#

how I do that? again ive never done something like this before, but I know that rn its not returning the right results

#

ok I think I see what your saying

#

(TempBVHNode.node_3z & 0xFFFFFF00) | ((uint)(ceil((BBMax.y - p.y) / e.y)) & 0xFFFFFF00)
this?

vagrant gulch
honest hull
#

problem is this is returning exactly 1 from what it should be

#

oh!

vagrant gulch
honest hull
#

ok thx

#

ill try and get it working but idk
hate that I cant send and modify bytes to the GPU

#

((uint)(ceil((BBMax.y - p.y) / e.y)) << 8 & 0xFFFFFF00)
so do I want this << 8 before or after?

vagrant gulch
#

After. You'll need to invert your mask too.
Basically what you want is:
value & 0xFF to select the lower 8 bits. Then << 8 to move the lower byte up one.

honest hull
#

ok

#

hrm im trying on the lowest one and I keep getting wildly different values than I should...

vagrant gulch
#

If you mask first and then shift you can use the same mask on all of them because you're getting the lower 8 bits of each result and then putting them into your destination byte.

#

Hmm, can you paste the code for that line?

honest hull
#

TempBVHNode.node_3x = (TempBVHNode.node_3x & 0xFFFFFF00) | ((uint)(floor((BBMax.y - p.y) / e.y)) & 0xFFFFFF00)

#

checking all my inputs now but its annoying cuz gpu

vagrant gulch
#

Change the last 0xFFFFFF00 to 0x000000FF. (I assume you want the first byte of the computation with bbmax).

honest hull
#

WAIT THAT WORKED

#

well I also had to change the (uint) to asuint

#

wait no it doesnt work everywhere

#

wait no it is working holy hell thank you so much

#

time to copy it and test it

vagrant gulch
#

👍 if some of the bytes seem to work and others don't then I'd double check all the masks and shifts first.

honest hull
#

nope! they are working!! thank you so much! youve saved this for me!

#

nevermind.... sigh

torn patrol
stuck onyx
#

if you would like to use Coroutines in a non monobehaviour class how would you do it? i've seen passing a monobehaviour as parameter but I wonder if wouldnt be easier to have some sort of CoroutineService you can call from wherever you want an launch coroutines

compact ingot
stuck onyx
#

I guess ill take the second... thanks a lot

silk hare
#

I have a bunch of global manager classes that need to be instanced at application startup; in unreal engine this would be done with the game instance - does Unity provide a similar way to have application lifetime classes, meaning not related to any scene loads and destruction?

#

Is DontDestroyOnLoad really the only tool here?

tribal pivot
#

Does it need to be a Unity object?

torn patrol
#

@silk hare

[RuntimeInitializeOnLoadMethod]
public static void OnLoad() {}

you could use this attribute with static method and it will get ran on startup, once for a class (you could pass an argument as well if you want to specify when you want it to run, like before splash screen of example). from here how you tackle with the problem based on your use case. you could instantiate an object and make it DontDestoryOnLoad, or create a class and hold static reference of it...

plucky laurel
#

^ +you can inject your update callbacks into the playerloop to be completely independent of scenes

hybrid plover
#

I don't really know where to put this since there is no general 'help' channel.
My build sometimes crash after a while. When I check my build log I get this error. Can anyone tell me why this is happening?

fresh salmon
#

The general help channel is #💻┃unity-talk, even if the name doesn't suggest it.
Looks like some internal Unity issue. Restart your computer, if that doesn't solve it repair your install. If that doesn't solve it report the bug and attach the log as indicated

plucky laurel
#

lol

silk hare
silk hare
torn patrol
#

it will automatically

#

@silk haretry it, debug.log and see when and if it gets run

tribal pivot
silk hare
hollow stag
sullen harness
#

ok so I dont know if this is considered advanced code but im trying to make a enemy that crawls up and down a wall but not the ground

torn patrol
sullen harness
#

what im asking is that can I just take the AI of a crawler enemy I have and change the borders?

shadow seal
#

That's so vague, how would we know your implementation of a crawler AI?

sullen harness
#

im sorry but im not that much of a coder im kind of using a 2d toolkit I found online as my template

steep robin
#

hi I want to be able to download a unity package from github

#

I created the repo on GitHub

#

then I try to add the repo reference into unity, but it fails

#

there is some convention to respect in order to make the package "installable"?

tribal pivot
#

it fails why

austere jewel
steep robin
sage radish
#

Do you have a package.json file in the root of your repo? If not, the documentation vertx posted has everything you need.

tribal pivot
steep robin
#

within manifest.json and packages-lock.json

sage radish
#

Sounds like your repo is of a Unity project. A package is not a Unity project.

steep robin
#

actually I would like to have a separate repo for this code. should I create a new repo only for the package?

hexed meteor
#

What could be causing a spherecast to ignore the provided layermask ??

flint sage
#

Your layermask is wrong probably

hexed meteor
#

It isn't :[

obsidian glade
#

I can't remember if it works when it starts inside and then exits, perhaps it will only fail to detect it when the entire cast is inside

sage radish
obsidian glade
#

Hoping someone can give some insight on async/await and how it works within Unity, especially in regards to performance - I have a test project set up which spawns 100k objects with this MonoBehaviour script on them: https://gist.github.com/Deynai/09fb0f0ff7e6d3bf7a62505275bab23a
The idea is when the the timer object is created it starts an async timer which periodically calls a function on an interval, in this test it's a simple calculation that's updating a field on the object. I'd like to have a lot of these objects running simultaneously in a performant way, each with their own timers.
With this async/await test though I'm getting these huge spikes with GC allocations under UnitySynchronizationContext - see pic. For comparison just having 100k objects running this with their own Update() method is a consistent ~25ms a frame.
Is this a problem inherent with async/await not being good for performance in general, with Unity, or something else?

hexed meteor
#

@sage radish It is serialised. It literally only has the default layer checked. so the layermask is definitely not the issue.

mint sleet
#
    protected override IResult OnBefore(IInvocation invocation)
    {
        var roleClaims = _httpContextAccessor.HttpContext.User.ClaimRoles();


        foreach (var role in _roles)
        {
            if (roleClaims.Contains(role) && !string.IsNullOrEmpty(role))
            {
                return new SuccessResult();
            }
        }
        
        return new ErrorResult(Messages.AUTHORIZATION_DENIED);
    }
#

how can I throw an exception with an object?

obsidian glade
mint sleet
#

it throws with a lot of garbage information

#

I want to return just this : "authorization is invalid" or somethin

#

@obsidian glade

obsidian glade
#

you can add a string parameter to describe it, or maybe Debug.LogError() is more what you're looking for?

torn patrol
kind flare
#

Is there anyone who has time to help me with steamworks/mirror leaving lobby and host migration? I've been stuck on this for 5 days now and I can't find anyone who wants to help me out with it :/

tribal pivot
scenic forge
#

async/await is a tradeoff, for your example yes an update function would be cheaper.

#

Also move your cancelling to destroy instead of finalizer.

#

If you are looking to do 100k objects, you may not want to use MB at all, ECS is a much better fit

#

Depending on how complex the 100k objects are, you can get away with just rolling your own quick and dirty ECS with Burst and get massive performance comparing to anything MB can dream of.

obsidian glade
obsidian glade
#

I did a rough test using some ECS concepts, not even using Burst, and performance-wise it's waaay better than individual MonoBehaviours - I'm just surprised the async/await behaved so poorly, dramatically worse than MBs even

#

I've been meaning to check out UniTask for a while so I'll give that a go and see how it compares

foggy vigil
#

Hey, random weird question. Can I inherit from GameObject? And instance those insteado of empty game objects? has anyone tried doing something like this? What could be potential problems with doing this instead of only adding functionality through monobehaviours?

formal lichen
#

GameObject is a sealed class so no

round blade
#

Apologies for cross-posting I am being blocked at work by this issue

scenic forge
patent zodiac
#

hmmm

I've got 2 things - A reload animation, and a reload animation circle as shown here

#

however, for some reason, the reload circle animation takes around 20% longer than the reload animation

for the circle animation, I have a green rectangle, and then a Mask rotates itself until the green rectangle is fully shown. Then, I simply make a clone of the green rectangle, offset its rotation, and do the entire thing over again. In total, it takes 72 iterations to complete the circle animation

anybody know why the display circle is slower than the other?

shadow seal
#

Why don't you just make the circle quicker?

patent zodiac
# shadow seal Why don't you just make the circle quicker?

I did, and it works as a solution, but it still doesn't answer the question why because if it happened in one area of my programming, it could happen in another area, and I want to know if its a problem with my programming logic or a limitation of computers, or whatever the problem is

shadow seal
#

A limitation of computers? I just think you put the wrong delay

vagrant gulch
#

How are you animating both of them? As in, how are you stepping each update, and what is it that should be keeping them in sync?

patent zodiac
shadow seal
#

I wonder if your animation has some extra frames

patent zodiac
vagrant gulch
#

Are you using delta time in your coroutine or stepping a fixed amount per iteration?

patent zodiac
#

for the Mask anim, I use time.delta time, but the mask is animated in a separate coroutine. The main coroutine uses yield return new WaitUntil(() => Time.time - StartTime >= Interval); to determine when the next iteration should happen

vagrant gulch
#

It's hard to know what's happening without seeing the full routine. Is start time set to the current time when the coroutine runs? Is interval a constant? If so then it will get out of sync because more than Interval time can have passed.

patent zodiac
#

Also do you want me to copy and paste here the full routine code?

vagrant gulch
patent zodiac
#

AddProgress() just returns an instantiated gameobject btw

next iris
# patent zodiac

this is the part that goes out of sync right? (and its only controlling the circle animation right?)

vagrant gulch
#

Looks like it's going out of sync for the reasons I stated above.

patent zodiac
#

yes

#

but, if that's the case then how would I go about re-syncing it every time it goes out of sync?

#

ohh i think I just had a eureka moment

vagrant gulch
#

I think this is more complex than it needs to be. You could pick a start rotation and end rotation and lerp your quaternion between them every update based on time passed.

patent zodiac
#

my code only checks for when the difference in time is >= Interval, but if its greater than the Interval, my code does nothing to compensate for the next interval value

vagrant gulch
hybrid plover
#

Anyone that has experience with Graphics buffers and VFX graph? I try to get my vertex buffer from a certain mesh, and then get the vertex position in the vfx graph but once I play, nothing shows up. anyone that can point me in the right direction?

obsidian glade
#

or 71 even

patent zodiac
obsidian glade
#

curious

patent zodiac
#

Hmm, what’s weird is that if I add in the offset check, it cuts the error from around 20% down to 10% but if I don’t add the offset check and instead just decrease the Interval by 20% it gives me a MUCH smaller error, like <5%

vagrant gulch
#

It seems likely that your guess was more accurate than your offset check. I wouldn't use coroutines for this though, I think you're making more work for yourself compared to computing your rotation every update.

patent zodiac
undone coral
#

for how to do this

#

you can also use the property binder i think

undone coral
hybrid plover
undone coral
#

ah i see

#

yes you will need to set it through code

#

but if you're using it to get the mesh

#

i think there's an example of that in the vfx graph samples

obsidian glade
#

in fact it looks like they explicitly recommend not using them at all

undone coral
#

async await isn't about multithreading

#

unitask has easy ways to run stuff on the thread pool

#

what is your objective?

obsidian glade
obsidian glade
sage radish
candid drum
#

Why can I only use the Instantiate() method inside of Start() ?

#

I would like to use it elsewhere, but the IDE will not recognize it

hybrid plover
somber swift
candid drum
# somber swift Have you tried in Update?

I am trying to use it inside a custom function which is called from inside start(). I just thought it was interesting this wasn't a common problem, I wasn't able to find any info about it online

somber swift
sly grove
livid fulcrum
#

Is there a problem with stacking multiple masks on top of each other? I have a minigame that has multiple layers of masks, but for some reason the gameobjects are only visible if it is on the first or front most mask. If I try to assign no mask or a mask behind the first, the object is not visible. I know that it still exists because I can see the transform values in the console.

#

I have tried quite a few things to try and troubleshoot it but I am now running out of things I can think of to try

#

Some things I have tried: Disabling the mask in front to see if it is visible (not visible), setting no mask at all (not visible), setting the object as part of the first mask (visible), setting the object as part of the second mask (not visible)

#

Any other things I could try to troubleshoot it?

robust citrus
#

i just upgraded my project from unity 2020.3 to 2021.3, and i'm getting a bunch of Assertion failed on expression: 'm_WriteObjectAccumulator.empty()' and The serialized array of [SerializeReference] objects is missing entry for Refid X errors. anyone seen this before? not seeing any info about it online really.

viral flame
#

Anyone know offhand if the navmesh builder has some maximum number of sources that it can build from?

I'm trying to fix an issue with the nav mesh surface component (which is modified to generate sources from terrain trees/colliders) and bake the terrain trees in, and it works fine on trees in my test scene where there are fewer of them, but in the main scene where I have many, it seems to miss some.

I've played with voxel and tile size and it doesn't seem to make a difference, any ideas?

#

NVM, I sorted it out, it was sillier than I realized, some of the colliders where just barely too short for it to "collider" with the generated mesh, so it wasn't getting "cut out" of the navmesh, just doubling the hieight of them fixed it.

undone coral
#

with unitask, you would use a helper that ties the lifetime of the async task to the lifetime of the game object.

#

it is better that way

hollow stag
#

how do i make like a 1v1 tag system when if you get tagged you turn red and you go back to normal

undone coral
#

maybe start with pre-existing samples or tutorials

#

you can aspire to do a local multiplayer game like this

hollow stag
#

i’ve been looking for eges

#

ages*

honest hull
#

hey so I use an array of bytes 4 long, given by (byte)value, and BitConverter.ToUInt32(bytearray, 0) to convert that into an uint
leaving me with the uint
now, I need to modify the uint constructed, but instead of using 4 bytes, I need to use 4 uints, of the same values as the bytes when using Debug.Log on them(so instead of (byte) I use (uint)), how do I do this? this is driving me nuts that I have been unable to do so, and especially since its the last hurdle in this part of my project

warm shale
#

I've been looking up how to send messages between gameobjects, and have found no working code. does anyone know how to do that?

compact ingot
honest hull
#

ive been struggling to modify bytes in a uint for a few hours now, I keep getting incorrect reseults and idk why

undone coral
#

okay i gotch you

#

don't overthink this

#

are you trying to flip specific bits?

honest hull
#

no
I have 4 bytes packed into a uint
I need to modify that uint with a new uint

undone coral
#

it's not clear what you mean by " I need to use 4 uints"

#

but what does that mean

#

modify

#

modify a uint with a new uint

#

super concretely

#

you're stressing out because this makes no sense lol

#

use the right words for things

#

and you're sophisticated so i'm sure you're trying to do something legit

#

debug.log on them... it's so confusing

#

what are you saying

#

just show me what you are trying to do

#

show me your code

honest hull
#

replace a byte in a uint with another uint that has the same value as the origional byte

undone coral
#

no

#

stop

honest hull
#

ok

undone coral
#

you can't replace a byte with a "uint"

#

lol

#

are you trying to say you want to pack 4 bytes into a uint?

honest hull
#

trying to use a uint as a byte(cuz gpu doesnt have bytes)

#

yes

undone coral
#

that's fine

#

okay first

#

you can cast uint directly to byte as step one

#
uint v = some number 0 <= x <= 255
var b = (byte)v;
#

this will just work

#

a byte is also a System.UInt8

honest hull
#

ok

undone coral
#

now to pack those four bytes into a uint there are many ways

#
// there are more succinct ways to do this but for helping
// us all understand
var b0 = (byte)value1;
var b1 = (byte)value2;
var b2 = (byte)value3;
var b3 = (byte)value4;
var packed = BitConverter.ToUInt32(new [] {b0, b1, b2, b3});
#

you could also bit shift the bytes, that will Just Work and is more common

#

does that make sense?

honest hull
#

yes
im doing bit shifting

#

using this to get the bytes from a uint

byte byte1 = (byte)(Data & 0xff);
byte byte2 = (byte)((Data >> 8) & 0xff);
byte byte3 = (byte)((Data >> 16) & 0xff);
byte byte4 = (byte)((Data >> 24));

and this to get uint from bytes

(uint)(byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24));
#

oh and I suppose, this is what I use to set a new value to one of the bytes

            if(NodeOffset == 0) {
                byte1 = InData2;
            } else if(NodeOffset == 1) {
                byte2 = InData2;
            } else if(NodeOffset == 2) { 
                byte3 = InData2;
            } else {
                byte4 = InData2;
            }
  

with nodeoffset being the byte I wanna modify

undone coral
#

you're overthinking this

#

big time

honest hull
#

its cuz ive been at this for 7 hours now, its gotten more convoluted

#

as solutions continuously dont work

undone coral
#

it's because you implemented your bytes from uint wrong

#

but it doesn't matter

#

just use the example i wrote

#

in the dotnetfiddle

#

i mean

#

it's all got problems

#

you can look up the source for bitconverter's methods

#

to see how to implement this in your compute buffer

#

is that example helpful @honest hull

honest hull
#

kinda yeah
thank you
but I have tried using just bitconverter things but that also doesnt work

#

I wouldnt be bothering with all this tho if I could send structs with arrays of bytes easily to the GPU

compact ingot
honest hull
#

yeah there has to be at this point...

undone coral
#

the example code is bulletproof

#

did i send you the wrong thing or something?

honest hull
#

I know so idk whats going wrong at this point
its basically the same as previous code that does work, just using modifification instead of full on replacing

undone coral
#

no

#

look at my dotnetfiddle

#

does this serve your needs?

#

stop looking at your code because it is flawed

#

help me understand what your goal is

honest hull
#

I converted to your code yes

undone coral
#

okay

#

structs with arrays of bytes easily to the gpu

#

i feel like someone has discussed this already using marshalling

#

people marshal compute buffers all the time

honest hull
#

wait really????

undone coral
#

it's

buffer =
 stride 0....L = struct size
0bbbbbbbb
1bbbbbbbb
2bbbbbbbb
...
Nbbbbbbbb
#

yes

honest hull
#

oh wait but that required setting a bunuch of stuff to unsafe and thats not smoething I understand yet

undone coral
#

you have to start reading source code

honest hull
#

yeah

honest hull
#

thank you so much

undone coral
#

even simpler example

#

@honest hull that's setting vertices

#

how did i find this?

#

i use grep.app and searched ComputeBuffer

#

you must master finding existing source code

honest hull
#

woah I had no clue about htis!

#

tho wait in the last linnk, vertices struct doesnt contain an array, thats what im lookin for

#

trying to avoid using fixed cuz that requires the struct to be marked unsafe which requires all uses of it in any functions to have those functions also be unsafe, and theres a LOT of functions

gray frigate
#

I'm using NuGet to grab a plugin I really need but the plugin has a few dependencies, one of which is System.Text.Json.6.0.2, which produces a ton of these kinds of errors because it has 26 languages containing the same file in each folder:
Multiple precompiled assemblies with the same name System.Text.Json.SourceGeneration.resources.dll included on the current platform. Only one assembly with the same name is allowed per platform. (Assets/Packages/System.Text.Json.6.0.2/analyzers/dotnet/roslyn4.0/cs/ru/System.Text.Json.SourceGeneration.resources.dll)
How am I supposed to handle this? Deleting the files just causes other errors to crop up due to the dependency being missing

rocky mica
#

Yo, question, is there any way to disable some soft castings in Unity/C#?

#

I have some functions with default values, and one of them is a a bool followed by a gameobject

#

by mistake you can pass the gameobject as the bool parameter and the compiler wont complain due to the gamobject > bool soft casting

#

I dont think i have ever seen a sane piece of code that uses that type of casting or anyone using it so I wanna disallow it lol

unkempt nova
#

Did you accidentally generate an operator based on a suggestion from your IDE?

rocky mica
#

I just really, really, really, dont want that behavior

unkempt nova
#

Oh, you mean something like if(!gameObject)?

rocky mica
#

yup!

unkempt nova
#

Didn't know > worked

rocky mica
#

it's deff a thing

unkempt nova
#

Pretty sure that's an operator defined by Unity, so pretty sure you couldn't turn it off

rocky mica
#

tbf thats how other languages works, usually checking for bool of an objects works in c or c++

#

I just hate it here lol

#

I lost like 5 hours of debugging to it

final heath
#

is there any way to make voice recognition where i can say agruments like "Make cube (here you say a color it will make it)"

unkempt nova
#

Yes

final heath
#

yea like i know how to make just voice commands but its the argument i dont know how to make

ocean igloo
#

Hi!
sooo ammm
I have a list of c# Type and interface references
When unity does an assembly reload in play mode all of these are lost

#

is there any way to persist them or should i just disable playmode reloads?

granite viper
#

playmode reloads suck

#

best to disable them

ocean igloo
#
[Serializable]
class Refs{
  Type type;
  Iface @ref;
}
List<Ref> refs;
#

this is the basic of what I have

granite viper
#

yah playmode refresh has never been good

meager kite
#

Is it possible to see which segments ot code cause the most lag? I need to optimize stuff and idk where to begin

humble onyx
meager kite
#

Thanks

novel wing
modest valve
#

So, I am making a MP game, and it has a project for the server and one for the client (two separate unity projects). And I want the client game to be able to host a server, which right now requires a separate .exe. How do I go about this? I want to open it, be able to send messages to it, and close it. (I currently can just start both .exe's and it works fine, i just want it to be a bit more user friendly)

granite viper
#

use the C# Process API

modest valve
#

Is it possible to make it run in background?

#

or just make sure it does not pop up on your screen

mint sleet
#

Hello Folks!

#

I have an API to register a restaurant, for example.
Should I make a Bulk API to register hundreds of them in one go? Or should I make Async and call the async API hundreds times instead?

#

What would you have prefered?

granite viper
modest valve
#

And can I send messages to it?

granite viper
supple magnet
plush lion
#

Hey, I need to make a ragdoll out of a character I download at runtime. The thing is the ragdollBuilder called when I do create3DObject->Ragdoll is not callable from a script, only from the editor. Does anyone knows of an elegant way to create a ragdoll at runtime ?

foggy dew
#

im working on material property block i set this code in start method but still instancing materials

#
        {
            int i = 0;

            foreach (var flower in rend.materials)
            {
                Color.RGBToHSV(flower.color, out float H, out float S, out float V);

                flower.color = Color.HSVToRGB(H, S, 0.2f);

                materialPropertyBlock.SetColor("_Color", flower.color);
                rend.SetPropertyBlock(materialPropertyBlock, i);

                i++;
            }
        }```
#

do you have any idea where im wrong?

sly grove
#

Use rend.sharedMaterials if you don't want that

foggy dew
#

but is there something wrong with this

#

materials doesnt work but sharedmaterials work

#

like any disadvantages or smth

sly grove
# foggy dew like any disadvantages or smth

Changing the shared material affects all objects using that material. If you use materials you get a fresh copy just for that object so your changes only affect that object

glacial geode
#

hey guys, im trying to get the shortest quaternion angle difference between current and target i saw online about a type for Quaternion.Inverse(Current) * target but that sometimes returns the longest rotation instead

foggy dew
#

it changes but i cant see the changes when i play

shadow seal
#

You asked your question less than 10 minutes ago, it's still visible. Stop crossposting and have some patience

sage radish
glacial geode
#

my issue with that (understanding that at the very least) is the fact this only returns an abstract float in my eyes

#

what is that angle for?

#

is it the x - y - z sum?

#

is it just y?

sage radish
#

It's not Euler. Euler is just one way to represent 3D rotation.

glacial geode
#

i wasnt speaking euler, just didnt mention the w scalar

#

i mean quaternions can have angle differences on all of their properties

#

so why does this return just 1 float?

#

i expected a new quaternion mentally i mean, but probably im over thinking it

sage radish
glacial geode
#

Currently i tried to just convert to eulers, modulo them to -180 / 180 radius (cause like i mentioned previously i was sometimes getting a longer inverse rotation while there was a shorter one near it) and cast back to quaternions

#

but turns out quaternions dont accept negative rotations

#

so it just reconverts it to 0/360

#

also define "how long further", i can tell it directly from the difference between current and target euler differences at first glance

#

when the closest euler rotation is 10 degrees it shouldnt do a 370o spin to reach it

sage radish
#

I think the source of the problem here is that you're using Euler angles. Do you intend to show this value to the user or let them modify it?

glacial geode
#

no im just trying to rotate towards a goal (and euler is easier to debug on my eyes)

#

euler arent used for computation, mostly to tell the rotations

#

and i also just debug the angle to see whats going on

#

is the Quaternion.Inverse(current) * target wrong?

sage radish
#

What I have in my code is target * Quaternion.Inverse(current), which can be reversed with current * difference Actually it seems to be reversed with difference * current, so yours might be more correct.

glacial geode
#

just to be sure i recall correctly

#

the order of multiplication for quaternions is important

#

so whats the difference, well with your angle difference and mine?

sage radish
#

I got to this with trial and error, so I can't answer that

glacial geode
#

okay then back to tests

#

thank you atleast

#

that helped me get some ideas

void hearth
#

Is there a way to make unity events with 2 variables as input
these do not show up in the Inspector

glacial geode
#

where are your events

void hearth
#

on the UI Manager

#

in the UIManager script

glacial geode
#

where? i dont see any such definition

void hearth
#

here you go

#

the test event does show up

#

and if I do a void with only a single(UI_Panel) it does show up too

fresh salmon
#

It's a method

glacial geode
#

thats not the event

fresh salmon
#

Not an event

glacial geode
#

the event is on the script you are trying to assign the method into

fresh salmon
#

And to answer the question, nope, UnityEvents don't support handlers with multiple parameters

glacial geode
#

what about structs spr2? (or just custom classes)

#

he can just hide his parameters there

void hearth
#

that's what I initially thought but as you can see the UI_panel_pair does not show up either

fresh salmon
#

You would need to have an instance of it and drag it in, not even sure it expands for you to edit the fields

glacial geode
#

also im rather sure thats not the case spr2 isnt it

#

since unity events can have T0,T1 arguments

#

or do they just not appear on the inspector?

#

(havent tested atm, asking as well out of curiosity)

void hearth
#

I can add them programatically tho

glacial geode
#

Ry, you havent showed the events im saying that again

void hearth
#

how should I show them?

fresh salmon
#

Even the ones with one argument, if it's not of any of the supported types (numbers, strings, Objects) you cannot add the handler thru the Inspector

#

You can only do it via code

glacial geode
#

What is this script?

#

or component

void hearth
#

I've added this method and it does show up here

sage radish
#

Because it supports Unity objects

fresh salmon
#

Because I suppose UI_Panel is a Unity component or object

#

Those are supported as you can drag em in the slot

void hearth
#

it's my class

sage radish
#

It supports void, bool, int, float, string and Unity objects

#

MonoBehaviour is a Unity object

fresh salmon
#

Yep it derives from MB so it derives from UnityEngine.Object

void hearth
#

oh ok

#

so all I can do is add another component with 2 Ui_panl references in it, (enter, exit)
and on Awake() associtate a Event to the component that needs

#

Thanks anyway!

#

but wouldn't a custom inspector support it ?

vital zodiac
#

Hey, everyone, I'm doing my research regarding architecture at scale. Do you have any resource recommendations? 🙂

sage radish
vital zodiac
livid kraken
#

How big a game are you planning on making

vital zodiac
# livid kraken How big a game are you planning on making

It's not about any game in particular. I've just finished my first prototype-ish game and looking for some best practices now so I can try a different approach next time (e.g. components-driven design, scriptable objects).

I'm coming from a web app background where approaches like MVC are popular, but it doesn't feel right in game dev environment for me.

livid kraken
#

For me the best aproach is really a mix of OOP and and a more data driven architecture

vital zodiac
livid kraken
#

Yeah in my experience resources are a bummer. Ive yet to find a book that solves everything for all games. There isnt a specific architecture that works best for all games

#

Like the architecture of Doom is vastly different from lets say a Total War game

#

I stumbles uppon this video yesterday and I generally agree with it

#

But its more of a collection of tips rather than what you are looking for

vital zodiac
#

Still thanks for the video! 🙂

glacial geode
#

Okay so i figured out my issue with rotation

#

so im calculating a rotation to apply based on time delta and so on, but the issue is while the target rotation is right i cant make the quaternion rotate inversely (from 0 it should lerp towards 360 in reverse instead of going 0 - 10 - 20 .... 360)

#

in this case Quaternion.Inverse(current) * target wont do it cause it keeps giving me the wrong thing

#

any suggestions?

warm shale
# compact ingot Wdym? Pretty much all code does that in one way or other.

Well, I have a player gameobject with a camera attached. The player has code to run out of health, but I need the camera to move when this happens. So I need the player to tell the camera that it is time to move. Is there a way the player's script can send a message to the camera's script like this?

errant plinth
fresh salmon
#

Inb4 the Doc pings you to use UniRX or something similar instead of that

plain abyss
#

I am having consistent Editor crashes for a while and I think I've realized what the problem is. If I exit play mode while a bundle is being loaded asynchronously, the next time I run the project, it will crash when I exit play mode. My guess is there's some sort of wrap-up that LoadFromFileAsync runs when it's done loading that makes the file okay to use next time, but quitting in the middle of that is preventing it. What is the proper practice for cleaning up asynchronous bundle loading when you exit? I would prefer to not have to wait for all of the loading to be finished before exiting play mode while testing.

errant plinth
#

Interesting. Thanks for mentioning UniRX

scenic forge
#

The one thing I've found working on my game is that Unity's prefab and scene serialization is incredibly noisy and unreadable.

#

It's fortunate that a huge part of my game is less of a game but more like a traditional app, so I can apply typical frontend knowledge to it, and I've since moved away from anything to do with editor besides using it to preview/speed up iteration.

#

Obviously that's not possible for majority of the games, but for my project at least, being code only rather than having anything to do with editor makes it so much more maintainable and scalable.

undone coral
#

reactive stuff sort of organizes itself, it shows you that decisions like where you declare an X matters less than having exactly 0, 1 or many Xs, and naming it discoverably.

plain abyss
#

So, how does one gracefully cancel an AssetBundleCreateRequest in OnDestroy if the game closes before it's finished? I think if I can find a way to do that, I can fix my crashing issue, but AssetBundle.UnloadAllAssetBundles doesn't seem to do it

undone coral
#

suddenly things like "singleton patterns" versus "systems" versus "controllers" melt away, because all those things are turn out to be holders of names for things, trying to make something fundamentally reactive look like something it is not

scenic forge
#

Declarative is 100% the way to go for any UI with complexity.

undone coral
#

i don't know man it sounds like you need to file a bug because that's a shitty one

#

you can have the object that makes the request live outside the scene

#

meaning in edit mode

#

[ExecuteAlways] basically

plain abyss
#

Maybe I can get away with that, since it wouldn't affect any builds anyway. This error only seems to be in editor, I haven't gotten any sort of crash in a build. Maybe I shouldn't be reloading the bundles every time I hit play?

undone coral
#

are you trying to animate a rotation? use DOTween

undone coral
plain abyss
#

Running in debug mode and breaking on exception is actually getting me some info.

The AssetBundle 'C:\Users\mfournier\JasminMaterials\metal' can't be loaded because another AssetBundle with the same files is already loaded.

And then the editor crashes. Definitely some hanging references if I close out of the game before it finishes loading.

#

Actually, it doesn't crash if I just continue in debug mode, but if I run it normally it crashes before the error comes up...

#

It manages to exit normally and show the error in the console like I'd expect...

#

Gah I've got too close of a deadline to worry about this editor bug, I'll try to sus it out more whenever I have time to thoroughly test. It doesn't affect the final product at all. Maybe just making the bundles persistent in editor is what I need

glacial geode
#

but since im using a lot of third party stuff it aint easy to just apply it to the transform

#

so instead i cache the delta rotations and then apply them

#

issue is how to properly get the inverse rotations cause it keeps fucking up counter clockwise rotations

pale arch
#

hi i have a problem about making a collision with grids, but i cant seem to assign the field for this object with OnTriggerEnter2D(Collision2D other), do i need to assign the field that im using in OnTriggerEnter method?

#

also want to say field is using Vector2int

plain abyss
pale arch
plain abyss
pale arch
#

im trying to assign the chest into colllsion so that when lets say a player is trying to push, then it is going to move

plain abyss
#

So, you set Chest to itself, then check if this Vector is equal to a bool...?

#

What does this even mean

pale arch
#

idk xd im trying things

fresh salmon
#

My man, I think you have the wrong channel

plain abyss
pale arch
plain abyss
# pale arch i do?

Your questions betray a lack of understanding of even the absolute basics of how Unity works

#

Also, as I said in beginner, why are all of these objects Vector2Int and not Transform or some script or something

#

If these are objects, make them objects

cloud trail
#

Seems to be grid positions rather than world positions

plain abyss
cloud trail
#

Ah this is a 2D game, gotcha

pale arch
cloud trail
#

Yeah you right dig

plain abyss
#

I don't know what your project looks like

pale arch
#

this is how it looks like

undone coral
#

like

#

what is the effect you are trying to achieve

#

i didn't really understand that explanation

glacial geode
#

thats fine i managed to figure it out

#

i used modulo to get the actual orientation from -180 to 180

#

and i used the difference when making my blending from 0 - 360 (since quaternions always use a 0 to 360 conversion)

#

it finally works, man this was a pain

vital zodiac
scenic forge
#

I just roll my own reactivity system that's similar to Vue's since I already have experience in that.

#

UI as well.

glacial geode
#

pardon?

honest hull
#

hey so in this code:

SkinnedMeshes[i].vertexBufferTarget |= GraphicsBuffer.Target.Raw;
FinalMeshBuffer = SkinnedMeshes[i].GetVertexBuffer();
MeshRefit.SetBuffer(ConstructKernel, "bufVertices", FinalMeshBuffer);

Why does the final line say that FinalMeshBuffer is null if I do this on start?

#

but it only happens if I put it in start

silver onyx
#

so...i was wondering like when i do a building system based on a grid i cast a ray from camera to cursor and then do some magic math to adjust to the grid based on nearest position... but when i want to display a grid on the terrain while building maybe only in a sphere around the mouse any hints on how to approach that? and make it so that the grid "shader" i guess is corresponding to the mesh position that its being placed on based on the grid size?

undone coral
#

that's weird

#

can you try waiting a frame?

honest hull
#

I did and that works fine

#

back to figuring out the transforms, realize my problem actually is that the vertex's from a vertex buffer are in world space and I need them in local space

arctic robin
#

Not sure if this is the channel for it, but:

I have these spikes on my HoloLens app, how do I use the profiler to track down the issue?

copper cypress
#

I know I've nothing to add, just wanted to say it's cool you're even making a HoloLens app. What is it?

arctic robin
#

Used to make short tracks in a HoloLens space

copper cypress
#

oh sweet

arctic robin
#

Am having a godamn weird ass bug though

#

Slider isnt being loaded for some reason.

copper cypress
#

so you're making a literal audio editor using Unity for HoloLens

arctic robin
#

Yeah but simpler

#

Uses samples

undone coral
undone coral
#

the trace

arctic robin
undone coral
arctic robin
#

That'd be correct, just no idea why.

rocky mica
#

you sure awake is being called and that Pinch Slider is actually attached to the gameobject when invoking that awake?

hushed plume
#

i haven't coded in about 4 months so i'm a bit rusty, to say the least

thin frigate
#

help ! I try load material from assetbundle and some of them are missing in Android😰

#

it is perfect in editor

#

anyone have idea?

#

and the wired thing is ....

#

the missing material was difference in difference mobile

#

🤪

#

my unity version is 2020.3.13f1

ornate gulch
#

Hello everyone! I was browsing around and came up with an idea for a game i would like to make.
It will use the precedent player's messages on a diary and afterwards the current player will write his diary during the game to give to the next player and so on.

I would like to know if there is a safe way to make something like this, i've heard about the game **Moirai **who had a similar mechanic but was taken down because of continuous attacks at the database, does anyone know something about?

hushed plume
#

a per-account string inscription would be my best guess

ornate gulch
#

I'm really new to C# scripting so i don't really know what are you talking about, i've been learning with many languages such as Lua, Python, Java and C# but never focused on one to understand it at his best, i've recently decided to focus on C# because of Unity so i'm actually at a really low-mid level.

hushed plume
#

than this wouldn't be the right channel lol

ornate gulch
hushed plume
#

not of code, but more of cybersecurity

#

my idea would be that each player has a key stored on their hard drive, and then the key is used to scramble and unscramble data coming to and from the servers

ornate gulch
#

I see, i'll search around to learn something about it, thank you.

hushed plume
#

@ornate gulch what's the data going tp be hosted on?

ornate gulch
#

I'm still thinking about, it will not be a huge project, just a little game for itch or something else so i'm searching for a cheap but safe system

#

I'm looking at Telegram now, i was thinking about this, since it is one of the most (if not the most) secure of all and also would be free for a little project like this

The game ends, the file with the text gets copy-pasted (sent) to a Telegram bot with a token and player number (such as Player#284 for example) everything is encrypted.
The Telegram bot shares the text with the main chat where all "stories" are stored
At the start of another game the game requests the latest Player# story to the bot and copy-pastes it on chat
The game then reads the text and updates it to the game

Does this sound good to you?

honest hull
# undone coral can you try waiting a frame?

yeah so this, erm for some reason that doesnt work anymore for a different modle? so I guess I need to actually look into it instead of slap together a fix
God I hate skinned meshes with a passion now

#

so this mesh doesnt have a vertex buffer, but has an index buffer?

#

wait no it does
I just have to wait an unknown amount of time or iterations of trying to call it for it to happen

thin frigate
honest hull
#

ok hey so this is now moved from annoying to all but infuriating me
the non wiremesh is the correct output of the skinned mesh, while the red wireframe is the raw output from the VertexBuffer of a skinned mesh with no extra matrices applied, what do I still need to correct the positions??
i have looked through other code, but theres not much on using vertexbuffer to get the skinned mesh, what am I missing?

honest hull
#

mine is like fixed by the hip whereas the correct output is not
and idk why

#

actually yeah thats exactly whats happening
for the vertex buffer output the hip doesnt move at all, why and how can I correct this??

thin mesa
stoic compass
#

I have a question about whether I'm using scriptableobjects correctly. Currently all weapons are scriptableobjects, and I'm implementing a simple randomization class which will create new random weapons (with randomized values) at runtime. So I figured I would just do ScriptableObject.CreateInstance<TypeOfWeapon>() and then set the values, create a GO, plug in the SO, and go from there. But looking up some threads, I'm seeing people say this is a bad way to use SOs. And I can't quite understand why. I've been trying to wrap my head around this:

#

and this:

fresh salmon
#

Sharing the same opinions as the screenshots here

#

If you need to randomize things, just make a plain old class and plug that in

lucid girder
#

I've yet to find a good reason to use SO over either static classes or parsing JSON/XML (or both)

fresh salmon
#

SOs are more of "static data containers", since their instances can be saved on your filesystem

somber tendon
stoic compass
#

I figured SOs were appropriate for weapons if the stats could be changed, and needed to be consistent across scenes. Is making all weapons (I was thinking all items) SOs bad, or is how I'm creating weapons at runtime bad?

fresh salmon
#

It's useful for that yeah, say you have weapon prefabs here and there in the scene for your player to pick up, and you need to increase the damage of them, then you just edit that value in the SO and it'll be applied to all scripts that references that instance

stoic compass
#

Okay, so if having weapons as SOs is fine, how else could I instantiate them during runtime? Cloning prefabs?

fresh salmon
#

A prefab of your weapon, containing a script that has a reference to the SO

#

Instantiate the prefab, the reference to the SO stays

#

But at this point you could just store those stats in the weapon script iself

stoic compass
#

Hm, the thing that made me sceptical about that is then the randomization class needs a reference to a prefab for each weapon type (so if there's forty types, that's forty references), whereas CreateInstance requires no references

#

Hm, wish I could see how other games approached randomization

lucid girder
#

You'll end up needing a reference for each type anyway though

stoic compass
#

I will?

lucid girder
#

Won't you need to know which of the types you'll spawn regardless of which method you use to spawn them?

stoic compass
#

I don't think so. Can just do BlueWeaponType blueWeapon = ScriptableObject.CreateInstance<BlueWeaponType>(); and then randomize its values however is appropriate

lucid girder
#

But what about a red weapon then?

fresh salmon
#

Then you can just do BlueWeaponType blueWeapon = new(); and you get rid of the SO part

stoic compass
#

You're saying just make all weapons monobehaviours?

#

Tbh I have no idea how multi-scening works, so I'm just guessing that having them as SOs will be good

#

(Also I've seen the unity tutorials where they're like 'use SOs for everything')

fresh salmon
#

Ah you need some kind of persistence alright

#

So yeah, standard classes won't do here, as they get dropped when all refs to them also drop

lucid girder
#

Or use DDOL

stoic compass
#

So you'd still recommend having a bunch of references to prefabs, rather than using CreateInstance?

fresh salmon
#

DDOL could be a solution, given that you persist the object that has the weapons on it

#

The player for example

stoic compass
#

Doing DDOL shenanigans is probably troublesome enough that I wouldn't be gaining much

#

Also I thought making inventory objects SOs was more or less standard

somber tendon
#

I personally try to stay clear from anything that's too "Unity's way"

stoic compass
#

Well I guess I'll make a WeaponTypeLibrary class which just contains references to a prefab of every weapon type. And can just clone from there as needed.

#

Is that the proper way?

#

It's hard to get answers to architectural questions, which is sad because they're the most nebulous and important

#

imo

somber tendon
stoic compass
#

K, I'll do it that way

lucid girder
#

You could also do static classes. They are instantiated just before your first function call to it, and will persist regardless of scene.

stoic compass
#

Also I just realized, since every type of item will need to be created at runtime, I would need a prefab reference for every type of item, not just every weapon. Geez... CreateInstance looking more attractive again...

scenic forge
#

Editor stuffs have big downsides

#

The major benefit is that non programmers can also work with it in editor to change things

#

But if that’s not something needed, plain C# solutions are just better and more maintainable.

snow grotto
#

Any way to optimze this? This works but I would like to know if there is a more elegant way, I only wanna calculate the angle before the check but I don't like having everyting done with if else

 // Fire cannons
            
            var rightFireAngle = Vector3.Angle(transform.right, targetDirection);
            if (rightFireAngle < minimumAngle)
            {
                TryFireCannons(Side.Right);
            }
            else
            {
                var leftFireAngle = Vector3.Angle(-transform.right, targetDirection);
                if (leftFireAngle < minimumAngle)
                {
                    TryFireCannons(Side.Left);
                }
                else
                {
                    var forwardFireAngle = Vector3.Angle(transform.forward, targetDirection);
                    if (forwardFireAngle < minimumAngle)
                    {
                        TryFireCannons(Side.Right);
                    }
                }
            }
tough tulip
# snow grotto Any way to optimze this? This works but I would like to know if there is a more ...

if your goal is to reduce the number of lines, you could try to directly use the angle results in the if statement check, but then again if you revisit the same code after some time you might not remember what the Vector3.Angle returns.

you can also try to calculate all angles at start, and combine all conditions in a single if/else statement to pass Side.Right if true, else Side.Left but then again, you're calculating all the angles at once before the check. which is not the case now.

but to be honest, dont worry about it. looks neat, and even if sometime later if someone else looks at the code, they wouldn't have difficulty in understanding the variables, and how you're using them

snow grotto
#

Alright, fantastic expiation, thanks! I'll keep using it then ;)

tribal pivot
snow grotto
#

Ah, good tip, thanks.

scenic forge
#

Look up on guard clauses.

#
var rightFireAngle = Vector3.Angle(transform.right, targetDirection);
if (rightFireAngle < minimumAngle)
{
    TryFireCannons(Side.Right);
    return;
}

var leftFireAngle = Vector3.Angle(-transform.right, targetDirection);
if (leftFireAngle < minimumAngle)
{
    TryFireCannons(Side.Left);
    return;
}

var forwardFireAngle = Vector3.Angle(transform.forward, targetDirection);
if (forwardFireAngle < minimumAngle)
{
    TryFireCannons(Side.Right);
    return;
}

// Handle cases where none of the above matches
#

But in terms of the actual code logic itself, there might be better ways than checking one by one.

snow grotto
scenic forge
#

This function does not just one thing but two things: determining side, and firing cannons in that side.

#

I would refactor into two functions, and you can instantly see how much nicer it is.

#
var rightFireAngle = Vector3.Angle(transform.right, targetDirection);
if (rightFireAngle < minimumAngle) return Side.Right;

var leftFireAngle = Vector3.Angle(-transform.right, targetDirection);
if (leftFireAngle < minimumAngle) return Side.Left;

var forwardFireAngle = Vector3.Angle(transform.forward, targetDirection);
if (forwardFireAngle < minimumAngle) return Side.Right;

// Handle nothing matches
TryFireCannons(GetSide(targetDirection));
snow grotto
#

Nice, that's defiantly the best option, thanks. When I get out of the prototyping faze I'll defiantly build it that way.

crimson python
#
[CreateAssetMenu(fileName = "New Ability", menuName = "Abilities")]
public class AbilitySO : ScriptableObject
{

    public string AbilityName;
    public string AbilityDescription;
    public Image AbilityImage;
    public int AbilityLevel;
    public int AbilityDamage;
    public int AbilityTargetAmount;
    public int AbilityHitAmount;
    public int AbilityManaCost;
    public int AbilityCooldown;
    public int AbilityLifetime;
    public int AbilitySpeed;
    public List<Buff> Buffs;

}


public abstract class Buff
{
    protected float modifier;
    public Buff(float _modifier) { modifier = _modifier; }
    public abstract void ApplyBuff(PlayerController pc); 
}

public class JumpHeightBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.JumpForce += modifier;

    public JumpHeightBuff(float modifier) : base(modifier)
    {
        
    }
}

public class MoveSpeedBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.MoveRate += modifier;

    public MoveSpeedBuff(float modifier) : base(modifier)
    {
    }
    
}

#

Can someone explain to me how I can add the buffs to the list?

#

And if this even looks correct

plucky laurel
#

System.Serializable

sly grove
#

it'll have to be in code though

plucky laurel
#

you can use Odin inspector

sly grove
#

you won't be able to do this in the inspector since you can't really do inheritance like that with Unity's serialization

hollow garden
sly grove
#

Odin might work yeah, or possibly SerializeReference

crimson python
#

Ok ill give it a try thank you!

#

Getting an error saying the Default Constructor not found

fresh salmon
#

You need a parameterless ctor for serialization to work

#

Adding your own parameterized ones removes the default implicit parameterless one

crimson python
#

Could you explain that in stupid for me please? You are basically saying i wont be able to pass the modifier?

#

Or that i just need to change how the constuctor is written

fresh salmon
#

Basically when you have a class with no constructor defined, it adds one by default, so you're able to do new MyClass();
But, as you created your own with a parameter public Buff(float mod), the implicit one gets thrown away

plucky laurel
#
class Foo {} 

generates default constructor Foo()

class Foo{
  public Foo(int a)
}

doesnt generate

fresh salmon
#

You need to have an empty one, the serializer will not use the one with a parameter

#

(in response to now deleted message) Please don't

visual basin
#

Okay

crimson python
#

So how can i circumvent this issue? How do I allow a parameter?

fresh salmon
#

You can't from the constructor directly

#

However you can make the value show in the Inspector by serializing it: [SerializeField] protected float modifier;

crimson python
#
[Serializable]
public abstract class Buff
{
    [SerializeField] protected float modifier;
    public Buff() { }
    public abstract void ApplyBuff(PlayerController pc); 
}
#

Essentially this?

fresh salmon
#

Yep, you could have kept the other constructor in the event you needed to create instances from code more easily, but that should work

crimson python
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "New Ability", menuName = "Abilities")]
public class AbilitySO : ScriptableObject
{

    public string AbilityName;
    public string AbilityDescription;
    public Image AbilityImage;
    public int AbilityLevel;
    public int AbilityDamage;
    public int AbilityTargetAmount;
    public int AbilityHitAmount;
    public int AbilityManaCost;
    public int AbilityCooldown;
    public int AbilityLifetime;
    public int AbilitySpeed;
    [SerializeReference, SubclassSelector] public List<Buff> Buffs;

}

[Serializable]
public abstract class Buff
{
    [SerializeField] protected float modifier;
    public abstract void ApplyBuff(PlayerController pc); 
}

[Serializable]
public class JumpHeightBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.JumpForce += modifier;
}

[Serializable]
public class MoveSpeedBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.MoveRate += modifier;
}

#

This seems to work in the inspector now

#

woohoo!

fresh salmon
#

Like methods, you can have multiple constructors as long as their param types are different

crimson python
#

Im working with stuff i have 0 clue about lol...

fresh salmon
#

Coworker comes in, sees a lot of code
"What are you doing?"
"I have no idea"

crimson python
#

Thats me every day in my project

#

Just a hobbyist. Learning as I go

#

I guess my question is. What was the point of the constructors than if I can just easily set the value already in the inspector

fresh salmon
#

If you were not meant to create new instances diectly in code by doing new JumpHeightBuff(42069), none

hollow garden
#

^

#

if there's no need to use constructors, there's no need to have them

crimson python
#

I don't think.... I did? Specially since this is on a ScriptableObject. I was just going to make multiple abilties and if they were a buff simply control the values inside the SO.

#

as such

hollow garden
#

yeah

crimson python
#

But moreso what you are getting at, is that i could reuse the code tho. For a non ability.

#

Say a buff tile

#

Thats what im understanding, correct?

scenic forge
#

Alternatively, for things that you don't intend to change via inspector, just do it like normal C# 😄

undone coral
#

then you can use constructors or whatever you want

#

if you need a more powerful editor, you can create a CustomPropertyDrawer for the Ability type i've described or use Odin

crimson python
#
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "New Ability", menuName = "Abilities")]
public class AbilitySO : ScriptableObject
{
    public Ability Ability;
}


[Serializable]
public class Ability
{
    public string AbilityName;
    public string AbilityDescription;
    public Image AbilityImage;
    public int AbilityLevel;
    public int AbilityDamage;
    public int AbilityTargetAmount;
    public int AbilityHitAmount;
    public int AbilityManaCost;
    public int AbilityCooldown;
    public int AbilityLifetime;
    public int AbilitySpeed;
    [SerializeReference, SubclassSelector] public List<Buff> Buffs;
}

[Serializable]
public abstract class Buff
{
    [SerializeField] protected float modifier;
    public abstract void ApplyBuff(PlayerController pc); 
}

[Serializable]
public class JumpHeightBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.JumpForce += modifier;
}

[Serializable]
public class MoveSpeedBuff : Buff
{
    public override void ApplyBuff(PlayerController pc) => pc.MovementPrediction2D.MoveRate += modifier;
}

#

Like this? @undone coral

haughty geode
#

Hey everybody,

I tried implementing a character direction change based on the path the character is moving on. As I am using a Pathfinder algorithm it happens that he needs to change twice direction during the same path (L shape path) in the case below it would mean changing position once to DOWN and at the corner to RIGHT

the Code shown below works for a single direction change, any idea on how to make it recognize a second one in side a path ?
https://gdl.space/unanulisoh.cs

undone coral
queen plover
#

Small nitpick, but it seems a bit redundant to have the "Ability" prefix before every variable if it is inside the "Ability" class.

crimson python
#

Understandable

crimson python
#

If you don't mind that is

#

Appreciate the help!

#

Im also second guessing myself too, should i even be using a SO? I would assume yes since im going to make a whole lot of abilities.

#

Then i just make a Job class and a list of AbilitySOs and bam right?

cloud badger
#

That's what I would do

#

Me also have question.

#

I spent a couple hours learning about cryptography last night and it's been really overwhelming

crimson python
#

I could only imagine

cloud badger
#

I'm trying to encrypt some amount of bits to where each input has exactly one input and the amount of bits don't change

#

I can think of a thousand shitty ciphers that might or might not be easy to crack

#

Is there a best way of doing this that someone could point me towards?

crimson python
#

What are you trying to encrypt? Everything?

#

Or data

cloud badger
#

Just some collection of bits, probably 32 at a time

#

It doesn't need to be decrypted either, the same input just needs to give the same output

scenic forge
sage radish
cloud badger
#

I actually haven't learned much about hashes, but a friend initially suggested using one then took it back

sage radish
#

But most of them are fixed size, the hash is always the same size regardless of the input

cloud badger
#

He said if it's using/getting 32 bits, between any two inputs, there was some 1/77000 chance their outputs would be the same

#

I'm going to be sending this data over a network and having it be more than 32 bits would be redundant for its application

#

(also really expensive because of how often it would be sent)

scenic forge
#

The major benefit of SO is that not only you the programmer, but also practically anyone even the artists, can create/edit/update SOs and their data directly in the editor.

sage radish
scenic forge
#

If that's not something you need then it's just a useless feature.

crimson python
#

Scriptable Objects are Unity only right? its not .net feature

scenic forge
#

Yes it's Unity.

crimson python
#

Coo Coo. THanks

scenic forge
#

My personal advice has already been, if you don't need editor capabilities then don't use editor stuffs, it's all going to be a headache later down the line.

#

Unity's serialization is extremely ugly and unfriendly to version control.

cloud badger
#

SOs are extremely addictive

#

I'm using them in everything- projectiles, inventories, items

#

Sticking them in a database and then accessing them by ID makes it really easy to make and access whatever you want whenever you need it

scenic forge
#

You can do the same without SO and with just POCO too.

cloud badger
#

I guess I just like how easy it is to organize them

cloud badger
#

It's just supposed to scramble the input

#

I think I've figured out what I'm gonna do for it though

sage radish
scenic forge
#

Editor stuffs suffer from typical magic string issues and you lose all capabilities of a typical code based workflow.

cloud badger
#

It's for a bunch of systems where I want predictable randomness

scenic forge
#

Any changes you make with serialization, also good luck doing code review on them (but this applies more to scene/prefab than SO)

cloud badger
#

Indeed

#

But I wouldn't want any duplicate outputs

vagrant gulch
cloud badger
#

Imagining my input is four numbers and my output is four numbers, [1,7,5,4] would give me [6,4,8,9], and no other input would give [6,4,8,9]

#

As long as the way that output is generated is hard to crack anything works

scenic forge
#

Is this generated on the server or client?

cloud badger
#

On the server, then sent to clients

#

That's why I don't want to use a hashing algorithm that generates a giant output

undone coral
vagrant gulch
#

I suppose any cipher would do this but 32bits is a small block size for a cipher.

cloud badger
#

I was gonna use a bunch of XORs with feistel ciphers for this

undone coral
#

yes but

#

what is the purpose

#

what are you trying to do

#

like 1 sentence

cloud badger
#

It's for unique data from a combination of different items

#

Lemme get a picture

undone coral
#

like

#

what is the gameplay purpose

#

help me understand

#

it sounds like you are trying to make an identifier

scenic forge
#

There are probably a lot more vulnerabilities in the way it works than the encryption itself.

cloud badger
#

the color wheel looking thing is a wand's "inventory"

#

given the combination of runes i've put in, generate some random 32 bit code to use for making a spell

undone coral
#

you're still being too small here

#

what is the gameplay purpose?

cloud badger
#

generating values for a projectile

undone coral
#

what does that have to do with cryptography

#

better question

#

what is your obstacle right now when you're trying to generate values for a projectile?

#

do you mean procedurally generate different projectile behaviors?

cloud badger
#

that's what i'm trying to do

undone coral
#

like different numbers for tits size and speed?

#

okay

#

so what is the obstacle right now/

#

communicating the randomly generated values to the player/

#

?

cloud badger
#

the obstacle is i need some way to scramble 32 bits in a way that no input is the same as the output

#

i've got everything else figured out, it's just this bit

#

with a scrambled 32 bit output i can generate everything else for the projectile by converting pieces of it into IDs

undone coral
#

this is easy. take a random number, i'll suggest 0x90FB18AE, then xor it with another number. it's now scrambled and also reversible. but what does this have to do with generating a projectile?

vagrant gulch
#

So basically you need to uniquely identify a set of runes? If that's the case then using a hash seems like a good idea. If there's a finite set of ruin combinations then you can ensure there's no collisions.

scenic forge
#

Why do you need it to be dependent from client input and why do you need it to be uncrackable?

undone coral
#

it's okay

#

i think you haven't really helped me understand yet what your objective is

cloud badger
#

alright so spells are completely randomized

#

i'm storing all projectile attributes as scriptableobjects within a database that can be accessed by ID

#

the 32 bit "input" is created from the amount of each rune used in creating a spell

#

the server then scrambles the input into a 32 bit output that's used to generate a spell, then sent to a client

undone coral
#

what is the significance of this step

#

why is there a server?

#

what are you trying to achieve in gameplay

#

succinctly

#

like "i don't want players to be able to ... X"

#

but X has to be real. it has to inhabit reality

#

lol

#

or "because i'm doing X i need..."

#

you're close

cloud badger
#

i don't want players to know what combination of runes corresponds to a given spell if they look at the code

#

mirror can completely hide server code from client builds

scenic forge
#

But if client sends the same 32 bits, server will respond with the same scrambled 32 bits?

undone coral
#

buuuuuut

#

don't they SEE the runes

#

i don't get it

#

if i am looking at an interface

cloud badger
#

they see the runes, but they won't know what spell it makes beforehand

undone coral
#

and i select some runes

#

and out comes a spell

#

soooooo

#

think about this

#

someone knows

cloud badger
#

it's like clients can know a chocolate cake can be created but won't know the recipe for it

undone coral
#

sure they don't

#

well

#

but why doesn't minecraft do this with their recipes

cloud badger
#

they don't try to keep that stuff a secret

undone coral
#

why is there no encryption

#

okay...

#

name me one game

#

that tries to keep "that stuff" secret

cloud badger
#

wrong warp biggrin

undone coral
#

?

scenic forge
#

If someone figures out a combo of runes will produce one spell, they can just share it to everyone else.

cloud badger
undone coral
#

are you saying that a bug in elden ring

#

is what you are aspiring to reproduce?

scenic forge
#

Then it's literally pointless.

cloud badger
#

i want people to be able to find combinations that have cool effects and then share it with others

undone coral
#

yes

#

they are still going to do that

#

but the encryption part makes no sense

#

dont' worry about this stuff

scenic forge
#

People can look at your client code and find out how it communicates with the server, and just send that request for whatever they want to know.

#

They don't even need to play the game to know what runes create what spell.

cloud badger
#

that's exactly what i'm building this to do

#

given an input of 32 bits, encrypt those bits on the server and send it to clients

#

clients wouldn't ever know how it got encrypted

scenic forge
#

No

#

A fake client can send whatever 32 bits they want and observe what your server responds with.

cloud badger
#

the "decryption" into spell attributes would be known, but they wouldn't know what combination of runes would turn into a given output

scenic forge
#

They don't need to know how the encryption works.

cloud badger
#

sorry, i worded this poorly when i tried to simplify it

scenic forge
#

They can just keep trying whatever 32 bits until they find one that gives what they want.

cloud badger
#

to get a 32 bit output they need to actually tell the server they want to cast a spell

#

the server looks at the inventory of the wand they're using, creates a 32 bit input from the combination of runes in it, makes a 32 bit output, then sends it to players

#

the only way players can get an output is by casting a spell and using runes

#

the wand inventory being in the top left

scenic forge
#

So everything is server side then, all client side is doing is just telling server "I want to cast a spell" and everything else happens on the server?

cloud badger
#

exactly, i just tried to simplify it earlier since i thought the inventory stuff might be a bit confusing

vagrant gulch
#

Why does the client need the scambled bits?

cloud badger
#

when the client receives the bits it'll use "decryption" on them to generate effectively random IDs

scenic forge
#

It doesn't, it's a miscommunication because they oversimplified it.

cloud badger
#

random IDs for stuff like the mesh, color, sounds, etc

#

i have them stored in databases mostly as SOs and other files

maiden turtle
#

I've been thinking how it's good to have dependencies explicitly passed to objects (inversion of control). Right now I'm doing a scene initialization method that has references to everything and just calls everything in correct order passing all dependencies into the initialization methods. I am aware of dependency injection frameworks that fo this automatically at runtime, but then I'd think the initialization is harder to understand and debug. What I've been thinking is to make a tool that would analyze the scripts and the scene, and then automatically generate a handcrafted initialization method for that scene specifically. The initialization order can be deduced from initialization method arguments, and adjusted with custom attributes. This way you'd get the benefits of dependency injection while avoiding its downfalls: impact on runtime performance and the "magic" of everything coming together automatically. You could see how exactly it comes together just by looking at the generated code.

#

your thoughts

scenic forge
vagrant gulch
cloud badger
#

it would simpler though

maiden turtle
scenic forge
#

If size is what you are worried about, use something like MessagePack/Protobuf/Flat Buffers/etc.

cloud badger
#

i haven't converted everything into a separate database yet to where this uses IDs, but it would be a lot of fields

maiden turtle
#

In the project I'm working on right now to test a feature you have to reach it from the main scene

scenic forge
#

There's no reason for your data compression to be tightly coupled with your actual logic.

cloud badger
#

i guess it just feels a bit lazy to do all the computing on the server and then send it out

vagrant gulch
cloud badger
#

it seems worth it to encrypt the data if it means sending 10x less information out to clients

scenic forge
#

That's not encryption, that's compression.

cloud badger
#

i'd say it would be irrelevant too if it meant only sending this out to a few players, but i'm trying to design this to be ready for however many there are

scenic forge
#

All you are trying to do, is to send a list of runes to the server, server generates a spell and send it back.

cloud badger
#

the server doesn't need to know any spell can be made from the 32 bits

#

it just needs to scramble them

scenic forge
#

Yes but it doesn't matter.

#

The server receiving the runes it can generate the spell however it likes, including turning those runes into a number and scramble it.

#

You are coupling your data transmission with the logic for no reason and trapping yourself into "I must find a way to scramble 32 bits"

cloud badger
#

surely scrambling bits would be far simpler and efficient than trying to compress spell information down

scenic forge
#

Nope.

cloud badger
#

there's no reason to completely initialize the spell before sending it out to clients

#

i can just send the information to clients and have them make it themselves

scenic forge
#

Actually I'm lost, weren't you say all client is doing is to tell server that they want to cast a spell, and fetching runes etc are done on the server side?

#

Or does client tell server what runes they are using?

#

Because if it's the latter then there's no protection what so ever, people can figure out every possible combination of runes and what spells they will produce.

cloud badger
#

have you ever played minecraft before?

scenic forge
#

I'm just saying, MitM is a thing and if your server is relying on the information client sends, then it's easily manipulated.

#

Regardless of whatever game, Minecraft included.

cloud badger