#archived-code-advanced
1 messages · Page 159 of 1
HA I TOTALLY FORGOT I BOUGHT THIS BOOK ON KINDLE
It’s good for thinking about the problem space of making games. Applying the techniques are a challenge.
On the same wavelength; have you looked into gameaipro.com yet? They have high quality content of the sort like game programming patterns.
◌ I haven't heard of that, but I'll check it out ◌
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
your method is called Shoot but the RPC you try to call is shoot (yes, there is a difference)
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?'
you mean this
[PunRPC]
void Shoot ()
{
that should be shoot instead of (Shoot
example
Change the string where you call the RPC to match the method name
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
yea i've tried with 2017, 2019, and 2022
I could stream it, right now i've restarted unity like 3 times and it's still happening
@silent rivet @thin mesa found problem photonView.RPC("Shoot", RpcTarget. All, 0); should be photonView.RPC("Shoot", RpcTarget. All);
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
is IL2CPP converting the entirety of the C# code to C++? ie if I build some ML, will it be fast?
it stands for intermediate language to c plus plus so basically yes
@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
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?
IL is just-in-time-compliled to native machine code by the CLR, it is not interpreted.
as the name implies, IL2CPP complies the immediate language i.e. MSIL to C++ and that C++ is then compiled to be executable natively on your target platform by a compiler that is aware of some tricks how IL code targeting the UnityEngine can be optimized. That C++ compilation also benefits from all the research that goes into LLVM.
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
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
Has anyone ever tried easing in and out of a bezier curve?
I can't find any references for it online
So in theory, if I were to avoid using unnecessary OOP cases and used gene sequencing using Interned strings, would I be fine?
Unity would still have to pipe input
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
Nah, it's more of a #🖱️┃input-system question
Then, and only after they created and completed their Input Actions Asset, they can come back to the programming channels
I don’t rly know in what category it belongs so i typed it everywhere lol
It’s kinda of code and input system
Perhaps you should take some time to enjoy #📖┃code-of-conduct, which says you shouldn't spam the entire server
I ment i sended it in the codes channels not in every channel
But sorry
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
Anyway to add event field in UI Toolkit
same way as this
i assume you know how crypto works... so nothing is keeping you from building your own
But why though
if you want a "real" one (i.e. etherium based), free is impossible
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?
I'll take you seriously. I was a believer in the web3 religion until I was reminded of the dream of web1. Web1 >>>> web3 >> web2.
What is the goal you are trying to achieve? Are you sure you want to make your own crypto (and all its headaches)? Or do you think you're trying to make a web3 (NFT! Smart contracts! Boutique block chains! etc) game/software/platform?
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);
}
If you're trying to grab all items under a scene, or a particular gameobject, I usually round them up via their Transform, since every object in Unity has to have a Transform
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
In that case you'll want to specify the exact names of the components you're wanting to attach.
For example, if your custom component is MyNeatBehavior then you'll want to get them by that type
Try var components = script.GetComponents<MonoBehaviour>() although that still won't exactly get only your componnents. Probably best to mark the components you're interested in with an interface and use that
am making a tool that get only components of the developers so i don't know what name they choose
good idea
this isn't going to really be possible. It's not going to be possible to distinguish scripts the user made vs those from third party assets or MonoBehaviours created by Unity.
you could try excluding types from certain namespaces, e.g. EnityEngine.* but little you can do beyond that
worked !
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 ?
Probably better to check the namespace, not the fullname https://docs.microsoft.com/en-us/dotnet/api/system.type.namespace?view=net-6.0#system-type-namespace
Even better to check for monobehavioura
s I think
yeah there's a downside, it's a bit slow and there could be false positives
All user components are monobehaviour
Right but Unity has some MonoBehaviour as well, and third parties too
yes exactly
Can you grab by namespace, specifically?
Or reference by a certain folder perhaps?
component.GetType().Namespace return NULL for classes that doesn't have a name space
https://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null This might pertain to you but I'm not 100% certain.
thats why i dont want to add crypto, coz its all too much headache. but thanks i think i will forget about that for a while.
fullname is includes namespace
https://docs.microsoft.com/en-us/dotnet/api/system.type.fullname?view=net-6.0
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?
extremely. isaac gym does not use c#
everything
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
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)'.
Sounds like you're using some old API in your code. Maybe look at the latest documentation. Also,probably better ask in #archived-networking
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...
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.
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.
no, but you could implement that yourself pretty easily
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.
wouldn't that be the exact same behaviour as with normal gamobjects??
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 ?
no. but what's the purpose anyway?
It's related to this: #archived-code-general message
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
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
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 ?
Thank you for the input. I think I'm missing the scope and I'm getting lost though.
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.
that absolutely depends on how you want your game to function and what design decisions you make
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
easiest way: have both scenes loaded
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
@limpid delta Don't crosspost.
could i ask a question about a VS issue here ?
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
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 ?
Load the scene additively and disable all root objects of the scene?
if you disable the scene root, doesnt it means all behavior will be frozen as well ?
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
But can you still call methods ?
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
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?
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
It has done exactly what you asked. Copied all of the fields. If you want to make a deep copy you'll have to write that yourself
Ahh okok, thanks for explaining guys
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?
Maybe you're looking for this?
https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html
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.
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
Would there be a way to apply AngleAxis on an existing Quaternion? (figured it out!)
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
ie:
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
You can use "if (!creating)" instead of "if (creating == false)" :)
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]
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
you should probably use an event for that
I decided to use delegates, yeah
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 ?
if you use velocity directly for your CC, all physics will be overwritten each update
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
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
I don't use the kinematic checkmark currently
Yeah, I want to make customizable physics
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
Yeah I feel this, I'm already working hard on a state machine, I let too much the physics on the side
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.
custom SRP implies that you have to DIY
I assumed as much, but some things are uploaded, such as geometry and matrix transformations (presumably they're buried too deep into unity)
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
from your cursory description, it sounds like a bug
Yeah I mean it sure feels like a bug. Only other thing I can find online is https://forum.unity.com/threads/graphicsfence-passed-throws-an-exception.1077485/ which is pretty much identical to what I'm experiencing, and goes a step further using reflection to prove it's broken
I encountered this bug like a year ago too
I don't really wanna make a new project to report the bug though :V
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
All you need to repro is run these lines:
GraphicsFence fence = Graphics.CreateAsyncGraphicsFence();
Debug.Log(fence.passed);
I've never used GraphicsFence before, so, do you not have to do anything first? before checking it's passed?
I mean technically to use them properly, yes. But in this case the fence fails to do anything so there's not much point
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
Not as far as I know. Docs only say to build it using CreateAsyncGraphicsFence and then use it
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
I'll just make another project to report it. Unity should be paying me at this rate
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 😛
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?
Why the change to structs?
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.
IMO It's only a bad idea if it produces non working software or there isn't a reason to do it.
you basically need to replace the struct wherever it lives
or use ref keyword where possible
Yeah, some kind of reference to the memory location and then overwrite that.
I can't store a list of refs though can I?
if the struct is a member of a class, for example, then you overwrite it with a reference to the class
unfortunately no
you'd have to store references to the class that contains the struct
Sadly no
The issue with that is I would need to check during serialization for each class and check if that class contains any instances of the type in question, instead of checking on the type during serialization. Would probably mean a lot of boilerplate / error prone code...
Which coding style is better?
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.
Just because it's official, it does not mean people prefer it.
So tell me, why do you ask? Use the one you prefer :)
Arguing with a friend xD @trim current
Is that C++, it looks like it with the public: thingies
Yeah
Sorry its not exactly Unity related, just trying to see which style would be preferred
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)
bitshifting in C# always infers type, so if its after some integer arthimetic its probably an int again
re-cast it
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?
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?
I don't understand. If the method only takes one parameter what good would it do to pass in extra parameters?
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
so there's a method like SomeMethod(Action<String> a)?
Ok... and...
where do these other parameters come in?
I feel that I'm missing a lot of context here
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
How would MakeTextures be able to call the function if it's only aware of the TExture2D arg
I have no idea, and thats why i am asking the above questions
I think you just need to bake those other "parameters" into the DO_Something lambda
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) {}
?
Nope, default parameter values must be constant at compile-time
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
No I'm talking about like...
tex.Whatever();
otherParameter1.Whatever();
otherParameter2.Whatever();
});```
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
ah okay then its that simple i was over thinking this
Sorry for the abstraction xD, but thanks a lot that helped me
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)
Use a compute shader and DrawMeshInstancedIndirect
Here's a really good tutorial that introduced me to that world https://toqoz.fyi/thousands-of-meshes.html
GPU instancing is a graphics technique available in Unity to draw lots of the same mesh and material quickly. In the right circumstances, GPU instancing can allow you to feasibly draw even millions of meshes. Unity tries to make this work automatically for you if it can. If all your meshes use the same material, ‘GPU Instancing’ is ticked, your ...
will that allow for different colors if its all instanced?
oh ok, I actually ignored that cause I thought it wouldn't. Thank you
I probably will, I have been meaning to. But I will check the draw mesh instanced out first. Thanks!
"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?
don't worry about it right now I think
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?
collisions are going to be a much harder issue
yeah thats what I thought, oof
Is there a way to limit an Editor Field to scripts implementing a certain interface only?
I did find this:
https://www.patrykgalach.com/2020/01/27/assigning-interface-in-unity-inspector/
But I just get an empty list in the editor
that preview window thing never works
just drag and drop
yeah.. had same issue with it.. not sure why.
what did you try to drag in
and what is the type of your field
I dragged in this
What is PlayableOnTarget
And the field is an Object
You can't just do public PlayableOnTarget onPlay;?
No sadly..
The field just dosen't show if I do that..
wait how did you drag this in
that makes no sense
it's not a MonoBehaviour
what did you drag
the script itself?
Yeah.. Now I'm trying with MonoBehaviour to see if it changes anything.
dragging in a script itself makes no sense at all
Got it haha..
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
Yeah but the whole point is to make sure only things (scripts) implementing that interface will go in there..
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
To what end?
It's the card's OnPlay effect that I store in the cards' scriptable object.
Then the whole object is made at runtime.
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
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.
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
Yeah, in my case nothing gets listed though which is what I've been trying to fix without luck..
But yeah ig i'll move on and it's up to me to not put the wrong thing there ig!
Less clean, but whatever haha
(and not dragable either)
What are you trying to drag?
That might be part of the problem, I'm trying to have scripts as parameters.
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
(and it has no default inspector unless you use a plugin like mine https://github.com/vertxxyz/Vertx.Decorators)
Oh nice! So that would work with an interface attribute too?
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.
Thanks, might try out your extension. I feel like before continuing with the Editor stuff I should definitely see if what I want to do works!
https://github.com/dbrizov/NaughtyAttributes this has an [EnableIf(...)] attribute that sounds like that
Otherwise, you can head over to #↕️┃editor-extensions to ask about creating your own editor which is the manual way of doing it
I see, thanks
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!
Alright thank you I'll check it out
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
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
Don't cross post
it is unityforum
#📖┃code-of-conduct Rules
Stick to one discord channel at a time with your questions
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
Likely they're all referencing the same sprite/image, perhaps try instantiating a new sprite/image.
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
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)
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?
What's your frametime
Between 10 to 30, depends of which PC is running the game
Is that CPU or GPU?
Don't know, how to display that ?
It's in the profiler
I cannot have it yet, but could you explain what information and solution this information will give us?
You'll know whether the CPU or GPU is causing your performance issues
So you can dig further into either of those
Low fps and spikes are not the same. You seem to just have consistently low fps/hight CPU time. Looking at the profiler hierarchy might give a clue on what's being slow. It would also help you figure out wether it's CPU or GPU bottleneck as Navi mentioned.
What cpu and GPU do you have?
HDRP runs pretty crappy on low end gpus
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! 🙂
i7 @3Ghz and GTX 1070 Ti
We could not have GPU FPS because we Graphics Jobs activated, we need to disable it to have that :/
We notice that UI is very fps consuming, we will investigate in that way
here is one of our capture
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.
Your CPU is spending 30ms on animation
I think that's scripts color. Animation is a bit more "cyanish".
Idk script looks a lot darker on my monitor
You'er probably right tho, since UI has the same color/thumbnail
Well, only NarLoke can tell for sure.🤷♂️
yes, scripts are in blue. There is no function that stands out particularly in the hierarchy and it is time to gain everywhere :/
Shwo a screenshot of the hierarchy in the profiler
Show a screenshot. But if nothing stands out it just means that everything is slow/unoptimized.
NextStep is our graph path
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
it's a custom graph for our boss behaviours
some kind of visual coding
Well it's expensive to calculate so optimize it
if you have advice (regarding the code I sent) feel free to send them 🙂 Thank for your help guys! 🙂
Maybe look into some existing AI solutions or algorithms that you can implement. If you traverse a graph, A* could be a decent option.
Also, check #854851968446365696 on how to post large blocks of code.
oh sry :/
Here is the code of our NextStep function : http://pastie.org/p/21BWAEB7pmMQ1Unv9IFC0r
we already have a look :/
So is that code part of an external asset?
GraphPath - is that your own script?
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?
Yes
I see. How many states does the boss have? Maybe a simpler state machine would be enough?
It depends, there is now rules. You can do as many as you want
You can have a boss with few node, and another with tones
Well, something in your implementation is very unoptimized. I've no clue what it is since It's probably across multiple scripts.
Ok :/
There are plenty of very fast and convenient assets for ai on the store. Maybe have a look at them?
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
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
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?
That's hard to do and even harder to do on runtime
we made some opti on NextStep
and here is the profiling
is ProfilingScope the profiler process?
It is :/
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?
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 ?
that's neat I'm interested in extendable Ai as well. I made a Fuzzy State Machine, FuSM, so states can be added and removed on the fly, also it's all scriptable object so the behaviors can be altered on the fly as well. The state is selected by a series of conditions, if all conditions are true the state fires off. It seems fairly efficient so far.
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.
I figured out how to make FSMs and BTs (behavior trees) extensible in a Unity context. My FSMs and BTs are vanilla C#.
And then I use Func<T, ...> and Action to serve as interface points for monobehaviours
@regal olive it's not an excuse not to do them though, hats of to all that make their games robust
we don't use TextureAtlases, but all our scene assets are statics
It kind of depends, there's some testing in framework components usually but testing game code is just a giant pain. e.g. it's impossible to test all actions a user can do, like testing whether the user can fall out of the map at any point
Interesting response. Its the idea of automated tests as a way of killing productivity.
I would push back on one point -- articulating an set of acceptance behavior of a software is universal. A video game can have a collection of software behavior descriptions that are either true in the game (or false).
@tiny lotus Unfortunately, only Gameobjects sharing the same Material can be batched together, so them being static may have no concrete effect currently
I recommend reading "Unit Tests: Principle, Patterns, and Practices." In that book it describes triaging what elements of your software is worth testing (and what isn't). You don't have to test everything. You do want to write the software you do test in a testable way
I think writing tests is a pain because not too many experts have translated how to do the practice into the gaming context, is what I think
ohhh
did not know that ...
thx !
I'm well aware of how testing works and have written plenty of tests in Unity
Awesome! I figured, since you have an opinion. Thanks for sharing, btw 🙂
I love talking about this sort of stuff.
Possibly! Al though, I'd say that would require a custom game engine that is built with testing in mind. Which most engines and very much including Unity is not
Yea... Maybe? I've written tests for wordpress, which is notoriously horrible for writing tests. It was made in an age before testing was a big concern.
I use much of the same stuff I've learned writing tests for wordpress in unity. Long story short, use the humble object pattern and push the unity framework/library to the edge of your core logic.
we bought, a long time ago, this asset : https://assetstore.unity.com/packages/tools/modeling/mesh-baker-5017 to bake material / mesh and texture, I did not take time to use it. Maybe it could help?
I don't think you need to rearchitect unity to write great automated tests for our games, imo.
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.
That's exactly why it's a pain, it reminds me of a company I used to work for that attempted to create an MVVM framework on top of Unity. Which involved writes a ton of wrappers for existing objects, in turn this made writing new code slow, painful, and error prone
Bro! Heckin' heck yea, thanks for this resource! I'm going to read it now. For me, I read articles from gameaipro.com and think about them a lot 🙂
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
WPF engineers trying to apply the same logic to Unity, no bad intentions just inexperience
WPF? Whats that?
Biggest C# UI framework
@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
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
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...
The biggest thing that I found liberating was being able to write vanilla C# "library" code in unity, and then allow monobehaviours to pass in methods via the Action and Func<T, ...> interface points. So clutch
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
A person after my own heart. I've watched that GDC video before. It's fantastic. In fact, it's been a while since I gave it a watch. I'm so much more experienced in AI now.
ya after watching that I was doing fuzzy pattern matching for everything lol
So far, my performance budget hasn't been violated in any of the games I've made. I figure if it ever does become a problem, I have a few patterns I could reach for to reduce the performance burden. Honestly, it hasn't had too much of an impact using this technique but I'm only at the scale of ~100-150 a.i. agents in my scenes.
Again, are you me? I do that too but haven't done it with fuzzy FSMs. All my stuff had event brokers after I learned about them. Great way of learning when to and when not to use techniques 🙂
lol cool to meet another Ai enthusiast.
There's literally tens of us. Tens! We could definitely fill up a small subway sandwhich location 😸
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.
Could be you messing with time scale / fixed timestep in code or maybe it just doesn't keep up with the updates causing it to snowball into more and more fixed updates per frame.
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?
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
How are you setting it?
Maybe that's what's causing the issue?
This is what I am running in FixedUpdate is it too much?
I don't know. How much cpu time does it take?
I am setting it in a start method on an object, maybe it should be on awake?
I can't say anything specific without seeing your code.😅
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Around 1.78ms to 2.92ms
Doesn't sound too bad.
You didn't mention that it was on phone. Or does it happen in the editor too?
Only on the phone
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?
Happens after around 5 min
Heard something about adaptive performance, could this be something to look at?
I'd check memory consumption and overall performance. Optimizing the game might make it last longer.
Never used it, so can't really say anything.
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
@versed pewterby the way, can you sort by the cpu time?
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.
The GPU waits for something before presenting the frame 🤔 do you have VSync enabled?
Have not set VSync anywhere
Hm, I also get results about the wrong OpenGL version being in use
What are the rendering stats sayin in the profiler?
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
Doesn't look too bad. What shaders are you using?
Do notice this spike in Audio CPU when the lagging starts
Is that thing at the top right audio?
These are the color codes for audio
Okay. That's probably in response to the lag, not causing it.
Anyways, what shaders are you using?
Are not using any shaders, basically I only have a terrain mesh that is hidden from the user with a UI
You have to be using shaders. Otherwise nothing will draw on the screen. Even ui.
Yes the standard build in Unity UI
What about other objects in your scene?
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.
Ok, then what exactly is happening in the game?
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
How are you moving the player?
https://pastebin.com/iA2XVCTw
Inside of FixedUpdate
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Should probably avoid MovePosition and transform.position assignment if you want proper collisions.
AddForce() instead?
or setting velocity
Can I use the same vector
You mean this?
Vector3 newPosition = Vector3.MoveTowards(rigidbody.position, position, speed * Time.deltaTime);
Yes
No, you need a direction vector.
You could get the direction from current position to target, normalize and multiply by some speed value.
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
ha I googled it and found your forum post lol
Okay gonna take a break now, but thank you so much for your time and help
I wonder if there's any way for use to edit that line https://github.com/Unity-Technologies/UnityCsReference/blob/61f92bd79ae862c4465d35270f9d1d57befd1761/Editor/Mono/GameView/GameViewSizes.cs#L430
thanks im out of office now but I will have a look tomorrow 🙂
i mean you can just set your aspect ratio to 16:1
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:
- Query some data
- Check some rules against that data
- 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
do you have odin? it lets you do this pretty easily
Odin Inspector is a plugin for Unity that lets you enjoy all the workflow benefits of having a powerful, customized and user-friendly editor, without ever having to write a single line of custom editor code.
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
https://github.com/dbrizov/NaughtyAttributes can do a lot
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)
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?
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/AssemblyHelper.cs#L302 Lovely. Eating the exception.
(context - I'm getting this error while trying to import a newtonsoft json custom converter)
Can't tell if it means anything bad
wild guess but maybe its missing a base type that is only known at runtime
the base type is in newtonsoft.. should be OK?
your custom converter is probably used in an attribute right?
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
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
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>
right... i try to keep custom converters very simple aswell, usually to fix inconsistencies in APIs
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
im having trouble if i Crouch i cant pres crouch again and stand up, if i slide and the slide stops i am crouching (code https://gdl.space/iqidufevok.cs)
you only uncrouch when you jump or when you sprint
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
what's wrogn?
thanks but i am not able to jump or sprint when i am in crouch
i might found it
if (crouched == p_state) return;
if i edit it and make it, if (crouched = p_state) return;
ye i know
if you really want to fix this you'd probably want some kind of state machine
my weapon is going up
like an enum for the current state instead of multiple bools
can you make a smal example if you want
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
How do i instantiate something on my mouse cursor
cz the cordinate system used by vectors and input.mouseposition is different apparently
2d or 3d?
2d
i see
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
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 >.>
what sorcery is this? <out T>
what do I google to look this up
covariance invariance contravariance... there will be a quiz
while you're at it, you could you turn that utility AI into a modal logic AI, that would be something. A system that can do some simple modal inference from statements and facts.
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
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.
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
you can assign a new sharedMesh to the collider, it will then be used as collider after cooking
can you elaborate?
like a terrain
but I can't use native terrain system with a round planet. At least not easily
Ha, I think that's kind of what HTNs are attempting to do. It's a forward planning system that basically takes a game world state, tries to find a plan that gets an a.i. agent(s) into a a desired game state.
Often that leads to agents getting pew pew'd in the face... But that's what we're here for, aye? ^^
problem is that such solvers are NP complete
Is that a bad thing? Also, elaborate? heh
so a practical one would require some creativity but would be very neat to have if it is sufficiently 'easy to use' and performant
is the concern the time it takes for a planner to find a valid enough plan?
like, it might take too much time?
there exists no efficient algorithm to solve generic modal logic problems
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?
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"
Killzone 2, and Transformers: fall of cybertron
Fair.
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
so you think a forward a.i. planner might not be super useful?
i think it would be super fun to build one and to make a game with it, but useful, no
I'll bite... What is the ai type you reach for when you want to make some ai?
Don't say FSM
hell no
.> don't just add an H to FSM
reflexes? -- goes to gameaipro to look it up --
reflex agents are basic robotics/AI idea where the agent respond directly to a sensor input
with no internal representation of the world
sounds like the "Controller" pattern, like a thermostat
yes, like a PID
word. I comprende
basically insect behaviour, bees, ants stuff like that
supposedly very effective for team sport ai
I'm thinking now of how to make an a.i. agent out of PID stuff
So will an ai agent want, like, one thing?
if you keep the utility functions simple, i.e. on a regular expression level of expressiveness
no, it just has no state
no memory
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.
yes
PIDs have CurrentState and ExpectedState. That's how a thermostat knows to turn on the HVAC system when its too cold
N reflex agents or util-functions fighting each other
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
doesn't really matter if we're true to the textbook definitions of reflex agents. all just ideas
I agree with that. I find that thought is required to translate the ideas into a unity context, lol
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
-- thinks about research bee dances -- hmm, you might be right
Kinda sounds like we're designing a sims ai system
you need a PID for stability... have one set of reflexes that explore and one set that conserves
yeah... that thought always comes up 😄
its fun to think about
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
wicked problem though... somewhere in there, you need to place a human player
but what it does might be best defined by something else (bt? planner?)
the most art-directable AI is certainly a BT
Yea, a.i. agents need to be fun for the player. BTs. Lmao. Months of my life
thats kinda what i understand that most people use nowadays
thoughts on this article? https://www.gamedeveloper.com/programming/are-behavior-trees-a-thing-of-the-past-
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
Have you made a squad level BT?
Same. Started. Thinking about solving the "grunt flees when elite dies" problem in a different way
Right now my implementation is pretty bespoke
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
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
maybe the concrete actions are a BT again, but the decisions are just one step removed from explicitly stating sequences/priorities
seems very reasonable
i do that everywhere when i build a solver/engine-type system
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
thats a neat idea... not done that yet
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
that basic idea comes up frequently in recent years... kinda inversion of control in terms of ai/leveldesign
exactly right on the inversion of control
also the whole procedural animation post-processing thing via IK... animate the object, not the character
dwarf fortress is also interesting for ai
Do you know what type of ai dwarf fortress implements?
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)
Stream Rick and Morty now on All4 🇬🇧: http://bit.ly/RMort
► SUBSCRIBE to Adult Swim UK: http://bit.ly/1ntNOb5
Find us, follow us, favourite us:
http://All4.com/adultswim
http://www.adultswim.co.uk
http://www.facebook.com/AdultSwimUK
https://twitter.com/adultswimuk
https://www.instagram.com/adultswimuk/
Adult Swim is your home for animation ...
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.
what does AOI mean?
area of interest
thx 🙂
good stuff
AHHH! Game ai pro released a fourth "online exclusive" book just last December!! And the FIRST article is about automated testing! Boo yah! I'm ahead of the curve!
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?
not a possibilty here because it needs too be prerenderd, because the scene has a lot fidelity
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?
i know people used cecil for such things, i just dont know whats the unity view on it. probably wont care
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?
yeah I know there is abuse potential but I need it for the render to work
but phew cecil, not much documentation about
Have you tried to use some parenting with null objects and rotating on local axis?
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)
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.
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
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.
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 ^_-
Thanks! I think I'm already doing some version of this already. Basically effects need to implement interfaces such as Playable, PlayableOnTarget, PlayableOnTargetForX, etc..
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!
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.
Scriptable objects seems like a perfect use case. In FF, they have magic spells like fire 1, fire 2, fire 3, and fire 4. All in a series seem perfect for being an asset with predefined damage ranges, hit %, and special FX. A single "fire spell" scriptable object could create the 4 assets required.
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
Yeah, so the contracts are based on what parameters they (the effects) need. So for example PlayableOnTargetForX will have a Play method that takes in both a target and an int value as parameters while Playable will have a Play method without any parameters.
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.
@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 🙂
What made me ask the question is the code smell you mentioned earlier and my inability to see the long terms downside/not knowing an alternative to it. So yeah, for the things I might have missed!
That was helpful btw, thanks!
Awesome, good! Good luck making your heckin' cool game! I'm thinking up some good vibes for you since making games is so dang hard. So much good luck!
Thanks a lot! It is pretty hard haha. I really hope I can finish this one. Can definitely let you know. Eitherways, thanks again, and likewise if you're working on one aswell! 🙂
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?
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?
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
Other than making script that will follow parent or follow by offset I have no idea.
I suppose you could track parent object scale, and lower child's scale by the same factor you enlarged parent. Like you enlarge parent with scale 10 then you should set child's scale to 0.1 of its original scale
Hope it helps
I mean you multiply parent scale with some number and then you divide child's scale with the same number
Ye from what i can see thats the only option. I just overcomplicated the process in my head and was looking for an easier way. Thanks for the help!
Shit happens man xD if you know someone who could help my problem it would be really nice xD
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
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?
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?
depends how performant your NN is
Liek how big and how much data it has to process
what's XR?
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
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
if you have a trained network specifically for gesture recognition of the type you will feed it, then it will be very fast to classify that gesture it sees.
But again, I'm not sure you really need ML for taht
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
what kind of gestures are we talking about?
the gestures involve both hand position and the hand pose itself, the curve isn't a bad idea
how complex are the motions?
some of them more complex than others, but overall, i'd say they're kinda complex
can you quantify "complex"
between switching hand poses quickly and also some big sweeping hand movements, at least
perhaps like, 6/10, where 1 is moving in a straight line and 10 is extremely nuanced and precise
Published at TVCG 2021
Website: https://exii-uw.github.io/OctoPocusIn...
Code: https://github.com/exii-uw/GestureRec...
Abstract:
Bau and Mackay’s OctoPocus dynamic guide helps novices learn, execute, and remember 2D surface gestures. We adapt OctoPocus to 3D mid-air gestures in Virtual Reality (VR) using an optimization-based recognizer, and ...
for example
this does involve a "start" trigger but I could see this being adapted to not need it
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"
those are probably easy to quantify with if/else
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
rather than using ML
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
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?
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
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
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".
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.
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
If youre intent on doing it with for loops, check out old ascii tutorials like this: https://stackoverflow.com/questions/33171682/printing-text-in-form-of-circle
if you google ascii print circle youre gonna find a hundred people talking about ways to do this
isn't there a formula for a circle where if the formula is true, then paint the pixel?
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?
it paints an 8x8 square
hmm actually.
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.
yea I have it save what center_x and center_y is
it's actually a paint area of 17 x 17
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.
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
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.
yep
thank you
holy cow it's done, that was way easier than I thought it would be thanks!
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?
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).
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)
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.
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
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.
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
i am unfamiliar with "blackboard" system , i will have to research it.
Yes, hard properties are easier.
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
am i inputing the wrong position data to the transform move?
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?
Is the scene itself marked as dirty after changes?
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hello everyone, this is my script. It seems to be fine but I get this error code can someone help me pls?
- Not an advanced code question
- see #854851968446365696 for the instructions for properly sharing code
- also see #854851968446365696 to configure your IDE
- It's Rad2Deg not rad2Deg
Thank you:)
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 ?
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)
SceneView.camera is the scene view camera
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
I think this makes sense to me. The interface spells out that it's an action listener for a specific type.
Pattern? It seems like you are using abstract interface techniques.
I think it's an improvement over the other way of calling it
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 🤷♂️
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
Enemy detect zone?
That's a tangent, [BC) is a tangent to A
@proven phoenix is that?
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
Uh
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
Wdym the other way?
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
@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)
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
okay nevermind that code is just fucked
Most likely a placeholder or leftover from testing
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.
The #archived-networking channel is the right place for this
👍
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+
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
no
instead of using MonoBehaviour, you can go with your own Behaviour which inherits from MonoBehaviour which will be inherited by your users.
{
void Awake()
{
DoSomething();
}
}```
```public abstract class BaseBehaviour : MonoBehaviour
{
public void DoSomething()
{
//
}
}```
looks very neat. gives me ability to cache variables too. thanks!
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
new input system probably missing from package manager
I'll give it a shot. Thanks!
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!!
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();
}
maybe because you lack extern "C" in the body.
its not always needed for header to declare it because thats used only for linkage
^ any ideas? I tried everything, All I want is be able to drag and drop into a field, and that should populate my array/list. but I dont want the children to shop up, and it would be a plus if the array size also does not show up. this already works in 2019, but its broken in 2020+
probably better ask in #↕️┃editor-extensions
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!
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
Are you sure that's how GetPixel works? From the docs it would seem that it retrieves the color of a single pixel
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
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?
think 'grid of cells with coordinates mapped to each cell', not 'cartesian plane'
GetPixel is just a pixel value. it cant be in decimal. maybe you're using a different map
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'
So in a texture the coordinates (1, 1) wouldn't be the same as if the texture would be applied to an object?
Alright, thanks
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
GetPixel() isn't reading texture space, it's reading in pixel space. There is nothing between 1 and 2
your 'image' is just a grid of pixels
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)
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?
If your image is guaranteed grayscale you could use any of the R G or B channels
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
That's the case. Thanks to all of you. Just what I needed :)
ah yeah, if you are building the image you can basically pack whatever info in there you want
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?
the documentation seems incorrect. you need to pass a preallocated Vector3[] without out keyword
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
You want a different algorithm for that, breadth-first search starting at S. You can use your distance heuristic in it
does BFS work when the graph has cycles? i've mostly used it in the context of trees
Yes. Keep a list of visited tiles
alrighty thanks, i'll look this up. i didn't even think about that
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
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
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
that brush should probably not have a collider but instead do a raycast(spherecast) against all colliders, from the result you can calculate the closest one.
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);
actually a basic spherecast should automatically return the closest one
Yea
it's a 2d game and they all have the same z
Oh 🤔