#archived-code-advanced

1 messages · Page 159 of 1

dawn zinc
#

I'd like to work on making things more scalable for different tasks I find myself doing

dawn zinc
#

HA I TOTALLY FORGOT I BOUGHT THIS BOOK ON KINDLE

regal olive
dawn zinc
#

◌ I haven't heard of that, but I'll check it out ◌

inland halo
#

im having tourble with the RPCs. ( i get this error when i try to shoot )
i checked code and its the same might be and update from photon i think but i haven't been able to solve it

thin mesa
#

your method is called Shoot but the RPC you try to call is shoot (yes, there is a difference)

silent rivet
#

Does anyone else have almost constant issues with the debugger hanging on an "mousedown" or "tick" event and never being able to run the editor until the VS debugger is turned off?'

inland halo
#

[PunRPC]
void Shoot ()
{

#

that should be shoot instead of (Shoot

thin mesa
plucky laurel
#

vstu updated? unity vs package updated?

silent rivet
#

No, I can't click unity and I hit no breakpoints, this happens like 75% of the time, and pretty much has as long as I can remember using unity, so like a decade now, across many different computers

#

It makes it very hard to use unity at all

silent rivet
#

I could stream it, right now i've restarted unity like 3 times and it's still happening

inland halo
plucky laurel
#

kill .vs folder, rebuild the solution

#

check if you have some firewall/av interfering

#

or vpn, or some virtual network adapters

#

across many different computers
this is the most worrying part, because that means you carry over something thats causing it

#

can be some software that you consistently use, can be vs cloud settings bound to your account, can be some hardware

heady umbra
#

is IL2CPP converting the entirety of the C# code to C++? ie if I build some ML, will it be fast?

hollow garden
regal olive
#

@hollow garden @heady umbra Um... That isn't exactly right (I might be misreading something, admittedly). How your structure your program has an enormous impact on the CPU and memory footprint of, ultimately, your running process. At the level most Unity developers are at then considering how one write their code and what impact it has on its process memory and CPU footprint will produce more performance dividends than switching to a language that is "faster."

This is a niche topic for all but very advanced users (what are you two?). It is true that native code (aka machine code) is faster than going through just in time (JIT) interpreter intermediary that then executes. For C#'s case, the code is compiled into MSIL (like java bytecode) which is run through the .NET common language runtime (CLR) that knows how to run on multiple computer architectures. What you get for your performance trade off is being able to write code that isn't specific to a computer architecture.

I must emphasize again that your code structure has a bigger impact on performance than a language choice. Figuring out how to tune your software to be acceptable for your use case is a skill one ought to develop.

To illustrate this point, check out this article on how an algorithm trading company uses Java to achieve performance capabilities of C++: https://medium.com/@jadsarmo/why-we-chose-java-for-our-high-frequency-trading-application-600f7c04da94

heady umbra
#

Hmm

#

That's a lot to digest, is it right to assume that a part of the solution is to avoid GC for the CPU intensive parts?

compact ingot
compact ingot
drifting galleon
#

the decision of using IL2CPP vs (mono........less so) (coreclr in the future) really depends of how much things you are using of the engine itself that are native c++ things. (coreclr) can give you better platform specific code than IL2CPP

tough tulip
# heady umbra That's a lot to digest, is it right to assume that a part of the solution is to ...

you write your code in C#, a language where you cannot manually delete an object. it has to be cleaned by a system which keeps track of references to your object.
IL2CPP doesn't avoid that. You still have a garbage collector in your IL2CPP build which does the cleanup for you just like the Mono garbage collection.
There are still many instances where AOT is slower than JIT because JIT can do some hardware specific optimization which is impossible in a complete native code. Though in most cases, unity's IL2CPP is still faster than the very old Mono's equivalent of .net 4.x
There are many platforms where you strictly need an AOT application like iOS (although i think iOS 15 brings back code generation)
IL2CPP provides more security to the code aswell since it's hard to convert a IL2CPP generated binary back to the source code whereas it's fairly simple in a IL generated dynamic libraries

alpine kindle
#

Has anyone ever tried easing in and out of a bezier curve?

#

I can't find any references for it online

heady umbra
#

Unity would still have to pipe input

green hazel
#

Hey how do i bing my arrow keys on the new system to do melee attack and when i hold them to do range attack

fresh salmon
#

Then, and only after they created and completed their Input Actions Asset, they can come back to the programming channels

green hazel
#

It’s kinda of code and input system

shadow seal
green hazel
#

But sorry

celest violet
#

hi nice people of unity, anyone knows if there is any way to add crypto currency to my game for free with out third parties? or if its too hard to implement a new crypto currency in unity? and which is the cost? thanks

faint marlin
#

Anyway to add event field in UI Toolkit
same way as this

compact ingot
compact ingot
#

if you want a "real" one (i.e. etherium based), free is impossible

compact ingot
regal olive
# compact ingot maybe for giggles?

The question certainly made me giggle hard 😂. If one were to make a cryptocurrency, unity is certainly the last software context I would use.

Now as a client of crypto or web3, sure... But as THE software context basis of the cryptocurrency?

regal olive
faint marlin
#

how to get all my component without getting unity builtin components

   var Components = script.GetComponents(typeof(Component));
       foreach (var component in Components)
       {
           Debug.Log(component.GetType().Name);
       }
woeful kraken
faint marlin
#

am trying to get all my components from one gameobject but am getting also builtin components that attached to this gameobject like : EdgeCollider2D , GraphicRaycaster ....

#

i want to get only components that made by me

woeful kraken
sly grove
faint marlin
sly grove
#

you could try excluding types from certain namespaces, e.g. EnityEngine.* but little you can do beyond that

faint marlin
#
       Component[] Components = script.transform.GetComponents<Component>();
       foreach (var component in Components)
       {
          if(!component.GetType().FullName.Contains("UnityEngine"))
               Debug.Log(component.GetType().Name);
       }
#

worked as expected , is there is down side for that ?

sly grove
olive totem
#

Even better to check for monobehavioura
s I think

sly grove
#

yeah there's a downside, it's a bit slow and there could be false positives

olive totem
#

All user components are monobehaviour

sly grove
#

Right but Unity has some MonoBehaviour as well, and third parties too

olive totem
#

Well then I'm not sure

#

Maybe check the assymbly of the type

#

Which it resides in

woeful kraken
#

Can you grab by namespace, specifically?

#

Or reference by a certain folder perhaps?

faint marlin
#

component.GetType().Namespace return NULL for classes that doesn't have a name space

woeful kraken
# faint marlin component.GetType().Namespace return NULL for classes that doesn't have a name s...
celest violet
faint marlin
regal olive
#

How different are the code in unity and Isaac gym?

#

I am trying to make RL algorithm testing on Unity but thinking of changing to Isaac gym, how different is the code?

Do I have to change a lot?

drifting galleon
regal olive
#

ya i know the language is different

#

but i'm using ROS

#

to connect with the unity

#

i'm just hoping to copy the RL from unity (that works) and put it into isaac gym

grim radish
#

Could I get help with this warning
I'm using Mirror for networking

Assets\Scripts\MyNetworkManager.cs(25,26): warning
CS0672: Member 'MyNetworkManager.OnClientDisconnect(NetworkConnection)' overrides obsolete member 'NetworkManager.OnClientDisconnect(NetworkConnection)'.

Add the Obsolete attribute to 'MyNetworkManager.OnClientDisconnect(NetworkConnection)'.

untold moth
fresh salmon
#

Precisely. There is the NetworkManager.OnClientDisconnect method that is marked as obsolete, and you are overriding it in your own class. To keep consistency, it asks you to also mark your own override as obsolete.
Better to use something else as dlich said...

untold fulcrum
#

Not sure if allowed here, but looking for someone willing to assist with some Unity coding around mini golf physics. Specifically, making the ball behave correctly (like Golf With Your Friends), work on different surfaces (mud, ice, sand, grass, etc), and work with slopes appropriate. Willing to pay a small bounty for someone with the right skills. DM for details.

pulsar isle
#

Is there an event that listens for ANY gameobject activation in the scene. Like instead of using OnEnable on each seperate gameobject, I would like a method from a single and always active gameobject to be triggered by any other gameobject activation.

drifting galleon
pulsar isle
#

Yeah I'm thinking a script with just the OnEnable and attach it to all gameobjects.

#

Is there a more "professional" way ? Maybe I'm overthinking a simple thing though.

drifting galleon
pulsar isle
#

yeah true but don;'t know what I need to do it the other way. Like do I count the number of active gameobjects on an update and when there is a new one added I call my method ?

drifting galleon
pulsar isle
#

Seems that inactive gameobjects don't get localized properly so I wanted to reapply the currently selected locale when a gameobject is enabled.

#

A hacky way but thought that it would work

drifting galleon
#

well i'd probably do it differently but here: you could create an instantiation manager singleton and only instantiate objects through it, then you can get the new instantiated object and pass it to whatever

lusty flare
#

Hey guys
How would you do to make a multiplayer system (with netcode) so that the players can be in different scene ?
Lets say player1 is the host and is in the town. player2 joined the host and now enters a house which is handled as a different scene. Player 2 now move a bucket in the house to a new location. How do i make this sync with the host which has not this scene loaded ?

pulsar isle
#

Probably need to reconsider my approach or go through each text object and reapply the localization which is a tiresome and lengthy procedure.

#

Wonder what I messed up.

drifting galleon
lusty flare
#

I do give a use case

#

I'm not talking player count, data size etc. I'm only interested in this usecase

#

It is a 'youre both client and server' type of thing. No dedicated server

drifting galleon
#

easiest way: have both scenes loaded

lusty flare
#

So the host player loads both scene but hide the one that he is not in

#

Or can you have two scene opened at once ? I'm not used to the scene system in unity

#

Because, how do i hide the house scene to the host without setting it to inactive

hushed fable
#

@limpid delta Don't crosspost.

vale flax
#

could i ask a question about a VS issue here ?

tough tulip
# lusty flare Hey guys How would you do to make a multiplayer system (with netcode) so that th...

There are 2 approaches to it. The easiest way is to load all scenes in host which are loaded in connected clients. And handle the movement directly.

Or store the data of each moved object and operation in the host. In a list or something. Then when host loads up the other scene in which changes are made, at the very beginning of scene, go through that list, and apply all the changes. either way you need to store the information somewhere.
You need to be a bit smart about the information aswell to track overwrites.
For example let's say there are two objects with object ID 100 and 200
And the client does following operation.
Move object 100 in Z axis by 100.
Rotate object 200 around X axis by 20 degrees
Move object 100 in Z axis by -100
Rotate object 200 around X axis by 40 degrees

Instead of saving information separately you can handle this somewhere in a class which has a structure like Transform

lusty flare
#

Thank you for the very detailed answer.
Lets imagine we would go for the first solution. How do you "hide" the other scene to the host ?

tough tulip
#

Load the scene additively and disable all root objects of the scene?

lusty flare
#

if you disable the scene root, doesnt it means all behavior will be frozen as well ?

tough tulip
#

It will be easier if your scene has visible objects disabled and then enabling them using a scene manager

#

your gameobjects will be inactive. the scripts in that scene will not be able to run functions like Update or do StartCoroutine

lusty flare
#

But can you still call methods ?

tough tulip
#

yes

#

you can sync up transforms aswell

lusty flare
#

Hum, good to know ! Well thanks 🙂 I can see how the first solution migth be problematic if we have lets say 10+ player in different scenes

#

But maybe i could try to put most behaviors onto a small, asset less scene, that would stay alive on the host side so that actions taken by players on other maps can be registered

#

And then as you said, save the transforms for reapplication later

warm adder
#

Hya, got a annoying little issue with my code. I'm using MemberwiseClone to clone a class. The class contains a subclass which doesnt gets cloned, but remains an active reference to the original class? Anybody know how to fix that?

flint sage
#

I usually make a copy constructor that takes an instance of a class and then reconstructs the fields

#

It's a lot faster than memberwise clone as well

sly grove
warm adder
#

Ahh okok, thanks for explaining guys

raw lily
#

Okay so, I modified code that allows to align cards in a player's hand on 2D space and ported it to a 3D space. Everything works except one thing. I need to turn the card 'rotateTowards' Vector3 target into a Quaternion. How would I go about this?

gray pulsar
# raw lily Okay so, I modified code that allows to align cards in a player's hand on 2D spa...

I assume you already saw that there is a Quaternion version of RotateTowards and you're just trying to construct the target parameter, not looking for a wholesale replacement for Vector3.RotateTowards. Quaternion.AngleAxis could be a convenient way of constructing the right rotation. Or Quaternion.LookRotation. Or w/ Euler angles like malloc says. It all depends on what information you have about your target rotation.

raw lily
#

Soo.. Euler KINDA works but I can't get the rotation from left to right around the blue (z), see in image 1-2.

#

I'll look into AngleAxis, maybe that would work?

#

Doing the 'left to right' rotation in the editor gives weird rotation values

raw lily
#

Would there be a way to apply AngleAxis on an existing Quaternion? (figured it out!)

gleaming thistle
#

long story short;
I was generating a grid using two for loops
for x=minx, minx<maxx,x++ for z=minz,minz<maxz,z++ etc

#

I switched to doing it via a spiral

#

etc

#

that works fine, except.. now the rest of the script is broken. no idea why. everything should be getting set to the same values and accessed thru the array the same

#

any thoughts as to what may cause this??

#

I set the array positions in a function with this:

int a = Tilepos.x - worldstart.x;
int b = Tilepos.y - worldstart.y;
if (creating == false) {
            if (Tiles [a, b] == null) {
                return null;
            }
                newBlock = Tiles [a, b];
        } else {

            newBlock = new Block();
//I set the values of newblock in here..
Tiles[a.b] = newBlock;
#

tilepos is just the x and z coordinates of any grid location

#

worldstart is able to be a negative number whereas an array must start at 0,0, so that's why the a and b values. this already worked before. the function sends the tilepos value, before it did it thru the two for loops, now it does it in a spiral fashion in a single for loop. both values should be identical but if I try to click somewhere it says that object value is null

wind geode
gleaming thistle
#

thanks. I always forget the little things like that

#

on that note, I actually have solved the issue

#

turns out, when it changed to spiralling, it wasn't saving the players position [0,0]

#

it was starting at 1,0

#

the spiral in action. [the green is where the spiral is currently]

hallow cove
#

hey so

#

I want to change a variable

#

and then have that trigger a function

#

and I want other scripts to be able to run logic whenever that function gets called

sand iris
#

you should probably use an event for that

hallow cove
#

I decided to use delegates, yeah

merry cedar
#

Hey, I hope you're all fine

#

I have a question

#

I'm trying to get a nice character controller, based on rigidbody.velocity

#

Is the default drag system okay ? I want to have control on the drag

#

Are animation curves a good thing to use for physics in general ?

compact ingot
merry cedar
#

They are for varying the input effect depending of the velocity

#

Like turn rate and stuff

#

Maybe it's a bad idea, that's why I ask

compact ingot
#

sounds like you want a kinematic character controller

#

you'd use a physics based one if 80% of what you want from your CC is what the physics sim does inherently, and you make minor tweaks to it

merry cedar
#

I don't use the kinematic checkmark currently

#

Yeah, I want to make customizable physics

compact ingot
#

that said, physics based has its issues, but it is also much less work if you don't need the control that a kinematic one provides

#

a kinematic one has to do all the collision handling, drag, jump, any forces etc. by itself and you need to come up with a system on how to make all of them blend together nicely, which is not trivial and gets complicated very fast

merry cedar
#

Yeah I feel this, I'm already working hard on a state machine, I let too much the physics on the side

patent dock
#

does anyone know offhand weither when writing your own SRP, if unity uploads the ambient color of the scene to the GPU, or if I have to do that myself? I'm assuming the latter since I can't find anything in the docs about it, but it never hurts to ask.

compact ingot
#

custom SRP implies that you have to DIY

patent dock
#

I assumed as much, but some things are uploaded, such as geometry and matrix transformations (presumably they're buried too deep into unity)

warm fulcrum
#

Why is GraphicsFence.Passed throwing a System.NotSupportedException when my system supports compute shaders and SystemInfo.supportsGraphicsFence reports true?

#

I've never been able to get GraphicsFences to work with this same issue

patent dock
#

from your cursory description, it sounds like a bug

warm fulcrum
#

I encountered this bug like a year ago too

#

I don't really wanna make a new project to report the bug though :V

patent dock
#

being stupid is always a possibility, if you care to upload a small reproduction to github, I can tell you if I get the same behaviour

warm fulcrum
patent dock
#

I've never used GraphicsFence before, so, do you not have to do anything first? before checking it's passed?

warm fulcrum
#

I mean technically to use them properly, yes. But in this case the fence fails to do anything so there's not much point

patent dock
#

is it possible passed reports unsupported when in reality that's just the default behaviour for a fence that hasn't been processed yet?

#

meaning you need to execute an intermediary step beforehand

warm fulcrum
#

Not as far as I know. Docs only say to build it using CreateAsyncGraphicsFence and then use it

patent dock
#

still a bug imo it reporting not supported instead of something more obvious, but since we don't have the code, we can't really check :S

warm fulcrum
#

I'll just make another project to report it. Unity should be paying me at this rate

patent dock
#

lol, fair enough, like I say, if you make a project, I can run it and tell you what the behaviour is my end.

#

just mention or pm me when you've got something and I'll let you know when I have a minute.

#

fwiw @compact ingot, the ambient scene colour does get passed as unity_AmbientSky

#

which is nice, because I was struggling to find the value exposed anywhere nearby a Render call to upload it myself 😛

west scarab
#

I'm a bit stumped on something since I rarely work with unsafe code.

Basically I have a step that deserializes a bunch of stuff, and the serializer adds all instances of a specific type to a list.
Once the deserialization is done, I want it to run a function on all collected objects.
This all works fine, but I would like to have the class that the function is being run on be a struct instead of a class. The issue being that the struct is copied somewhere along the way (I assume when I add it to the list, as the list expects an interface, which would then copy and box the struct(?)).

How would I go about doing this with structs? I guess I need keep track of the memory address of the struct, and then find the correct memory address again, and overwrite (change) the existing struct at that memory location. What would be the best way to approach something like this?

west scarab
#

It's just for convenience sake. Currently I have a struct and a class that almost do the same thing (hold a reference to an addressable address), but I need to use the class version during authoring on scriptable objects (due to the above issue), and then convert those to structs for usage in burst jobs.

#

It's not a huge issue, I was just wondering how something like that would be possible. Maybe it's a bad idea, since it kind of fundamentally bypasses how structs work.

regal olive
sly grove
#

or use ref keyword where possible

west scarab
west scarab
sly grove
sly grove
#

you'd have to store references to the class that contains the struct

crimson kettle
west scarab
quartz totem
#

Which coding style is better?

fresh salmon
#

If that's meant to be C#, then none of them
Namespaces, methods and public members must be PascalCase.
Any other language, no idea. Check your styling conventions online.

quartz totem
#

Just because it's official, it does not mean people prefer it.

fresh salmon
#

So tell me, why do you ask? Use the one you prefer :)

quartz totem
#

Arguing with a friend xD @trim current

fresh salmon
#

Is that C++, it looks like it with the public: thingies

quartz totem
#

Yeah

#

Sorry its not exactly Unity related, just trying to see which style would be preferred

pulsar roost
#
byte[] SegBuffer = new byte[TableSize];
for(uint i = 0; i < TypeTable.Length; i++) {
  SegBuffer[i/2]= (byte)TypeTable[i]<<(i%2*4);
}
``` it's been a while since I have touched unity since I have used c++ for the past little while. its telling me you cant bit shift a byte and a uint (TypeTable is a byte). what types are bit shiftable (re-casting the variables just give me more CS0019 errors)
merry robin
#

bitshifting in C# always infers type, so if its after some integer arthimetic its probably an int again

#

re-cast it

pulsar roost
#

cant implicitly convert int to byte?

#

the hell is this language I dont remember this crap lol

#

oh wait im dumb

#
byte[] SegBuffer = new byte[TableSize];
            for(uint i = 0; i < TypeTable.Length; i++) {
                SegBuffer[i/2]=(byte)((int)TypeTable[i]<<(int)(i%2*4));
            }
``` ugly. whatever, thanks
#

why does CS bitshifting only work on signed integers though?

glacial geode
#

i am trying to call a callback from a method, but the issue is said method will only call it passing 1 argument as it should, while i need to pass it with 2 more arguments to do what i need

#

any suggestions?

#

per example

#

CalculateStuff(Action Argument 1)

while i need something

CalculateStuff(Action Argument1 (and some way here to inject my other parameters))

#

any suggestions?

sly grove
glacial geode
#

No the method takes an Action, and the action needs to be of type Action (String something) [string is used as an example class)

#

but i need to call the action like

sly grove
#

so there's a method like SomeMethod(Action<String> a)?

glacial geode
#

Action (String something, MyClass1 second_argument, MyClass2 third_argument);

#

yes

sly grove
#

Ok... and...

#

where do these other parameters come in?

#

I feel that I'm missing a lot of context here

glacial geode
#

I was trying to be abstract but let me be more specific cause i see why its confusing

#

i am using a library to generate textures in realtime and one of the arguments is said action of type Action<Texture2d>

So the method would be something akin to : MakeTextures(Action<Texture2d> Do_Something)

#

But i am linking these textures in another coroutine with some items, and in order to do that i need that "Do_Something" to have more arguments

#

but i am not sure how to achieve that properly so ive been scratching my head over it

sly grove
#

How would MakeTextures be able to call the function if it's only aware of the TExture2D arg

glacial geode
#

I have no idea, and thats why i am asking the above questions

sly grove
#

I think you just need to bake those other "parameters" into the DO_Something lambda

glacial geode
#

in the lambda you say

#

hmm wait let me process this

#

Since the lambda needs to be of type

#

(Texture2d result) {} hmm

#

can i simply do it with a default parameter assignment will that work?

#

something like

#

MyClass item;
(MyClass internalItem = item, Texture2d result) {}
#

?

fresh salmon
#

Nope, default parameter values must be constant at compile-time

glacial geode
#

would a body definition in the lambda work in this context i ponder then

#
MyClass item;
(Texture2d result) {item //Or MyClass internalItem = item}```
#

or something more proper cause this example is shit

sly grove
#

bake the other "parameters" into the actual lambda code

#

I have no idea what you want to do with them ofc so that code is just very random

glacial geode
#

ah okay then its that simple i was over thinking this

#

Sorry for the abstraction xD, but thanks a lot that helped me

sinful fossil
#

Is there anyway I can render out a million cubes in unity every frame. Each cube might change its position every frame so I can't use combine mesh. (It would be nice if this wasn't limited to only cube meshes and also wasn't limited to unit locations but if there is a fast way using just a color and no mesh then I would like that too like some 3D shader)

sly grove
#

Here's a really good tutorial that introduced me to that world https://toqoz.fyi/thousands-of-meshes.html

sinful fossil
sinful fossil
#

oh ok, I actually ignored that cause I thought it wouldn't. Thank you

sly grove
#

You could also look into VFX Graph

#

if that suits your needs

sinful fossil
#

I probably will, I have been meaning to. But I will check the draw mesh instanced out first. Thanks!

sinful fossil
# sly grove if that suits your needs

"If you must move meshes while using DrawMeshInstanced(), consider using a sleep/wake model to reduce the size of these loops as much as possible." I would like them to move so what is this sleep wake model they are talking about?

sly grove
sinful fossil
#

oh ok

#

Since I am gonna do this, would there be any similar way to test for collisions of cubes and "the player" using the gpu?

sly grove
#

collisions are going to be a much harder issue

sinful fossil
#

yeah thats what I thought, oof

raw lily
#

Is there a way to limit an Editor Field to scripts implementing a certain interface only?

raw lily
sly grove
#

just drag and drop

raw lily
sly grove
#

and what is the type of your field

raw lily
#

I dragged in this

sly grove
raw lily
#

And the field is an Object

raw lily
sly grove
#

You can't just do public PlayableOnTarget onPlay;?

raw lily
#

The field just dosen't show if I do that..

sly grove
#

that makes no sense

#

it's not a MonoBehaviour

#

what did you drag

#

the script itself?

raw lily
#

Yeah.. Now I'm trying with MonoBehaviour to see if it changes anything.

sly grove
#

dragging in a script itself makes no sense at all

raw lily
#

Got it haha..

sly grove
#

You need it to be a MonoBehaviour and attached to a GAmeObject

#

then you drag the GameObject in

#

OR it needs to be a ScriptableObject, and you create an asset of it, and you drag that asset in

raw lily
#

Yeah but the whole point is to make sure only things (scripts) implementing that interface will go in there..

sly grove
#

yes

#

and it works

#

but you can't just drag a script into a slot somewhere

#

you can only drag instances of things into slots in Unity

raw lily
#

Hmm, so there's no way to put a Script as a param?

#

And then add component?

sly grove
#

To what end?

raw lily
#

It's the card's OnPlay effect that I store in the cards' scriptable object.

#

Then the whole object is made at runtime.

austere jewel
#

If you're looking to add instances of non-UnityEngine.Object interfaces to objects then you probably want to use SerializeReference

#

Though ScriptableObjects do tend to be the best way to do this sort of thing in general. SerializeReference is helpful for the cases where they don't work

raw lily
#

How would you go about adding a script to a serializable object then?

#

I mean I can just do it without the interface check..

#

I guess it's overkill at that point, had no luck with it.

austere jewel
#

I'm unsure what you mean, with the scriptable object setup you drag a SO instance into the field, and the property drawer would restrict it to having implemented that interface

#

it's not an extremely robust setup, but it works

raw lily
#

Less clean, but whatever haha

#

(and not dragable either)

austere jewel
#

What are you trying to drag?

raw lily
#

That might be part of the problem, I'm trying to have scripts as parameters.

austere jewel
#

Yeah that's not how it works unless you use SerializeReference

#

where it won't be a script, but an instance you serialize into that field

raw lily
#

Oh nice! So that would work with an interface attribute too?

steady stirrup
#

Is it possible to create a sort of tag that toggles a section in the inspector when a bool is checked in the inspector checkbox?
As an example:
isTintable: if not checked nothing appears below it

but if it is there might be a colour popping up, and int, etc.

raw lily
austere jewel
steady stirrup
#

I see, thanks

slow valve
#

Not really sure if this is the right place to ask but i am wondering if anyone can help me with randomly generated world/terrain for 2D topdown survival type game?

it will have the usual stuff like grass, sand, water, trees, rocks ect all that stuff kinda like minecraft, i have had a little look online for stuff i know that it uses perlin noise butttttt i aint really sure what the best videos of articals are to help me so if anyone could help point me in the right direction that would be great!

merry robin
#

is 3D, but premise is the same

slow valve
#

Alright thank you I'll check it out

rich storm
#

I'm making a game where you paint on objects in game. There's an extension called Free Draw that lets you draw pixels on a blank sprite on tope of the original sprite. I have a script that creates a sprite that has the exact same properties as the parent sprite and I'm wondering if it's right

merry robin
#

EventSystem

#

or actually, it looks like you just want to see if the touch point is over a rect. thats even easier. just get the rect of the canvas object you're interested in and use Rect.Contains

orchid marsh
#

Don't cross post

frigid vigil
orchid marsh
austere jewel
rich storm
#

I have a prefab with a blank sprite to paint on. But I want multiple instances of this prefab, and if I paint on one it mimics another, I made a lot of blank images and I don't know how to assign them dynamically

#

I need to make an array of these blank sprites and assign them to the paintable sprite renderer

#

automatically, and when objects are destroyed, give that blank canvas back into the pool

#

I'm not sure how to determine which blank canvas sprites are in use and are free to be assigned

orchid marsh
#

Likely they're all referencing the same sprite/image, perhaps try instantiating a new sprite/image.

rich storm
#

I have 60 blank sprites saved

#

my problem is how to pick one that isn't being used by another

#

how to determine which of the 60 blanks in the sprite pool are assigned to a renderer

#

I want to auto-pick a free sprite

#

and when an object is destroyed, put that blank canvas sprite back in the free pool

tough tulip
#

well you are assigning it. unity doesn't do it automatically by picking any Sprite from pool and automatically assigning it to the sprite renderer/image

#

before assigning take the sprite from pool. and never put it back to the queue (so that your painted sprite never ends up in a pool of empty sprites)

tiny lotus
#

Hi there :)
We had a problem with our game, we have low FPS but after profiling there is no spike or nothing clearly slow.
Our GPU / CPU usage is normal and we use only 1.5 Go of RAM.
Our scene have occlusions culling, around 1000 drawcall.
We are in unity 2020 and HDRP 10 (LTS).
Do you have any leads to help us to fix this problem?

flint sage
#

What's your frametime

tiny lotus
#

Between 10 to 30, depends of which PC is running the game

flint sage
#

Is that CPU or GPU?

tiny lotus
#

Don't know, how to display that ?

flint sage
#

It's in the profiler

tiny lotus
flint sage
#

You'll know whether the CPU or GPU is causing your performance issues

#

So you can dig further into either of those

untold moth
tough tulip
#

HDRP runs pretty crappy on low end gpus

lusty bramble
#

Hey guys, currently doing an Endless Runner Generated game targeting Mobile and I've been diving deep into Optimisations, we're making it quite heavy in decors and scenery and I've been able to pull some things out of my hat like using StaticUtilityBatching.Combine() on pre-made 'blocks' so that they could be Dynamically moved while being Statically batched.

But one thing I haven't been able to figure out if how to implement a Dynamic Occlusion System. Currently, most of the assets are hidden because of angles and whatnot, it feels like half our ressources go to waste, but due to the fact that our scene is Generated, and ever changing, I can't bake any Occlusion data (or is there a way to bake them into a prefab? or a block of 100's of prefabs ? that I'm unaware of)
I've tried pretty much every Asset on the store I could find, but they always had a catch or simply didn't work well from what I've tested. I'm currently looking into the CullingGroupAPI to see if I can do something with it. But I figured maybe someone has had a similar experience here or might be able to orient me towards appropriate resources ?

Thanks in advance! 🙂

tiny lotus
tiny lotus
#

here is one of our capture

untold moth
# tiny lotus

You're not gonna get far by just looking at the graph. Check the profiler hierarchy instead. But even just from the graph it's clear that the scripts take most cpu time.

#

Select a frame to see the details in the hierarchy view.

flint sage
#

Your CPU is spending 30ms on animation

untold moth
#

I think that's scripts color. Animation is a bit more "cyanish".

flint sage
#

Idk script looks a lot darker on my monitor

#

You'er probably right tho, since UI has the same color/thumbnail

untold moth
#

Well, only NarLoke can tell for sure.🤷‍♂️

tiny lotus
#

yes, scripts are in blue. There is no function that stands out particularly in the hierarchy and it is time to gain everywhere :/

flint sage
#

Shwo a screenshot of the hierarchy in the profiler

untold moth
tiny lotus
#

NextStep is our graph path

flint sage
#

Your pathfinding?

#

Well w/e it is, all that recursion is taking a long time and generating a fuck ton of garbage

#

There's a bunch of ot her things taking a long time as well

tiny lotus
#

some kind of visual coding

flint sage
#

Well it's expensive to calculate so optimize it

tiny lotus
#

if you have advice (regarding the code I sent) feel free to send them 🙂 Thank for your help guys! 🙂

untold moth
#

Maybe look into some existing AI solutions or algorithms that you can implement. If you traverse a graph, A* could be a decent option.

tiny lotus
untold moth
#

So is that code part of an external asset?

untold moth
wispy terrace
#

I've been using Steamworks.Net in Unity for a multiplayer game, but I need to two different steam accounts to join a game toguether for testing. I'm using virtualbox, what else do you recomend?

tiny lotus
untold moth
# tiny lotus Yes

I see. How many states does the boss have? Maybe a simpler state machine would be enough?

tiny lotus
#

You can have a boss with few node, and another with tones

untold moth
#

Well, something in your implementation is very unoptimized. I've no clue what it is since It's probably across multiple scripts.

tiny lotus
#

Ok :/

untold moth
#

There are plenty of very fast and convenient assets for ai on the store. Maybe have a look at them?

tiny lotus
#

We can't use them, all the behaviour is made by our tool :Boss maker

#

It's not just IA issues :)

#

Our game is Cellyon: Boss Confrontation and we propose a tool to players to create their own boss fight

flint sage
#

Better start optimizing then, looks like what 200 nested steps there

#

You probably don't need all of them

#

You're still generating a lot (I really mean a lot) of garbage

#

Which is really slow

#

And again, that's not your only issue. Your player loop is 70ms, that AI thing is "only" 15ms

#

15ms is your normal frame time limit to hit 60 fps

lusty bramble
#

Shouldn't you look into baking/compiling an AI logic from your node system, instead of running the node system at runtime as the AI Logic or smth?

flint sage
#

That's hard to do and even harder to do on runtime

tiny lotus
#

we made some opti on NextStep

#

and here is the profiling

#

is ProfilingScope the profiler process?

flint sage
#

Probably

#

You should be profiling a build and not the editor

tiny lotus
regal olive
#

Why is automated testing in video games something that not very many people want to do? Honestly that is the most confusing thing coming from the professional software world.

Also, possibly related... I have heard from people who say that video games should not follow patterns from external fields/industries. Whats up with that?

lusty bramble
#

I'm surprised by the time everything is taking, lets split the problems.

  • Rendering is taking a significant time on it's own, do you guys Bake Occlusion Culling, are all your scene assets Static, do you share the same Material for most objects with TextureAtlases ? How high is your PolyCount ?
  • AI scripts seem heavy, 1mb GC per frame feels huge, feels like you guys are doing a ton of Boxing or Reinstantiating code, could you not re-use cached variables ?
leaden jungle
lusty bramble
# regal olive Why is automated testing in video games something that not very many people want...

I'd say many reasons which might not be related to each other, but contrary to Software Development, where you usually want to resolve a problem, like Banking Operations or Making Api's you know what you aim for. In Video Games, especially non-AAA, they are kind of exploring where to go, and sometimes we have no real idea of what we want to achieve, systematically writing UnitTests in these cases would kill productivity.

regal olive
regal olive
lusty bramble
#

@regal olive it's not an excuse not to do them though, hats of to all that make their games robust

tiny lotus
flint sage
tiny lotus
#

we bake occlusion culling

#

for polycount I don't have exact count but not so much

regal olive
lusty bramble
#

@tiny lotus Unfortunately, only Gameobjects sharing the same Material can be batched together, so them being static may have no concrete effect currently

regal olive
regal olive
tiny lotus
#

did not know that ...

#

thx !

flint sage
#

I'm well aware of how testing works and have written plenty of tests in Unity

regal olive
#

I love talking about this sort of stuff.

flint sage
regal olive
tiny lotus
regal olive
leaden jungle
# regal olive I figured out how to make FSMs and BTs (behavior trees) extensible in a Unity co...

I mostly make my own Ai solutions, never worked with behavior trees, but I found this article interesting.
https://www.gamedeveloper.com/programming/are-behavior-trees-a-thing-of-the-past-
The solution not mentioned is a Fuzzy State Machine, it seems to solve the issues of trees, especially with complexity, a FuSM can be written out as a simple spread sheet and the system allows for emergent behavior as well.

flint sage
regal olive
flint sage
#

Developer productivity went down and they were unhappy writing code

regal olive
# flint sage Developer productivity went down and they were unhappy writing code

Interesting. I know there aren't too many folks who know how to do testing well. Like, seriously few. Most people seem to have preconceptions of what automated tests are. Most of the time, they're wrong lol.

I wonder how much of the MVVM fiasco was from bad engineering. Like, was the lead architect a cargo-cult engineer trying to pad their resume? Lol, these are things I wonder (but ultimately won't know!).

Interesting anecdote though

flint sage
flint sage
#

Biggest C# UI framework

lusty bramble
#

@tiny lotus Yeah I tried using that though it did not fit our needs for why we were trying it, I think the Atlasing worked on it, the basic idea is to make a single Giga-texture which your material will use for all prefabs and that your UV will use this texture as a sort of "spritesheet" and will choose the right one in consequence if I'm not mistaking.
Because of this, it can all be rendered together, since they don't need to change any reference or values in the rendering loop ^^

#

@tiny lotus here is an exemple

leaden jungle
# regal olive Bro! Heckin' heck yea, thanks for this resource! I'm going to read it now. For m...

I think I watched most the GDC talks on Ai, this is one of my favorites and was the bases for the FuSM I made.
https://www.youtube.com/watch?v=tAbBID3N64A&t=2s
And here is more on left4dead, the game was pretty revolutionary in terms of Ai
https://steamcdn-a.akamaihd.net/apps/valve/2009/ai_systems_of_l4d_mike_booth.pdf?fbclid=IwAR0lr9t-_SZrF7vmxRr6UkSACUOgvrfnu3YNIqb3IlqCnB9BcCmznhElgoU

GDC

In this classic GDC 2012 session, programmer Elan Ruskin shows a simple, uniform mechanism made for the Left 4 Dead series for tracking thousands of facts and possibilities, allowing intelligent characters to remember history, cascade from special to general cases, and select the optimal dialog, script, behavior, or animation for every situation...

▶ Play video
regal olive
flint sage
#

Creating lambdas and allocating closures is a good way to kill your performance if you do that, you'll have to be careful to not do that

regal olive
leaden jungle
regal olive
regal olive
leaden jungle
regal olive
versed pewter
#

Does any one know why suddenly my physics get called 30 times, after my app have been running for a couple of minutes? They normally get called 2-3 times per frame, and then suddenly they get called over 20 times per frame. This eventfully freezes my app.

untold moth
versed pewter
#

I have tried to set a fixed fps of 30. And my fixed timestep to 0.0333.
Before doing any of that it still eventually would freeze

#

I noticed that ToString does a lot of GC allocate, is ToString a performance issue?

untold moth
#

Also, I'm not entirely sure, but seems like you're running quite some code in fixed update..? Maybe it's worth taking it out of it?

#

You don't have enough GC to cause any performance issues imho

untold moth
#

Maybe that's what's causing the issue?

versed pewter
#

This is what I am running in FixedUpdate is it too much?

untold moth
#

I don't know. How much cpu time does it take?

versed pewter
untold moth
versed pewter
versed pewter
untold moth
untold moth
versed pewter
#

Only on the phone

untold moth
#

Well, it's probably overheating and going into a low performance mode. Then the fixed updates just accumulate because they can't keep up and snowball into a lagfeast.

#

How soon does it happen?

versed pewter
#

Happens after around 5 min

#

Heard something about adaptive performance, could this be something to look at?

untold moth
#

I'd check memory consumption and overall performance. Optimizing the game might make it last longer.

untold moth
versed pewter
#

Well the thing is that it actually not rendering anything other than a static UI for the player, so behind the scene every light, texture, camera etc er turned off

untold moth
#

@versed pewterby the way, can you sort by the cpu time?

untold moth
#

Seems like fixed update shouldn't be your main concern.

#

Not sure, but the first one is probably your gpu not keeping up..? Can you expand it?

#

And then you also have 52 ms of scripts updating.

versed pewter
fresh salmon
#

The GPU waits for something before presenting the frame 🤔 do you have VSync enabled?

versed pewter
#

Have not set VSync anywhere

fresh salmon
#

Hm, I also get results about the wrong OpenGL version being in use

untold moth
versed pewter
charred monolith
#

Does anyone know how to make a GUI Inspector panel similar to this? Where pressing a button leads to certain serialized fields?

#

The only method I found is that these GUIButtons lead to a different inspector panel

untold moth
versed pewter
#

Do notice this spike in Audio CPU when the lagging starts

untold moth
versed pewter
untold moth
#

Okay. That's probably in response to the lag, not causing it.

#

Anyways, what shaders are you using?

versed pewter
#

Are not using any shaders, basically I only have a terrain mesh that is hidden from the user with a UI

untold moth
versed pewter
#

Yes the standard build in Unity UI

untold moth
#

What about other objects in your scene?

versed pewter
#

I have 3 cubes that are red, using the standard shader.
I have a terrain but the texture is never displayed, I only use the terrain collider part.

untold moth
#

Ok, then what exactly is happening in the game?

versed pewter
#

I have a player with a rigidbody that are pushed around a terrain with GPS coordinates where the cubes are different sound objects

#

I do have some glitches, but should not be part of the performance problem as it also happens when the player is static

#

I do like a solution to the terrain clipping though 😅

#

I have released a older prototype before, but it was just moving around a flat 3D space, so the new thing in this version is the height of the world

untold moth
versed pewter
untold moth
versed pewter
#

AddForce() instead?

untold moth
#

or setting velocity

versed pewter
#

Can I use the same vector

untold moth
#

You mean this?

Vector3 newPosition = Vector3.MoveTowards(rigidbody.position, position, speed * Time.deltaTime);
versed pewter
#

Yes

untold moth
#

No, you need a direction vector.

#

You could get the direction from current position to target, normalize and multiply by some speed value.

rugged wagon
#

I need to render a 16:1 17280x1080p for a 75m wide LED display
can one workaround the
GameView reduced to a reasonable size for this system (8192x512); UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Im working with a RTX 3090

cedar saddle
versed pewter
cedar saddle
# rugged wagon I need to render a 16:1 `17280x1080p` for a 75m wide LED display can one workaro...
GitHub

Unity C# reference source code. Contribute to Unity-Technologies/UnityCsReference development by creating an account on GitHub.

rugged wagon
drifting galleon
cursive horizon
#

it sounds like you are building an interface around a query language

#

so every When is some kind of GameEvent which exists already?

#

it sounds like DoThis isn't really the hard part

#

then i think you are writing queries

#

I would think of it like this:

  1. Query some data
  2. Check some rules against that data
  3. If (some | all | any) rules (pass | fail) -> DoThing
#

if you knew what the events would be and what args they were passed, you could hook into those directly

#

but since you don't, it sounds like you need to support testing rules against relatively arbitrary queries

#

i started once and decided it wasn't worth it

cursive horizon
#

do you have odin? it lets you do this pretty easily

#

there are some free ones too, but odin is the only one i've actually used

#

it's very worth it if you're doing any custom inspector stuff

#

what's your time worth? I felt the same for years and then felt like an idiot for not having paid $50 to save dozens of hours earlier

#

well then i envy you, and you should ignore all my advice because efficiency is all i know

#

(Except the thing about TypeCache. You'll want to use that for the custom inspectors you'll be writing)

raw schooner
#

so i don't even know where i'd begin to ask this, but i got a few small questions about mono? i know it's not unity-specific, but i'm doing some work on a desktop app that reads a game's memory to display values.
since you can simply use mono to find all loaded classes, i can easily get the class that's of the most use to me. the class inherits from a Singleton<T>, easy enough, just go to the parent. the tricky part is that Singleton<T> has a nested private class Nested within it which finally has the internal static instance; field i need.
does anyone know how to get the nested _MonoClasses in a _MonoClass instance?

misty glade
#

(context - I'm getting this error while trying to import a newtonsoft json custom converter)

#

Can't tell if it means anything bad

compact ingot
misty glade
#

the base type is in newtonsoft.. should be OK?

compact ingot
#

your custom converter is probably used in an attribute right?

misty glade
#

I dunno.. I went down the path of writing a custom json converter and it was too difficult for me to get working properly so.. I remodeled the data instead

silent rivet
#

I'm having a weird problem were I'm making sprites from texture2ds with differeint image hashes, but they all just turn out to be blank images in the built game.

This is my code:


        for(int x = 0; x < sheetTileDimensions.width; x++) {
          for(int y = 0; y < sheetTileDimensions.height; y++) {
            Texture2D subMap = new(tileWidthInPixels, tileWidthInPixels);
            Color[] colors = spriteSheet.GetPixels(
              x * tileWidthInPixels,
              y * tileWidthInPixels,
              tileWidthInPixels,
              tileWidthInPixels
            );
            subMap.SetPixels(
              0,
              0,
              tileWidthInPixels,
              tileWidthInPixels,
              colors
            );

            UnityEngine.Tilemaps.Tile tile 
              = ScriptableObject.CreateInstance<UnityEngine.Tilemaps.Tile>();
            tile.sprite = Sprite.Create(
              subMap,
              new Rect(0,0, tileWidthInPixels, tileWidthInPixels),
              new Vector2(0.5f, 0.5f),
              tileWidthInPixels
            );
            Hash128 tileHash = tile.GetTileHash();
            // see if this tile already exists in this world:
            if(@return.all.TryGetValue(tileHash, out UnityEngine.Tilemaps.Tile foundLocal)) {
              //ScriptableObject.Destroy(tile);
              tile = foundLocal;
            } else if(tileTypes.TryGetValue(tileHash, out UnityEngine.Tilemaps.Tile existing)) {
              //ScriptableObject.Destroy(tile);
              tile = existing;
            } else 
              @return.all.Add(tileHash, tile);

            @return.inPlace[x, y] = tile;
          }
        }

gettilehash just returns imageContentsHash

Anyone know how I could debug this further? I can see the colors going in are different than eachother and all have an alpha of 1 so they should be making an image right?
And the hash verifies they're all different

misty glade
#

Yeah, but I tried it both as an attribute and as an option creating the json serializer

#

maybe the attribute was causing the issues (with the unity mono helper thingy)

#

i was trying to do a Dictionary<T, int> converter but ... just having a heck of a time with it, so I just remodeled it to Dictionary<enum, int>

compact ingot
#

right... i try to keep custom converters very simple aswell, usually to fix inconsistencies in APIs

misty glade
#

i migrated to System.text.json for a while (because cosmos depends on it) but got so fed up with the things it doesn't do, next to newtonsoft, so i went back

#

but the custom dictionary key was still a sticking point, and i couldn't get it to work.. issues in camel casing.. issues with the converter.. configuration issues importing the DLL into unity.. etc.. all of that fiddly-ness went away when i just made the DTO more sensible with a primitive as the key

#

i didn't even really NEED the custom object as the key, it was .. a little convenient for some other reasons but not required

#

anyway.. lesson learned, i'll try not to be smarter than i am

inland halo
cedar saddle
silent rivet
#

Does anyone know if maybe i'm doing something wrong here?

            Color[] colors = spriteSheet.GetPixels(
              x * tileWidthInPixels,
              y * tileWidthInPixels,
              tileWidthInPixels,
              tileWidthInPixels
            );
            subMap.SetPixels(
              0,
              0,
              tileWidthInPixels,
              tileWidthInPixels,
              colors
            );

maybe it has to do with miplevels? I don't know what those are tbh

cedar saddle
#

what's wrogn?

inland halo
#

i might found it

#

if (crouched == p_state) return;

#

if i edit it and make it, if (crouched = p_state) return;

cedar saddle
#

oh no no no

#

that's absolutely terrible

inland halo
#

ye i know

cedar saddle
#

if you really want to fix this you'd probably want some kind of state machine

inland halo
#

my weapon is going up

cedar saddle
#

like an enum for the current state instead of multiple bools

inland halo
#

can you make a smal example if you want

cedar saddle
#

not really

#

you can google it

inland halo
#

okay thanks

#

i increased the ground check raycast and now im able to do everything again

#

if i crouch and stand up my weapon goes up and never comes down

topaz geode
#

How do i instantiate something on my mouse cursor

#

cz the cordinate system used by vectors and input.mouseposition is different apparently

cedar saddle
#

2d or 3d?

topaz geode
#

2d

cedar saddle
#

you have to convert it back

topaz geode
#

i see

regal olive
#

Time... time to make a utility a.i. library

#

I have FSMs, HFSMs, and BTs. Utility theory a.i. may afford more designer friendly a.i. agents. Lets see

regal olive
#

Easy. The secret sauce:

public interface ICalculateUtility<out T>
{
    public T CalculateUtility();
}

Pretty easy to imagine how it can be attached to a BT implementation >.>

regal olive
#

^_^

#

Moving on to hierarchical task network (HTNs)

compact ingot
compact ingot
drowsy torrent
#

Hey all. So, about 10 years ago I remember having to do some hacky stuff to get meshcollider to generate during runtime. In the editor it works if you toggle the component off and on, in code you need to do the same, probably with an IEnumerator so you can skip a frame and all.

#

Now I'm messing up with that kind of code but wondering if there isn't a more elegant solution now

compact ingot
# drowsy torrent Now I'm messing up with that kind of code but wondering if there isn't a more el...

Per unity docs:

You should not modify mesh geometry that is used for colliders because the physics engine has to rebuild an internal mesh collision acceleration structure every time you change the mesh. This causes a substantial performance overhead. For meshes that need to collide and change at runtime, it is often better to approximate the mesh shape with primitive colliders like capsules, spheres and boxes.

drowsy torrent
#

yeah, I know. This is a procedural planet. I might have to find a different way to do this.

#

in principle all I should need is the height, since it has no overhangs. But I don't know of any way of integrating that into the physics engine

compact ingot
#

you can assign a new sharedMesh to the collider, it will then be used as collider after cooking

drowsy torrent
#

like a terrain

#

but I can't use native terrain system with a round planet. At least not easily

regal olive
#

Often that leads to agents getting pew pew'd in the face... But that's what we're here for, aye? ^^

compact ingot
#

problem is that such solvers are NP complete

regal olive
#

Is that a bad thing? Also, elaborate? heh

compact ingot
#

so a practical one would require some creativity but would be very neat to have if it is sufficiently 'easy to use' and performant

regal olive
#

is the concern the time it takes for a planner to find a valid enough plan?

#

like, it might take too much time?

compact ingot
#

usually you do what you do for all N-SAT problems... ant colony, monte carlo, ANN, etc. i.e. stochastic approaches that approximate the correct solution

#

but i'm thinking more of something really simple, usefuly, practical... not theorem prooving... just fun ai that can appear to understand a few simple dependencies in the world

#

do you know of a recent game project that uses HTNs successfully?

regal olive
#
public class PlannerUnitTests
{
    [Test]
    public void APlannerCanComeUpWithAFinalPlan()
    {
        var sut = new Planner(new CompoundTask(), new WorldState());

        var result = sut.Plan();
        
        Assert.NotNull(result);
    }
}

My planner returns a "final plan" now 🙂

#

Er, on second thought maybe it just returns a "plan"

regal olive
compact ingot
#

those arent recent

#

they are from the golden age of planning AI

regal olive
#

Fair.

compact ingot
#

just about before "everyone" gave up on the whole planning ai thing because its uneccessary for people having fun

#

but i havent looked into it for years, so was hoping you had some new intel

regal olive
compact ingot
#

i think it would be super fun to build one and to make a game with it, but useful, no

regal olive
#

I'll bite... What is the ai type you reach for when you want to make some ai?

#

Don't say FSM

compact ingot
regal olive
#

.> don't just add an H to FSM

compact ingot
#

utility, BT or just some reflex agents

#

you can get a lot out of reflexes

regal olive
#

reflexes? -- goes to gameaipro to look it up --

compact ingot
#

reflex agents are basic robotics/AI idea where the agent respond directly to a sensor input

#

with no internal representation of the world

regal olive
#

sounds like the "Controller" pattern, like a thermostat

compact ingot
#

yes, like a PID

regal olive
#

word. I comprende

compact ingot
#

basically insect behaviour, bees, ants stuff like that

#

supposedly very effective for team sport ai

regal olive
#

I'm thinking now of how to make an a.i. agent out of PID stuff

compact ingot
#

flocking/swarm behaviour

#

you could use your utility ai to implement a reflex ai

regal olive
#

So will an ai agent want, like, one thing?

compact ingot
#

if you keep the utility functions simple, i.e. on a regular expression level of expressiveness

#

no, it just has no state

#

no memory

regal olive
#

O...kay now that I'm thinking about this, maybe a game object can have n > 1 number of controllers that tries to get the game object into some expected state.

compact ingot
#

yes

regal olive
#

PIDs have CurrentState and ExpectedState. That's how a thermostat knows to turn on the HVAC system when its too cold

compact ingot
#

N reflex agents or util-functions fighting each other

regal olive
#

I think a Controller monobehaviour can make sense.

#

Interesting conversation. Reflex agents, eh.

#

The controllers could fight each other. Like, what if one controller sets a character destination in it's locomotion component

compact ingot
#

doesn't really matter if we're true to the textbook definitions of reflex agents. all just ideas

regal olive
#

I agree with that. I find that thought is required to translate the ideas into a unity context, lol

compact ingot
#

absolutely

#

the battle of controllers should not happen on the transform, but in a virtual space, and the result of the battle is applied to the transform

#

it helps to study how bees, ants and flies operate to understand what a working reflex system looks like

regal olive
#

-- thinks about research bee dances -- hmm, you might be right

compact ingot
#

a key aspect is making it stable

#

but not too stable

regal olive
#

Kinda sounds like we're designing a sims ai system

compact ingot
#

you need a PID for stability... have one set of reflexes that explore and one set that conserves

compact ingot
#

its fun to think about

regal olive
#

I almost think that PID controllers might be good for reflexes. I also think another AI system could serve as the higher level desire

#

Like, a halo grunt has a reflex to dodge a gernade

compact ingot
#

wicked problem though... somewhere in there, you need to place a human player

regal olive
#

but what it does might be best defined by something else (bt? planner?)

compact ingot
#

the most art-directable AI is certainly a BT

regal olive
#

Yea, a.i. agents need to be fun for the player. BTs. Lmao. Months of my life

compact ingot
#

thats kinda what i understand that most people use nowadays

regal olive
compact ingot
#

i have built my own BT and utility is just a node in the graph

#

i use that just like select and sequence

#

i found that article quite interesting back then, but the headline is just clickbait

#

i haven't really gone deep with any ai system other than BTs

regal olive
#

Have you made a squad level BT?

compact ingot
#

started one

#

not squad level but "village"

#

really small village

regal olive
#

Same. Started. Thinking about solving the "grunt flees when elite dies" problem in a different way

#

Right now my implementation is pretty bespoke

compact ingot
#

an idea that i havent really tried yet is giving all npcs certain abstract needs and traits (via utility functions) that have relatively concrete actions that would satisfy them (think feeling of security vs excitement and fearful vs bold)

#

each of these are values that rise/deplete automatically over time and also via actions and well, that drives what the npc decides to do

regal olive
#

I use Actions and Func<T, ...> so my monobehaviours can pass in concrete implementations of stuff

#

Not sure if that is helpful, but its what I do

compact ingot
#

maybe the concrete actions are a BT again, but the decisions are just one step removed from explicitly stating sequences/priorities

compact ingot
#

i do that everywhere when i build a solver/engine-type system

regal olive
#

Have you implemented smart objects yet? They're basically objects that have a BT in it, so a.i. agents can "know" how to use them

compact ingot
#

thats a neat idea... not done that yet

regal olive
#

It's a thing that roller coaster tycoon and the sims use. I guess it allows them to make game content more easily

#

Like, maybe a weapon has a Tactics function that returns a BT that describes what tactics to use. E.g. a shotgun has the agent be more aggressive

compact ingot
#

that basic idea comes up frequently in recent years... kinda inversion of control in terms of ai/leveldesign

regal olive
compact ingot
#

also the whole procedural animation post-processing thing via IK... animate the object, not the character

#

dwarf fortress is also interesting for ai

regal olive
#

Do you know what type of ai dwarf fortress implements?

#

https://gamedev.stackexchange.com/questions/32813/how-does-dwarf-fortress-keep-track-of-so-many-entities-without-losing-performanc

Omg. Reading this thread made me think about a scheduler for a.i. Right now, basically all BTs have a thinking rate hard coded where the BT will then be Tick()ed. Maybe, just maybe... Maybe I would want to add in a scheduler to try and spread out the load of a.i. agents thinking per frame.

The idea is to 'bump' lower priority A.I. to frames where not a lot of a.i. thinking is happening.

I would really need a situation where performance is an issue to justify complexing my software with a scheduler. Neat. I'm going to put this idea in my back pocket.

#

It's like similar to the concept of level of detail (LOD) for a.i. (agents further away don't have to think as much -- see rick and morty when Jerry is in a simulation for an example)

glass anvil
#

I see a cool example for say an open world online rpg, with massive draw distances. You don't want to outright hide enemies too close because then you get that nasty pop-in. an LOD would allow higher AOI range so that would be a nice combo I think.

glass anvil
#

area of interest

sand iris
#

thx 🙂

regal olive
fervent sage
#

Thinking of doing a neural network for a TCG; Any suggestions on asset packs as a base which would work well with a NN with a lot of inputs/outputs?

rugged wagon
rugged wagon
#

hey guys I would need to change a core function in Unity
GameViewSizes.cs this one here
anyway I can temper with it? and in wich .ddl is it compiled into?

plucky laurel
#

i know people used cecil for such things, i just dont know whats the unity view on it. probably wont care

regal olive
#

hey guys, does anyone know how to rotate along a custom axis, im trying to set up a dual axis turret where the base rotates only along its transform.up while the second axis only spins along its transform.right, second axis is parented to the first but i need it so even if the base is 45 degrees to the right, it will still only spin along its up axis to aim at the target, any tips guys?

rugged wagon
haughty glacier
raw lily
#

I'm making a Card game and Cards have their effect scripts. Do you guys think it's a bad practice to have the Card Effects Script act like a god script? (have access to almost anything)

sage radish
# rugged wagon hey guys I would need to change a core function in Unity GameViewSizes.cs this o...

If you want to do it by hand, you can use something like dnSpy to edit compiled .net dlls. But you can also modify .net assemblies at runtime using the Harmony library:
https://github.com/pardeike/Harmony
But you'll have to get your hands dirty with IL.

GitHub

A library for patching, replacing and decorating .NET and Mono methods during runtime - GitHub - pardeike/Harmony: A library for patching, replacing and decorating .NET and Mono methods during runtime

rugged wagon
#
using System;
using UnityEditor;
using HarmonyLib;
using System.Reflection;
using UnityEngine;

namespace AntiRenderSizeRestriction
{
    [InitializeOnLoad]
    public class Patch
    {

        static Patch()
        {
            var harmony = new Harmony("com.unity.game");

            var mOriginal = AccessTools.Method(AccessTools.TypeByName("GameViewSizes"), "GetRenderTargetSize");
            var mPrefix = AccessTools.Method(AccessTools.TypeByName("Patch"), "Prefix");

            Debug.Log(mOriginal);
            Debug.Log(mPrefix);

            harmony.Patch(mOriginal, new HarmonyMethod(mPrefix), null);
        }

        static bool Prefix(ref Vector2 __result)
        {
            __result = new Vector2(16000, 1000);
            return false;
        }
    }
}

Worked like a charm

unique ermine
#

Do you guys have any ideas on how to create dynamicly generated territorys?
So how would I slice my terrain into territorys.
I haven't found any source online sadly on how smth like this is done
Perhaps a algorithm would work? Perlin noise?

#

After thinking about it I came up with my own solution:
Instead of dynamiclly creating it, I'll just make an editor where I can create my own territorys by adding new vector3's, store them in a List.

Now if I want to check if a player is in Territory B I just loop trough the list, check if player is inside of the area and boom.
I guess that works.

regal olive
# raw lily I'm making a Card game and Cards have their effect scripts. Do you guys think it...

Yes, typically a god script is a code smell. That said, if it is what makes sense to you in order to make working software that's fine! Seriously!

However, I would definitely use the strategy pattern/abstract interface techniques to accomplish this.

The idea is to make contract that applies to all card side effects (base class, or interface). All side effects abide by this contract by subclassing or implementing the interface... The 'thing' that handles side effects just uses the 'generic' contract API. This allows the details of a side effect to be pushed to the concrete implementations of the contract.

I've seen folks use scriptable objects + this technique to great effect as scriptable objects allow one to tweak specific values as assets.

Cards then, maybe, all have a list of side effects. Maybe even 'vanilla' damage can then be thought of as side effects ^_-

raw lily
#

And also they are stored in Scriptable Objects. I also think it makes sense that if cards can affect almost anything in the game (even the rules), maybe that makes sense that they act this way. Anyways, really appreciate the in depth reply!

regal olive
#

Hmm, I'm contemplating your OG question again... Sounds like you've already considered the info I shared before I shared it, which is great.

Now I think it's a question of design. The concrete classes-- (sorry, wife called, had to take) -- I think the question is how much context will any given side effect need.

I think what you're grappling with is the question "what do all side effects need to know" versus "what does this specific side effect need to do its job.

Honestly, if it were me... I wouldn't assume anything in common and I would let every side effect concrete class be responsible for receiving it needs to operate.

regal olive
silver hill
#

Hey, I'm trying to refactor my input handling to an event-based model using InputSystem, but I'm not sure how to handle certain cases in which input receiver is not the player character. For example, I can have a script subscribe actions from PlayerInput to methods inside PlayerMovement. However in some cases I need to subscribe methods from other object, such as vehicles. I don't want to keep a concrete reference in PlayerInput, because different vehicles can bind the same actions to completely different methods.

I thought about creating in interface that declares void Bind(InputActions actions) and add it to vehicles, then let them bind their actions themselves.
I also thought about a system which sends input based on a stack or a linked list. Like if you bind PlayerMovement's move method to Move action but then Vehicle's one, Move action would only trigger Vehicle methods, as it's the last entry. Then when the player exits it I could just pop it and the input will go to PlayerMovement. This way I could also have a ui which requires keys operate while in a vehicle, or something.

As you can see I'm really damn confused and likely overcomplicating things a lot so if anyone has better suggestions please let me know lol

raw lily
#

But after that.. they can literally call anything from the BattleManager to more specific rules and values. So what they can know is everything but each script will be limited to a thing or two. But possibly just one per script, and if there are multiple it would be a list of scripts in the cards' Scriptable Object, each representing an effect.

regal olive
#

@raw lily Are you seeing any downsides to this approach? Do you feel like you're doing something wrong, or are changes seemingly complex to make? Just curious as you must have felt something to ask the original question 🙂

raw lily
#

That was helpful btw, thanks!

regal olive
raw lily
latent violet
#

Hello guys, I'm having problems with cloth, does anyone have an idea or pointer how to fix it? In short game about sailing and I'm using cloth to simulate sail interaction with wind. Currently I'm lowering sails by scaling them on Y axis, and my problem is that cloth does not scale well. But if I disable cloth component and enable everything for that moment is fine.

#

Is it some wierd cloth feature or am i doing something really stupid?

mortal ivy
#

I have an object which, during runtime, is created as the child of another object. I want it to follow this object but I don't want it to follow the scale. Does anyone know how?

latent violet
#

Can you explain it a bit better?

mortal ivy
# latent violet Can you explain it a bit better?

I'm creating an arrow object in 3D that can be scaled by using X and Z. But the user can create more arrows stemming from the original, and i want them to follow the original if it's position changes. However i don't want it to follow the scale changes

latent violet
#

Hope it helps

#

I mean you multiply parent scale with some number and then you divide child's scale with the same number

mortal ivy
latent violet
humble onyx
#

there are the constraint components for that

#

you can have a position and rotation constraint on the object so that it follows the player but does not scale

#

@mortal ivy

long ivy
#

Has anyone used Firebase InAppMessaging with Unity on iOS? I'm trying to send a message containing a clickable link, but clicking that link just dismisses the ingame modal dialog instead of launching the browser as expected. I was wondering if there might be some Plist config that I missed?

echo cove
#

if i'm making a neural network to have gestures in XR be recognized, do I need to have something like a "start recording" button and then feed that data into a CNN after the recording ends, or should I use something like an RNN? if I do the latter, do I end up with the neural network doing its thing every frame? wouldn't that like, totally tank performance?

cedar saddle
#

depends how performant your NN is

#

Liek how big and how much data it has to process

#

what's XR?

echo cove
#

VR/AR

#

right now I've just about implemented the former of the two systems I hypothesized

#

but I'm a bit bothered by the idea of having to press a button to start tracking an input. ideally, it'd all be automatic

cedar saddle
#

why use ML for that?

#

in any case I'd imagine you would feed like 1s of positioning data?

#

like position/orientation

#

Those can be smoothed a bit so you don't have to provide 1 data point per frame

#

I don't think you'd need too big of a network for that so running it once per frame or every couple of frame should be doable

#

Depending on what kind of platform you are targeting

compact ingot
cedar saddle
#

But again, I'm not sure you really need ML for taht

echo cove
#

yeah right now i'm just tracking the position/orientation of each hand, plus the positions of each fingers, so it only comes out to like 42 inputs

#

i'm a bit lost as to how I'd do it without ML, honestly

compact ingot
#

what kind of gestures are we talking about?

cedar saddle
#

you'd probably make a curve out of the motion

#

and use some heuristics

echo cove
#

the gestures involve both hand position and the hand pose itself, the curve isn't a bad idea

cedar saddle
#

how complex are the motions?

echo cove
#

some of them more complex than others, but overall, i'd say they're kinda complex

compact ingot
#

can you quantify "complex"

echo cove
#

between switching hand poses quickly and also some big sweeping hand movements, at least

echo cove
cedar saddle
#

for example

#

this does involve a "start" trigger but I could see this being adapted to not need it

echo cove
#

yeah it'd be more complex than that

#

because it's not just hand position, it's also like, "where are your fingers and what are they doing"

cedar saddle
#

those are probably easy to quantify with if/else

echo cove
#

so it should be able to gauge whether or not I'm transitioning from a closed fist to an open palm as I thrust my hand forward, or somethin glike that

cedar saddle
#

rather than using ML

echo cove
#

I should also clarify that I'm thinking about adapting this to use oculus' hand tracking, which isn't as straightforward to my knowledge. i'd at least need some kind of pose estimator

echo cove
# cedar saddle and use some heuristics

I also haven't worked with heuristics (or ML-agents at all), so perhaps i'm unaware of what you're trying to explain here. from what I understand, wouldn't it be a pain to code the gestures manually by hand rather than just record some training data?

burnt shard
#

anyone have a script for breaking up a polygon collider into convex shapes?

#

oh I swear I googled before asking but now that I've asked I found a way. I can do Collider2D.CreateMesh then use the mesh's triangles. It won't be optimal but that's fine

#

can probably throw some algorithm in the middle to combine triangles into polygons

rich storm
#

Hey everyone, I'm not sure if this is the right place to put this, but I got my paint sprites to work finally, but the actual painting is too square. The painting code itself uses a y for loop inside an x for loop, which makes a square and I use a random range int to determine whether a pixel is actually painted or not. Can I make this array a circle somehow? like only paint pixels in this square array in a circular pattern if that makes sense?

#

I want them to look more like randomized paint streaks but I don't think I can do that with math

#

unless this looks ok

golden garden
#

Hey @rich storm . I would use a circular alpha mask on the texture instead of trying to trig your way through two for-loops to know "ignore this x,y coordinate".

rich storm
#

I'm already using sprite masks on the objects

#

but you do get what I'm trying to do

golden garden
#

i think i get it. but i think the mask will work. your randomized paint sprite is still a sprite. youre applying that as a mask to the object beneath it (the buliding). im saying put a mask on TOP of your generated sprite.

rich storm
#

I'm not using a sprite to determine the actual paint

#

I'm applying a color to random pixels onto a sprite on top of the object

#

so I have a script

#

that determines where in world space the paintbrush hit is

#

turns that into pixel coordinates

#

and paints on a writable sprite on top of the building sprite

golden garden
#

if you google ascii print circle youre gonna find a hundred people talking about ways to do this

rich storm
#

isn't there a formula for a circle where if the formula is true, then paint the pixel?

golden garden
#

ask yourself what it's calculating. is it a circle? is what a circle? the arbitrary (x,y) you've pulled out of a hat?

#

Is it within a circle of... what? what's the center coordinate? what's the radius?

rich storm
#

it paints an 8x8 square

golden garden
#

hmm actually.

rich storm
#

within the loop is technically an 8x8 grid

#

and it knows every x and y

golden garden
#

you could do a distance equation from your random (x,y) to the origin of where your paintbrush is. if that is less than a distinct amount (a radius), then it can paint.

#

Because the corner of a square will be too far from the center.

rich storm
#

yea I have it save what center_x and center_y is

#

it's actually a paint area of 17 x 17

golden garden
#

okay, so as you randomly paint pixels, check if the random (x,y) youve decided is <width/2 from your center. if it is, paint it, if it isnt, dont.

rich storm
#

I think Distance checks World distance, and this is local pixel distance but I'll have to play with the distance number

#

I can just comment out the randomization for now

#

and just make a solid paint

#

and lower the number until it looks like I want

golden garden
#

distance being that vector2.distance or basic geometry with pythagorean theorem

#

you can do it, you just have to play around with it.

#

if you randomly keep yourself a set amount of distance from a center point, youre going to make a circle. Think you hold out a stick in any direction from your body. You spin. Youve made a circle.

#

The tip of the stick cannot get any further away from the center in any direction.

rich storm
#

yep

#

thank you

#

holy cow it's done, that was way easier than I thought it would be thanks!

golden garden
#

you did the distance check thing and it worked?

#

super glad to hear it. 🙂

thick cairn
#

Heyy. I am just starting to learn advanced concepts in C#. I am creating an FSM for an AI. (I know Behavior trees is also an option but i started using FSM already).
Now providing context to the states, instead of providing the entire AI script (or statemachine), i only pass what the state needs for better encapsulation.
So let's say i have a Vector3 variable _target where i store the target where the AI needs to go.
Now, one of the states(say the one that handles chasing the player) needs to constantly update the _target but since its a vector3 i can't pass it as reference. (Using ref won't help since i am only passing the context in constructor and storing them in the state class' own variables and you can't store ref like that).
Instead of passing the entire script to the state, I instead created two delegates that can get or set the _target and passed those as context.
But i feel it might get messy as more variables create such demand. It would have been so convenient if you could pass the property get and set as parameters amd store them but it isn't possible.
Is there a better workaround this?

viral flame
#

Why not just store the whole context?

#

Depending on how the context works / if you're included a "world blackboard", states will want to write back to the context eventually (imo).

plucky laurel
#

yeah a single context with whatever ai operates on (and interfaces with other systems, like same destination can be set by any node, then used by movement)

thick cairn
#

yes, storing the whole context will make it super easy. But i am trying to keep the states as dumb as possible. Only knowing what they are using.
As to why i am doing this, i guess this approach is a habit and is usually a good thing. This might be an exception.
For now the AI is relatively simple though, maybe creating a more complicated AI will eventually make me passing the whole context.

plucky laurel
#

you will refactor later and its going to be pain to work with

#

when for gameplay reasons some nodes that on the first glance only need couple of bits of data, suddenly need to - know if the agent is alive, know if it sees the target, know the distance to something, etc etc, all just to return a basic bool "can move" and stuff like that

#

agent behaviors are very volatile

thick cairn
#

yes.... between passing ten parameters to a state just to maintain encapsulation and passing the whole context, the latter would be the obvious choice.
I just needed to know what approach people take in game development since i am relatively new. Thanks.

plucky laurel
#

most off the shelf solutions offer some sort of "blackboard" where each variable is wrapped into an object, which is convenient for designers, but its a nightmare to debug

#

i prefer hard properties, since you can always use "find references" and see all the read/writes, instead of dealing with strings

thick cairn
#

i am unfamiliar with "blackboard" system , i will have to research it.
Yes, hard properties are easier.

formal nexus
#

https://pastebin.com/Qhx1mjNu

so i have a problem with my physicsbased fishing line. when i remove (reel in the fishing line) a node it extends the other nodes in small increments im not sure why that is.

#

am i inputing the wrong position data to the transform move?

fervent sage
#

How do you make sure values changed in an editor script are saved?
I have an editor script which formats and caches things in my menu. But after running the script, if I leave the scene and then come back none of those changes are saved.
Seems a bunch of people talking about how you need to edit fields in a specific way, or set the specific edited objects to dirty, but I am editing a lot of objects.
Is there any way to just force-save all the changes in the scene through editor script?

plucky laurel
#

Is the scene itself marked as dirty after changes?

deep finch
#

Hey, i have system made of two scripts, one of them connects objects with fixed joint and creates hinge joints on the point where i click objects, and then hinge joints go to the second script variables where the script have to make line renderer between those hinge joint. But its not working, the point apear not in the place where hinge joint is and anchor position of hinge joint is messed up, i think the problem is when it goes to assigning anchor in connector script. But i dont know how to fix it.
First script(the connector) https://pastebin.com/enMXpnyU
Second script(the visualiser) https://pastebin.com/xKX6NeQZ

grave berry
#

Hello everyone, this is my script. It seems to be fine but I get this error code can someone help me pls?

thin mesa
grave berry
#

Thank you:)

merry cedar
#

Hey, I'm trying to access the scene view camera but I'm harassed by null reference exceptions, even when I reference a new camera, is there a trick to know about that ?

thin mesa
#

if you're trying to use Camera.main make sure your main camera is actually tagged as MainCamera
(if you are referring to the scene view camera for the editor then ignore me, i'm dumb)

compact ingot
#

SceneView.camera is the scene view camera

silver hill
#

Am I reinventing some kind of pattern here?

  public class Character : MonoBehaviour, IActionListener<MoveAction>, IActionListener<LookAction>

Cause calling these action like this is disgusting (but it works like I want tho)

    public void DispatchAction<T>(T a) where T : IBaseAction
    {
        foreach (IActionListener<T> listener in listener.GetComponents(typeof(IActionListener<T>)))
        {
            listener.OnAction(a);
        }
    }
#

And at this point I'm not even sure it makes sense and need a second opinion

regal olive
regal olive
hollow garden
#

im not any advanced coder by any means so take this with an extremely ginormous grain of salt but that just looks like c# events to me

#

listeners and events are probably fundamentally different tho so 🤷‍♂️

proven phoenix
#

This might be more of a math and geometry question but I am trying to find a point for coding an enemy behaviour in my game

#

can somebody tell me if its possible

#

to calculate point C

#

from knowing position B, position A, and radius r

#

and if its possible, how do i do it

#

wait

#

it hink i know it

#

🐒 neuron activates

spiral burrow
fresh salmon
#

That's a tangent, [BC) is a tangent to A

proven phoenix
#

thats my neuron activation

#

but now i am stuck again

#

lol

spiral burrow
proven phoenix
#

uhh

#

not really i am trying to make an enemy that finds a destination within a min and max range to player, while moving a minimum to a maximum distance

#

so im trying to like intersect circles to get angles

#

and then turn angles into positions

#

but for that i need tangent

spiral burrow
#

Uh

proven phoenix
#

i think i can just use Math.Asin

#

ok nvm i dont know math

proven phoenix
#

ok i did it

#

i needed acos by calculating the cos with r / BA

#

but it confused me because exceptions were thrown if B (player) was too close obviosly, then cos was not between 0 and 1 anymore because the triangle was fucked up

#

i conquered math, back to using inbuilt functions lol

#

but hey its working

silver hill
#

The reason I didn't use an Event is because it seems easier to pass action as a class 🤔

#

That way I can have as many argument and as complex and logic specific to that action

#

Just need to cache it somehow so I don't getComponent every time I guess

proven phoenix
#

@spiral burrow i dont know if u care but here is why i needed it

#

the red marks are the areas i want my enemy to move next

#

(the red square is the enemy)

covert osprey
#
public static float EaseOutBounce(float start, float end, float value)
    {
        value /= 1f;
        end -= start;
        if (value < (1 / 2.75f))
        {
            return end * (7.5625f * value * value) + start;
        }
        else if (value < (2 / 2.75f))
        {
            value -= (1.5f / 2.75f);
            return end * (7.5625f * (value) * value + .75f) + start;
        }
        else if (value < (2.5 / 2.75))
        {
            value -= (2.25f / 2.75f);
            return end * (7.5625f * (value) * value + .9375f) + start;
        }
        else
        {
            value -= (2.625f / 2.75f);
            return end * (7.5625f * (value) * value + .984375f) + start;
        }
    }

can someone tell me why the author chose to do value /= 1f at the beginning ? I can only imagine this exploiting some weird IEEE quirk but i really cant think of any ?

#
 float d = 1f;
        if (value < d * 0.5f)

or this ??

#

Im either missing something or this is stupid

covert osprey
#

okay nevermind that code is just fucked

sly grove
gleaming thistle
#

general question; do yall have any good resources on learning about setting up networking? (such as for an mmo for example, being able to join "rooms"/"worlds"/"servers" that are separate.
saving and loading to.. somewhere. etc.)
I'm still quite aways from doing this sort of thing, but would love if someone could point me in the right direction. cheers.

gleaming thistle
#

👍

fervent parcel
#

Hello, "EditorGUILayout.PropertyField(serializedProperty, new GUIContent(name), false" does not work properly when it comes to arrays/lists past 2019. I want a way to drag and drop into the array/list field but I want to turn off the ability to show children. is there a way to do that? in 2020+

reef wren
#

I have a question related about C# and not exactly unity.
when i write some extension method for monobehaviour, something like public static void DoSomething(this MonoBehaviour mb)
when i want to access it from within the monobehaviour inherited script, then i'm not able to call this function directly from within it
for instance:

internal class SomeClass : MonoBehaviour
{
  void Awake()
  {
      DoSomething(); //doesnt compile
      this.DoSomething(); //works correctly
  }
}

is there a way to avoid this?
i'm creating a library with some monobehaviour extensions. i dont want people using it to deal with this problem

plucky laurel
#

no

tough tulip
reef wren
lavish plume
#

Anyone know what the heck this error is? Looks pretty funky and I just opened my project today to see it. Restarting it did nothing

tough tulip
lavish plume
#

I'll give it a shot. Thanks!

grizzled flume
#

Heya!

I'm looking at using native code within Unity for the first time, though I can't get an example working and keep getting an EntryPointNotFoundException: example

Here is the code I am trying to run:
cpp header

ifndef MathsService_API_h
#define MathsService_API_h __declspec(dllexport) 
#define EXPORT extern "C"
EXPORT float example();
#endif

cpp body

  float example() {
    return 5.0f;
  }

(the above is built into a DLL called MathsSevice)
csharp

    [DllImport ("MathsService")]
    private static extern float example();

Then this is called on start

Debug.Log(example());

Thanks in advance!!

olive totem
#

Not sure if it's actually mandatory, but I think you should also add the extern "C" where you implement the function

  extern "C" float example() {
    return 5.0f;
  }
#

Also might help to add CallingConvetion.Cdecl where your DllImport attribute is

#

Like so

[DllImport("MathsService", CallingConvention = CallingConvention.Cdecl)]
private static extern float example();
#

This is how I do it with my own native libraries

#

In your header you can do this

extern "C"
{
    extern float example();
    extern void some_other_function();
}
tough tulip
fervent parcel
grizzled flume
#

Thanks for the suggestions @olive totem @tough tulip. Seems like I am still getting the same issue but I am just going to make a brand new VS project and try that - in case I have altered a build setting that may have caused this (unlikely I know) but if there are other suggestions on what to try then it'll be appreciated!

lavish meteor
#

Is there any code to get the color of a pixel when using pixel art. The GetPixel() method works with ints so GetPixel(1, 1) would only get the Color of the intersection between 4 pixels

#

I'd basically need a method that would exept floats or doubles

novel wing
#

Or are you saying you want an interpolated color of multiple pixels yourself?

#

Just tested it and it does give back the color of a single pixel at specified X & Y coords

lavish meteor
#

These are pixels having 1 width and 1 height each. They intersect at full numbers. Since you can only use full numbers in GetPixel() it wouldn't really work as intended or am I wrong?

cursive horizon
tough tulip
#

GetPixel is just a pixel value. it cant be in decimal. maybe you're using a different map

cursive horizon
#

you aren't 'going up one and over one' you are literally retrieving the cell 'identified by' (1,1)

#

or i suppose you still are, but in discrete units 'grid cells' not 'distance from the corner'

lavish meteor
#

So in a texture the coordinates (1, 1) wouldn't be the same as if the texture would be applied to an object?

cursive horizon
#

when you apply it to an object it maps based on the uvs which are normalized 0-1, but that's got nothing to do with the pixels in the image itself

novel wing
cursive horizon
#

that's the 'image' of a smiley all zoomed in, and you can access any grid square through it's coordinate ID (in this case the image is 10x10 pixels)

lavish meteor
#

Alright, that helps a lot. When reading out the color of different pixels in the picture that I've shown, would there be a way to check on how dark they are?

novel wing
cursive horizon
#

if it's not, you could convert it to HSV and read the value? someone who knows color math better would have to confirm if that is actually useful or not

lavish meteor
cursive horizon
#

ah yeah, if you are building the image you can basically pack whatever info in there you want

cinder zinc
hallow elk
#

Question for you guys. LineRenderer.GetPositions says the following in its documentation:

public int GetPositions(out Vector3[] positions);

However, Intellisense says to use it without the out keyword, and using the out keyword gives a compile error that I cannot use the out keyword. Why is this?

tough tulip
alpine snow
#

this is more of an algorithm question but i have a tilemap based implementation of A* pathfinding in my game. i'd like to extend it's functionality to have a function that takes a source tile S and positive int d as input and returns a list of all tiles T for which there exists a path from S to T of length at most d. by length i mean the number of tiles that make up the path, not euclidean distance. i'm trying to find a good way to implement this function

#

there's the obvious exhaustive search approach where i could iterate through the entire tilemap, compute a path from S to a given T, and check the length of the path. but this is clearly not efficient, and also not very natural in terms of the problem. i should be able to start from S and compute paths traveling away from it, stopping when i reach length d

long ivy
#

You want a different algorithm for that, breadth-first search starting at S. You can use your distance heuristic in it

alpine snow
#

does BFS work when the graph has cycles? i've mostly used it in the context of trees

long ivy
#

Yes. Keep a list of visited tiles

alpine snow
#

alrighty thanks, i'll look this up. i didn't even think about that

grim oxide
#

I just encountered a strange consistency... I had a bug that was arising from not having a strict script execution order for a pair of scripts, but what was strange about it was, the initial instance of the actor with the two scripts always worked correctly, and any immediate duplicates of that first actor worked correctly, so somehow they were consistently arriving at the "correct" execution order without guidance

#

BUT, any SECONDARY copies (duplicates of a duplicate) would ALWAYS have the "incorrect" execution order

#

100% of the time

rich storm
#

I'm making a painting game, and each paintable object has a Collider2D. Some objects overlap, how do I detect multiple colliders at once and pick the one closest to screen

grim oxide
#

I didn't even realize execution order was consistent per-object between updates

#

@rich storm Sounds like you want to do a ray from camera

#

sec

rich storm
#

I have a paintbrush collider

#

that hits objects colliders

compact ingot
grim oxide
#

If you just need the collider closest to the screen at a given point then I think raycast is more efficient than like boxcasting and sorting by distance or something

#
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, layerMask);
compact ingot
#

actually a basic spherecast should automatically return the closest one

grim oxide
#

Yea

rich storm
#

it's a 2d game and they all have the same z

grim oxide
#

Oh 🤔