#archived-code-general
1 messages · Page 321 of 1
I would not rule out error logging in a production build. I would instead hide them in log files
Hiding error logging would make it very hard to tackle errors that only happen in production
Otherwise consider setting up configuration that allows you to specify a minimum and maximum severity with logging, which can be adjusted to easily test for errors by adjusting the configuration
my team lead said he didnt want any debug.log occurs or process during production stage as every debug logs will slow down the app
whether its logwarning or logerror
Modern loggers do not slow down the app at all
and our project is actually quite chaotic
you know during development mode you get a small windows that can display errors and exceptions right?
recently had to scuff my way into getting rid of a warning unity has with instantiation in onvalidate
Serilog for example writes its sinks asynchronously
So you can use that with no issues
previous team members gone lazy, they wanna check certain important messages quickly on that windows, so they delibrately make ~200 log , that is supposed to be a normal log, to become logerror
Also, usually error logging doesn't occur, so why optimize logging by removing any instances of that? 🤔
so 40% of logerror might not be an error at all lol
your team members need to learn to use the debugger
I would say that these log messages are removed instead then
That sounds very chaotic and bad
tracepoints > hundreds of debug.log calls
Did the developer never have their code reviewed?
That sounds like something that anybody would have rejected with a simple review
our codebase are 6yrs old , since ~2017
there are never rewrite and rebase of codes, NEVER i would say, we dont have time to do that
i can still see some deprecated or unused code thruout the codebase until today, thats 3-4 yrs old
we just keep adding things on top
i will clean out a very little part of it if i encountered them
ok you know what, i couldnt do much about the code now, we will push out the new production in next few weeks, but for debug logging i gonna fix errors and exceptions so they can go well on production mode as well
debug that confirmed to be ruled out of production mode:
-> Log
-> LogFormats and all of its variants
-> LogWarning
debug that will preserved during production mode:
-> LogError
-> LogExceptions```
Yeah that seems reasonable
I'm not 100% familiar with how much is allowed with consent but you can also send these errors/exceptions to a server if they happen to somebody
@worldly hull
like our game server? or database?
actually we dont store errors and exceptions on client app side tho
like we dont have a database or server to do that, if errors happened it will stay in users local storage i think
the logs
server side errors will have records , its more secure and tidy
I mean data from exceptions are send to a database on your end through an API or something
Makes it easy to handle things that might be thrown on the client and cause crashes
Hey everyone!
I'm trying to make a UnityEvent which I then add listeners to from another script (code: https://pastebin.com/MVmETYxq)
The problem is that I can confirm that the event is invoked and that the other script tries to add its listener but it seems like it's never added as it's never called
Thank in advance for any help!
Such a long name for logging things 😄
Seems weird to not just have it as static, and to write to some instance, but perhaps this is with a reason?
General thing you could consider is to create an instance of the logger for each class requiring logging, and to accept a generic type that accepts the class type. Then you can write the class name and namespace to logging to accurately determine where logging was called.
but u cant implement interface for it?
FYI this is also how .NET does logging, it has dependency injection and allows a ILogger<out class> class for logging
I have this for example:
internal sealed class ConcurrentServerDataProvider : IServerDataProvider, IDisposable
{
/// <inheritdoc cref="ILogger"/>
private readonly ILogger _logger;
public ConcurrentServerDataProvider(
ILogger<ConcurrentServerDataProvider> logger)
{
this._logger = logger;
}
Then all logs will be displayed under that specific class
looks cool
.NET also allows you to set severity per class if you have this
So if one class logs way more than what you want you can just turn it off for the whole namespace
So maybe this is useful in your case with all the excess logging
Adding listeners works if it's in the same class so it seems like it's something to do with it being between two classes but i'm not sure what it could be
Are you sure the instance that has event you subscribed to is same instance that calls the event?
Yes, im sure that the instance never changes
Maybe do a sanity check and print out the instance IDs. You could also make this a c# event since you hide it in inspector anyways
genuienly thought i was going insane when i saw them come back different but I figured it out, I was invoking the prefabs version of the event instead of the instance's version
(In)sanity check
Usually, I add the name of the GO to a lot of my debugs if not instance id. Might be useful for you in the future
Thanks for the tip!
Hello friends, I'm struggling, someone help me 
I have a Isometric Y as Z tilemap and want tiles to be highlighted on mouseover using a sprite which is already on the scene but will show and switch positions when hovering over tiles.
- Cell size of my isometric cell layout is
1, 0.5, 1 - The projects
Transparency Sort Modeis set toCustom Axiswith following values:0, 1, -0.26
What I have tried:
- Get mouse position by using
Input.mousePosition - Convert the mouse position to world position using
Camera.main.ScreenToWorld() - Convert the world position to cell position calling the grids
WorldToCell()method - Change the position of the highlight sprite to the cell position
But the position is off like half of the tiles width in px.
Once you have the cell position you can use
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.GetCellCenterWorld.html
I'm running home now, if this works, I will gift you 1 month Discord Nitro.
Hey guys so like I’m trying to code a game timer but for whatever reason when I paste the script into the camera on the timer text box I cannot select it
On my laptop I got a hardrive and all my downloads I download is going to my C drive but I want it to go to my hardrive does anyone know how to fix it so when I download something it goes to my hardrive instead of C drive
There's also https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html
Which of the two that's correct depends on how your highlight sprite is pivoted
And this is a Code or even Unity question, how?
But how do I fix
Idk where else to ask
Drag and drop, and make sure the type of the thing you're trying to drag is correct. Looks like your code wants Text which is the legacy Text component. You sure you don't want TMP_Text?
I just assumed people in here would know how to fix it
@zenith bear This has nothing to do with Unity. Put it in google
Honestly not sure I’m new to Unity, currently working on a college assignment and I’m just confused
I guess I could try that
Drag and drop won’t work thought, the box is refusing to accept the asset which is UI text
By default text elements are TextMeshPro these days so it would be TMP_Text
Unless you specifically used the Legacy Text component
How would I check that
look at the component you want to assign to it
Look at it
Alright hold on
is there a way to access the prefab preview image?
Yh it’s text mesh pro
Then you have your answer
So I got to convert it to legacy?
No you just change your code
Aha
In the way I explained above
i cant get that to work.
it tells me value is null
You know how vague this is?
Can't help you without more information
i was about to give some...
I already explained how you need to change your code
Then you can assign it in the inspector
But first you have to change the code
Also please stop sharing phone photos
private void CreatePreviewImage()
{
string path = AssetDatabase.GetAssetPath(this);
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/Level Previews " + typeof(Level).ToString() + ".asset");
Texture2D prefabPreview = AssetPreview.GetAssetPreview(this);
AssetDatabase.CreateAsset(prefabPreview, assetPathAndName);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}```
i try to get the object but the compiler says its null
Wdym by "the compiler says it's null"?
Compilers don't do such things
That's a runtime exception
Nothing to do with the compiler
Which line is line 50?
Of GenerateLevelPreview.cs
Seems unrelated to this code you shared
yes it was. its the wrong error. gimme a sec
Alright ah I see now replace text with TMP_text that makes sense thanks for the help.
Perfect it works now tysm!
whats the best way to get the name of an enum, Enum.GetName or tostring ? i think its getname but it has boxing
Wdym by "the name of an enum"?
Like the name of the value?
yep
ToString()
tyy
@leaden ice Friend, I tried it out.
Can't confirm that it works, since I don't see the tile highlight.
I'm sure this is due to the Z position?
Doing += 1 just for testing also didn't change anything.
I'm on my PC now, can also show code/screens if needed.
Enum.GetName is faster than ToString
But the difference is not worth mentioning
I use it just to be consistent, since I'm already using Enum.GetValues, etc.
@leaden ice Camera.main.nearClipPlane it is!
does anyone know how to enable intellisense in rider for unity packages? Fro example I want to be able to navigate between symbols in the Packages > ReadOnly > Modules > Shader
it's ignored, a part of unity package cache and analysis is OFF (on the right)
you should be able to turn that on in preferences > external tools
in unity or rider somewhere?
help
public AudioSource passosAudioSource; // Referência ao AudioSource para os passos
public AudioClip[] passosAudioClip; // Array de clips de áudio para passos
void Passos()
{
if (passosAudioClip.Length > 0 && passosAudioSource != null)
{
passosAudioSource.PlayOneShot(passosAudioClip[Random.Range(0, passosAudioClip.Length)]);
}
else
{
Debug.LogWarning("ReproduzirPassos: AudioSource ou AudioClip não foram atribuídos corretamente.");
}
}
You have an animator playing the animation with that event which does NOT have this code also attached to it
Maybe just a general comment, but I'd look out with the game you're making. You gotta have the permission of the game creator if you want to use their title, art, characters, ect ... If it has copyright (which prob is on a game that big)
im making for studes
alr, just saying so you won't have to pay a large fine if you'd ever decide to publish it.
☠️
thanks, I selected built-in and registry, now I can navigate!
Alr then do whatever you want with that attitude.
no bro, i understand
i wont post
i just want to use it as a way of learning
I completelly understand, but just don't react like that.
sorry bro
I have Particle System as a child object. I want particles to continue to exist after parent destruction. I trying to unparent particle system in the OnDestroy, but particle system "resets" when I do this, just starting playing from the start. I believe that's happening because parent object already marked as "ready for destroy" and this affects how particle system behaves.
How can I solve this?
I need it to be on a target, to follow it, to partly inherit parent velocity and all of that
just copy over the transform matrix every frame to the particle system object
at least i think that is how it works, because particles tend to live in their own little world after being instanced
once a particle is made, you can’t touch it
you can’t read, access, modify, or delete it individually
So there is no more optimal way to solve this issue without creating empty objects that follows everything I want particle system on, and managing this object, their destruction and all that?
you could make the particle system the parent of the object, but you still need to then make all changes to the parent, which is like a backwards hierarchy
or a parent objec that has as children the particle system obj, and the actual object. But this is just an organizational difference in the hierarchy, equivalent to what we discussed earlier
but point being: if your particle system component is on an object that gets destroyed/disabled, then that shit is gone
For the context: it's a burn effect on enemies that instantiated in the runtime and I want it to disappear smoothly
i understand the use case
it changes nothing, as that is normal
for reference, in SM64, particle sprites are like separate objects
like little dust clouds and shit are like separate entities
just so you have some context
either way, if you want something to exjst on the board, it needs to exist. and you can’t have something exist when it is also supposed to not exist from being destroyed
I can unparent particle system before destruction of the parent, seems perfectly fine to me for it to continue to exist without a parent now. The problem is in that strange behaviour when particle system "resets" and I have this jittery animation because of that
Can anyone help me figure out why my placing system doesnt work
Maybe.
Just post the !code and see if someone can
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public bool CheckTile(TileClass tile, int x, int y, bool isNaturallyPlaced)
{
if (x >= 0 && x <= worldSize && y >= 0 && y <= worldSize)
{
if (tile.inBackground)
{
if (GetTileFromWorld(x + 1, y) || GetTileFromWorld(x - 1, y) || GetTileFromWorld(x, y + 1) || GetTileFromWorld(x, y - 1))
{
if (!GetTileFromWorld(x, y))
{
RemoveLightSource(x, y);
PlaceTile(tile, x, y, isNaturallyPlaced);
return true;
}
else
{
if (!GetTileFromWorld(x, y).inBackground)
{
RemoveLightSource(x, y);
PlaceTile(tile, x, y, isNaturallyPlaced);
return true;
}
}
}
}
else
{
if (GetTileFromWorld(x + 1, y) || GetTileFromWorld(x - 1, y) || GetTileFromWorld(x, y + 1) || GetTileFromWorld(x, y - 1))
{
if (!GetTileFromWorld(x, y))
{
RemoveLightSource(x, y);
PlaceTile(tile, x, y, isNaturallyPlaced);
return true;
}
else
{
if (GetTileFromWorld(x, y).inBackground)
{
RemoveLightSource(x, y);
PlaceTile(tile, x, y, isNaturallyPlaced);
return true;
}
}
}
}
}
return false;
}
its says i get the nullreference at the if statement for tile.inbackground
Because tile is null I guess. Try to debug it and check what you pass to the function
Then GetTileFromWorld returned null for those coordinates
Also, I find some workaround. It works as expected when using OnDisable instead of OnDestroy. OnDisable is also called before destruction (and I think before marking object for destroy), so particle system doesn't resets before unparenting. Kinda works right now, but I don't want to face problems when I will need to use exactly "disable" in the future.
Anyway, seems like there should be a better solution that to create a bunch of empty GOs that follows every enemy just to smoothly stop the emission of particles.
Maybe I can somehow disable this behaviour of reseting animation during destruction process or something like that?
the other way would be to disable all the other entity components, and all children. instead of destroying it. then wait for some amount of time for particle system to be ready to destroy it
but then you made your game logic dependent on your graphics, which is a big nono
just make your particle system on a different object. you know the answer that works, and you just trying to tie a component to an object where you need the component to work even after the object is destroyed.
hey i am in need of some help. i am using wheel colliders to make a realistic car controller. i have made some scripts including a script for anti roll bar and downforce. i used AddForceAtPosition for this but it didnt really work. i was wondering why and tried everything and still no results. my plan was to do it a little bit later into the project and go to the tyre scripts first. when i was looking for some info i saw this guy talking about downforce https://forum.unity.com/threads/the-dark-art-of-unity-wheel-colliders-what-unity-doesnt-tell-you.1109261/ on the forums and wanted to implement this as well. thats when i remembered that i used AddForceAtPosition and have my scripts made in a way that is able to be used with multiple positions on the car. so for each wheel to have the correct downforce or ARB force applied i need to check how much force there is on the wheel. this is where i have no clue what to do and maby need some help for some ideas on how to solve this while not changing my scripts or only the AddForceAtPosition to a different function or something. https://gdl.space/homedajola.cs this are the 2 scripts i am talking about. any help would be fantastic.
I'm gonna try to setup destructible terrain using the Marching Squares algorithm and was wondering if the points property in PolygonCollider2D needs the array to be in order because i have no idea how to order those so they go from start to finish
Hey when I’m trying to download the lts 2022 2 errors comes up, the errors are android SDK & NDK Tools and OpenJDK how do I fix this?
and we are just supposed to magically intuit what those errors are?
this sounds like you mostly need a dynamic RB, and need to do a lot of tuning to apply forces to the object that feel correct
But to particle system object is a separate game object. It's just happens to be a child of an enemy some amount of time. Really don't see any like architectural or logical problem, am I missing something? The only problem is in the this kind of optimisation(or what it is) for ready-for-destroy objects.
Separate empty gameobject that just follows another object seems just like a self-made parenting to me, but I can be wrong
yes. in unity, child objects are destroyed/disabled if the parent is
you can use a PositionConstraint to make something follow another object
that is the fundamental core thing that you seem to not understand
As I said, I am unparenting child object before destruction
just start by not parenting them
I know what a child object is, man. The whole problem is in that I want to unparent child before destuction and it's work with literally everything except particle system because it is getting resetting for some reason
if you do not want their fates to be linked, don’t link them like that in the first place
Well that’s what it says?
transform.parent = null
don't actually need to detach with particle system. Just Stop() the main particle and coroutine a lingering time before cleaning up
the secondary emissions will continue but no more will produce
Yea, that's what i'm doing.
Something like this is happening right now, yes.
Problem is that particale system kinda "resets" and starts playing from the start after unparenting (parent = null). And seems it's not because of change of the parent, but because of mechanism that marks initial object for destruction. I'm doing this before enemy destroy basically
I used to do the detach method, but once you start pooling systems it just becomes an annoyance because you want the object intact when returning.
Pooling systems?
Object pooling, like bullets and explosions
Hm.. So what would be the problem with bullets/explosion? I can detach particle system of a bullet before bullet destroy and its trail or something else would be there, right? Or what you mean by "returning"?
The idea of pooling is you don't destroy. You cache a set amount of objects and reuse them.
So ideally when you reuse them, they should be in a state such that if you were to instantiate them instead.
and so you don't run into hiccups when doing stuff like this
https://cdn.discordapp.com/attachments/448923113921576992/1239337917520937012/Unity_LuZSmrLUEF.webm
(VFX Graph is better though but cant use it with webgl)
what do you mean by this? i dont get what you mean by dynamic rigidbody.
dynamic rigidbodies are affected by forces
and if you find this to be new information, then you are definitely not ready to implement all the forces you would need to make a car drive smoothly as a dynamic rigidbody
can t use "Using Cinemachine" at the top of the script someone have an idea?
not enough info
i get this error : "The type or namespace name 'Cinemachine' could not be found"\
- is the package installed?
- are you using assembly definitions
- is error in code editor or Unity as well
the error dosen t show in the script itself just in the unity console. So is something with the unity version?
If I have a property that equals an instantiated scriptable object. Later on I instantiate a new scriptable object and set it to that same property. What happens to the original scriptable object that no longer has a reference?
- Does it just float around until garbage collection occurs?
- Is it recommended that I destroy that instance of the scriptable object after I no longer use it?
is your IDE even configured ?
normall its the other way around
i mean the text isn t hilighted with red
yes i have it configured
which ide are you using?
visual studio code
if its a scriptable object it lives in your assets folder
so does it normally highlight red other issues?
anwyay if its also showing error in unity you seem to be missing the package or you have assembly definitions somewhere
yes it dose and it autocomplete things
alr. can you show the package manager for cinemachine
so the folder ?
hmm alr.
you don't use assembly definitions ?
oh fuck
nvm
they changed the namespace ffs
using Unity.Cinemachine;
If I instantiate it though, that becomes a separate version of the scriptable object.
Thanks very much
still didn't use it so it threw me off 😛
after I saw you had 3.1 though it sparked a thought to double check
yea
So the instantiated version just goes back into the assets folder along with the original scritpable object?
is it not in the assets folder? its been a while since I did runtime SOs
so like I kinda can't figure out how to make a player movement and mouse movement script
No, created instances are not automatically. You have to use editorutils to save it as a asset. So i would assume it has to be gc'd. Can't tell for sure tho.
oh so they are just in memory ?
oh right I remember you have to do
AssetDatabase.CreateAsset(theData, path);
AssetDatabase.SaveAssets();```
I found a post about this issue, I wasn't sure what to search for until we started talking, but basically any unreferenced objects will eventually be destroyed by the garbage collector.
https://www.reddit.com/r/Unity3D/comments/d070vl/how_do_i_make_sure_an_instantiate_class_has_been/
i searched for this and i can only find dynamic rb's for the 2d rb. i am using a normal rigidbody and i cant find anything on a dynamic setting there. i dont know much about the 2d rb but since the wheel colliders ignore almost all forces i dont know if this would even work. i can be wrong but it sounds really odd to me that the wheel colliders would react differently to another rigidbody. i also tested with increasing the values in the meantime but it only gets more buggy if i do so
rigidbodies for 3D have different modes, for both kinematic and dynamic
i can very confidently recomend you not touch this problem until you learn more
I guess so, couldn't imagine unity would do any hidden asset creation here 🙂
That's the way i had in mind too to save them.
yeah forgot it was an exclusive method to save, and CreateInstance didn't actually save it
i have barely used runtime SO creation
can i ask you why? its a school project and downforce in this project is a relative big part of it so i dont know if i would even have a choice.
Me neither, everytime i start thinking about it, it feels like it would be more appropriate to use a poco or simply some stats on the mb. But i'm not very experienced at designing systems, maybe i'm completly wrong 🙂
yeah I mean classic 
One thing I don't use them for is for mutable data
prefer poco for that
because you have a lot of learning to do to figure out how to manage forces, to make a big complex object like a car that requires many forces from different angles and spots, all applying torque with tuned parameters to give a decent ride
like, you should be learning kinematic rigidbodies first, which are rigidbodies that go exactly where you tell them to go
oh do you mean the isKinematic checkbox on the collider?
ohhhhh k
now i get what you mean
i didnt know that isKinematic off meant that it was a dynamic rb
but in that case i have used dynamic rb plenty of times before
i saw a neat video about the basics of car physics recently
but i dont know how you think tuning forces on the rb if the wheelcolliders ingore those forces is going to work then
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
it does not use unity physics at all
(at least, not for calculating how the car behaves)
^^vid i based a controller on, very good explanation
there are different ways, but you need to learn more before you start coding anything
i’m surprised your professor taught you jack shit about this, and just threw you to the wolves
“go make a car”
nah that isnt really how my school works tho. we have 10 weeks to make a game in groups of 3-5 people and we chose a race game
also isnt my first days with rigidbody's. so i think i can make it work
this looks really interesting tho
it only looks like a shit load of work to make it work realisticly
i dont think you should follow a youtube tutorial for the base of your school project lol
unless the professor doesnt care
I'm debating between two different approaches to an Item system for a survival game I'm working on.
There are many different types of items, and a good amount of them have unique functions which will need to be hardcoded. I am wondering if I should have
Unique Class for every item type
- Can hardcode the unique function into the class, very readable, but bloated
- Will result in a lot of class files which are just the default file, repeating a lot of boilerplate
LogItem, AxeItem, WoodItem, etc...
Or
Have generic Item class differentiated by an Enum
- For what I am planning, I can handle the unique functions of items outside of the item itself, with a manager script.
- Probably less readable.
- Will rely on Unity prefabs
- A little less safe because of the mutability of Item class instances.
Itemand possibly inherited classesTool, Consumable, etc
Anybody have similar experience they can share to help me decide? Thanks!
the last time i saw our teachers care about anything is when the coffee macine broke so im not to worried about that. i only see a lot in that video what could cause issues when wanting to make it realistic. so i dont really know if i even want to go for that approach. on the other hand the wheel colliders have been irritating me so much right now that it does look really tempting.
An abstract item class with derived classes implementing the extra functions should be fine. If you need to plug these in inspector, then an enum can be fine but a scriptable object might be better.
Just to clarify, ScriptableObject in place of what?
I've tried to learn about them like 4 times and I always get confused 😅
This would be purely for assigning items in inspector, since you cant just write "AxeItem" in inspector and get the correct class. If you have like a
[SerializeField] Item myItem;
You cannot just plug in the AxeItem script, you need an instance of it
It's the same use case as the enum. An enum would just give you a way to serialize it in inspector. You have your item enum exposed in inspector, then look up the actual class you want to create an instance of
I see. Thank you for the insight!
One thing I will say though, is the scriptable object route is also somewhat a pain. Right now I'm somewhat doing what I suggested, although my items can affect stats and can have unique functionality. Affecting stats is easy, but this gives me actual reason to use scriptable objects because I can assign those numbers in inspector. I can reuse an items functionality with different stats.
In your case, if you're really just creating 1 instance of an SO then it might become a pain. You'll end up creating 2 scripts per item, 1 for SO and 1 for the item, plus the actual instance of the SO.
Small rant done
Yeah I totally understand, I did take this approach in the past (although pretty rudimentarily) and I had a similar issue where I needed a lot of file system overhead to make my items work. They were very efficient at runtime because of it, but very inefficient in terms of development time.
I got weird problem, I made assembly definition for unit testing. But I came to the conclusion delete all of these stuff including assembly definition and unit test codes. After that all is deleted, I still got error: TypeLoadException: Could not load type '.CharacterStatsManager' from assembly 'AssembleDefinitionTesting'. How I could fix this? That CharacterStatsManager is also deleted, its old code...
perhaps restart unity
What is the difference between IJobFor and IJobParallelFor? The documentation makes them sound the same, but with slightly different methods?
hey I made a game that uses a python script to capture webcam feed and then pass it to unity
is there a way to build the script with the game?
or should I build the unity game and then compile the script to exe
and just make the python exe call the unity game exe
The latter imo, not everyone has the python runtime installed on their computer
why not just use unity's https://docs.unity3d.com/ScriptReference/WebCamTexture.html ?
because it's not actually passing the webcam feed, it's running MediaPipe body recognition and passing the AI's output to unity
ah, I see
bump
IJobs don't have to be run in parallel. You could schedule them to be run sequentially, i guess that's the main difference.
IJobsFor, you mean?
Yes, sry my fault 🙂
And what does it means to run in the main thread?
Like, it won't create a new worker thread?
Yes it will run aside the most of the usual code which is running on main thread.
Oh i realise you could have meant something different here. Just to be clear: Did you want to know what it means in general if something is not run on the main thread, or if the IJobFor will run on main thread?
So, the IJobFor has a method called Run() that, according to the documentation, allow the job to "run on the main thread".
I'd like to know what that means
Yes, calling run will put it on the main thread. But this is usually used for testing purposes. One of the reasons to use jobs is to have code not run on the main thread but instead in those worker threads, to make use of more cpu cores. But threading, which the job system encapsulates is something else than tasks.
Aaaah ok, thanks
I was confused because "why use job if not to multithread"
That clarifies it
When you call Schedule() instead, those jobs will usually land on seperate worker threads, but might end up on the main thread too. For this reason unity also recommends to have those jobs finish in under 1 frame.
bear in mind, WebGL cannot multi thread
Oh, I see
I have problem about walking sound effects. If I dont leave key, sound doesnt play i used both input.getkey and getkeydown commands
If you dont leave key it doesnt play
I didnt have this problem for mouse click, it directly plays
footstep is reference for class right one
You can use just audioSource.PlayOneShot(footstepSound); to simplify down that big block of code in void Step().
In void Update(), walking will always be false because you re-declare it each frame. Visual Studio signals that walking = true; is unnecessary because the variable isn't read afterwards.
i had echo problem with that
tried first
You need to add a delay between plays, because here you're playing a footstep sound once per frame
so Im starting to have a lot of different object pools in my scene (enemy, projectile, damage numbers, etc) and each have their own gameobject singleton. Is there a better way to handle all these pools?
Probably the factory pattern
well im not creating the pools at runtime
EnemyManager.Instance.GetEnemyFromPool()
ProjectileManager.Instance.GetProjectileFromPool()
DamageNumbersManager.Instance.GetNumbersFromPool()
or my prefered way:
GameManager.Instance.EnemyManager.GetEnemyFromPool()
GameManager.Instance.ProjectileManager.GetProjectileFromPool()
GameManager.Instance.DamageNumbersManager.GetNumbersFromPool()
i make script that ping servers using GET, but it take me more less 50 seconds for it to complete:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Pinger1 : MonoBehaviour
{
bool[] online = new bool[50];
void Start()
{
StartCoroutine(PingAll());
}
public IEnumerator PingServer(int index)
{
using (UnityWebRequest uwr = UnityWebRequest.Get($"http://sub{index}.domain.net:8000"))
{
uwr.timeout = 1;
yield return uwr.SendWebRequest();
switch(uwr.result)
{
case UnityWebRequest.Result.ConnectionError:
online[index] = false;
Debug.Log($"error: {uwr.error}");
break;
case UnityWebRequest.Result.DataProcessingError:
online[index] = false;
Debug.Log($"error: {uwr.error}");
break;
case UnityWebRequest.Result.ProtocolError:
online[index] = false;
Debug.Log($"error: {uwr.error}");
break;
case UnityWebRequest.Result.Success:
online[index] = true;
Debug.Log($"success: {uwr.downloadHandler.text}");
break;
}
}
}
public IEnumerator PingAll()
{
string list = "";
for(int a = 0; a < online.Length; a++)
{
Coroutine c = StartCoroutine(PingServer(a));
yield return c;
list = list + $"{a}: {online[a]}; ";
}
Debug.Log($"Ping complete: {list}");
}
}
And result is:
Ping complete: 0: False; 1: True; 2: False; 3: False; 4: False; 5: False; 6: False; 7: False; 8: False; 9: False; 10: False; 11: False; 12: False; 13: False; 14: False; 15: False; 16: False; 17: False; 18: False; 19: False; 20: False; 21: False; 22: False; 23: False; 24: False; 25: False; 26: False; 27: False; 28: False; 29: False; 30: False; 31: False; 32: False; 33: False; 34: False; 35: False; 36: False; 37: False; 38: False; 39: False; 40: False; 41: False; 42: False; 43: False; 44: False; 45: False; 46: False; 47: False; 48: False; 49: False;
Which is correct. How can I make it faster while ensure I get this list correctly?
you could/should run the requests in parallel instead of in sequence
thank
This might work???
string list = "";
List<Coroutine> coroutines = new();
for(int a = 0; a < online.Length; a++)
{
Coroutine c = StartCoroutine(PingServer(a));
coroutines.Add(c);
list = list + $"{a}: {online[a]}; ";
}
foreach (Coroutine c in coroutines) yield return c;
Debug.Log($"Ping complete: {list}");```
i will take look i appreciate suggestion
Anyone know why this code isn't triggering? I have this in the update method. trying to learn the new input system.
if (playerInputActions.Player.Interaction.WasPressedThisFrame())
{
Debug.Log("Inside of the interaction if statement");
interactable.Interact();
}
Im pressing F and nothing happens
Was playerInputActions.Player.Interaction pressed this frame?
Did you ever Enable() the asset instance or the action?
omg if it was this i swear to god
ill get back to you
that was it 🤦♂️
thank you @leaden ice
also is this the correct way of checking for key pressed?
i saw another value which was
playerInputActions.Player.Interaction.triggered;
and I wasn't sure if that was the correct way
yes
I mean there are many correct ways
not just one
triggered would also be correct here
triggered is equivalent to WasPerformedThisFrame() and there are subtle differences between that and what you have, but with the way your action is set up, they are identical
thats exactly what im doing. im just saying my scene is getting cluttered with xPool, yPool etc
was wondering if there was a better way than using singletons
GameManager is my only singleton
well, either way you can just child the singletons under GameManager
collapse when you need a manager
Well, take a look at my example again. It's one singleton
that's all you need if you design it as such
sweet thank you for your help!
so you just have all your object pool scripts on your gamemanager gameobject which some GameManager script holds references to?
pretty much. It's the manager of managers
(but who manages the manager of managers?!)
It's either bind the gamemanager reference to all your scripts, or just use the static accessor
I choose to be lazy
same thing in the end really
does unity give a script u name GameManager a custom image lol
do you have all your other managers/pools just normal monobehaviours?
if I want to insert stuff into them from the editor, yes
if you're pooling monos, then it's probably going to be on the scene anyway
yeah since it needs to instantiate
is there anyway to subscribe to SceneManager.sceneLoaded without having your function return some UnityAction<Scene, LoadSceneMode>
it shouldn't return that
it should be that
that's a delegate type
That means it needs to take a Scene and a LoadSceneMode as paramters
void MyMethod(Scene s, LoadSceneMode mode) {
// blah
}
void Subscribe() {
SceneManager.sceneLoaded += MyMethod;
}```
ah i see
I guess you were trying to do this??
UnityAction<Scene, LoadSceneMode> MyMethod() {
// some stuff
return null;
}
void Subscribe() {
SceneManager.sceneLoaded += MyMethod();
}```
That's not quite correct
yeah, its fine with the first example
That will just do the "some stuff" once as you subscribe and do nothing else
is sceneLoaded called after start?
you mean after Start for... the objects in the new scene?
yeah
Almost certain it's not
hm, im trying to have some persistant singleton find the player when the scene changes
will that not work then?
why not just have the player register itself with this singleton in Start?
// In the player script
void Start() {
MySingleton.Instance.RegisterPlayer(this);
}```
good point
@leaden ice so i ran script and it was still taking 50 sec. what i did was i modify your suggestion and use yield return new WaitUntil(() => responded >= 50); then print the list. In PingServer() at each case I made responded increment by 1 in order to work
should I use a persistant singleton that moves between each scene or just copy a singleton in each scene for my game manager?
i sure http is 100% chance either result in error or success
but if not then what idid might not be good
Using LineRender to draw the meshes edges, why do they look like that from a far away but better closer?
pretty sure it's a typical aliasing artifact
This isn't a code question, but that's aliasing for you. If you use anti-aliasing of some kind it will improve
Also some Moiré happening https://en.wikipedia.org/wiki/Moiré_pattern
thanks!
how inefficient is to do that kind of thing (e.g wireframe effect with LineRenderer) within a script compared to a shader?
like, actual games will probably never do something like that?
Very inefficient
to use vfx graph, do I have to instantiate an empty game object with the effect? (ie object pool it) or is there a more efficient way
You need a GameObject with the VisualEffect component attached.
so go the object pool route?
I don't see how an object pool is relevant
unless you need lots of reusable elements of the effect
for something like a death effect
the enemy can't play the effect since it will be destroyed no?
Much like the old ParticleSystem and Emit(), you can also use a single VisualEffect for the whole scene and use events to spawn particles
im not familiar with either the old ParticleSystem or Emit
so a single gameobject with VisualEffect on it can create effects throughout the whole scene?
even at the same time
yep
For example on the right side of this screenshot there's a custom event which causes some particles to spawn
im confused, the visualeffect mobo asks for a asset template which seems like a specific vfx
no, so I need a different gameobject for each effect
They all have the same death effect?
yeah its just some blood explosion
then you only need one for the whole scene
if it's a different effect yes
okay makes sense
from the enemy script, how do I get it to play the effect at the location?
It's kinda hard to explain if you're not experienced with VFX Graph yet... lemme see if I can find a tutorial
But basically you would add the spawn position of the effect as an event parameter https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@16.0/manual/ComponentAPI.html#event-attributes
and read that in the graph
basically the C# code would look like:
https://docs.unity3d.com/ScriptReference/VFX.VisualEffect.SendEvent.html
with an attribute for the position:
https://docs.unity3d.com/ScriptReference/VFX.VFXEventAttribute.html
https://docs.unity3d.com/ScriptReference/VFX.VFXEventAttribute.SetVector3.html
vfx graph is bestest
im still confused, it seems like you do need to object pool still?
particle systems no, but gameobjects yes
what do you mean?
there's a few ways you can do it
if it was something like a shoot fx, it could just be childed to the player or what not
SingleSystem vs multiple systems like particle system way
but since its a death effect, the enemy will be destroyed along with the vfx
you use a single VisualEffect and just call SendEvent to spawn a "burst" of particles
the VisualEffect wouldn't be a part of the enemy object
what do I pass into SendEvent though?
I explained here
You pass the name of the event (you would make an event like "SpawnBloodExplosion") and the position you want to pass in (the position where the enemy died)
this event?
it's good for predicted vfx but if it's constantly updating cpu side via physics there's some extra work you need to do
nah its just a flipbook death effect
https://qriva.github.io/posts/how-to-vfx-graph/
More on send event and other methods like graphic buffers
graphic buffers is useful for moving projectile gameobjects that can't be predicted in the gpu
attritube.SetVector2("Position", transform.position);
GameManager.Instance.DeathFX.SendEvent("SpawnDeathEffect", attritube);```
like this?
looks like it
yep something like that!
not working, hm
well did you set up the graph itself properly?
You need to set the event up like this in the graph and hook it to a spawn system ("MyAwesomeEvent" example)
that's too blurry to read
even when I "open in browser"
better but you should use a "Single Burst" spawn system
that's doing 1 particle per second
now its not even playing
Before trying your code
play with the "Send" button in the graph on the event
to make sure it works there
What position are you spawning the particles at right now?
just at the enemy position
but i didn't realize once you made a custom event the Play button wouldnt work
it still plays but there are some artifacts it seems
not sure why
well how are you getting that?
right now just try to get it to spawn at 0,0,0 when the event happens
this code is on the enemy
you might be experiencing an issue with the bounds
sure but
in the grapoh
how are you getting the position
so you're probably not at all
yeah
ah yeah, its all being played at 0,0,0
Is that working then at least?
Ok so now you just need to use this I think?
https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@16.0/manual/Operator-GetCustomAttribute.html
I think you might need to... define the custom attribute in the graph somewhere?
It's a little fuzzy to me
but this would be your custom position attribute
Oh maybe this is relevant: https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@16.0/manual/Events.html#event-attribute-payloads
Event Attribute Payloads are attributes that implicitly travel through the graph from Events, through Spawn Contexts, and eventually to an Initialize Context. To catch a payload in an Initialize Context, use Get Source Attribute Operators or Inherit [Attribute] Blocks.
I have a scriptableobject that doesnt seem to be saving whenever I restart my unity. It seems to save all the values in and out of play mode just fine, however all the values are reset after closing the client...The values are just Vector3 and Quaternion
show the code for it?
Are the values serialized?
How can I make a currency system in 3d?
int money;
Yes
Without further details, that is a "currency system"
{
_dataSO.Save(_gunTransform.localPosition, _rightHandTarget.localPosition, _rightHandTarget.localRotation, _leftHandTarget.localPosition, _leftHandTarget.localRotation, _rightElbowTarget.localPosition, _leftElbowTarget.localPosition);
}```
``` public void Save(Vector3 gunPos, Vector3 rightHandPos, Quaternion rightHandRot, Vector3 leftHandPos, Quaternion leftHandRot, Vector3 rightElbowPos, Vector3 leftElbowPos)
{
Debug.Log("DATA SAVED");
GunLocalPosition = gunPos;
RightHandPos = rightHandPos;
RightHandRot = rightHandRot;
LeftHandPos = leftHandPos;
LeftHandRot = leftHandRot;
RightElbowPos = rightElbowPos;
LeftElbowPos = leftElbowPos;
}```
public class WeaponIKDataSO : ScriptableObject
{
[HideInInspector] public Vector3 GunLocalPosition;
[HideInInspector] public Vector3 RightHandPos;
[HideInInspector] public Quaternion RightHandRot;
[HideInInspector] public Vector3 LeftHandPos;
[HideInInspector] public Quaternion LeftHandRot;
[HideInInspector] public Vector3 LeftElbowPos;
[HideInInspector] public Vector3 RightElbowPos;```
Do you have a tutorial with more details
when you say "closing the client", you mean the Unity editor?
is "overwrite" and "source" correct? still spawning at 0 0
Right, whenever I close my unity editor and restart it. The scriptable objects data is set back to default
That's probably the built in position attribute?
overwrite add multiply blend, then source/slot
"use Get Source Attribute Operators or Inherit [Attribute] Blocks."
in that doc
What if you use https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html on the SO
hmm so target the SciptableObject and SetDirty.
{
_dataSO.Save(_gunTransform.localPosition, _rightHandTarget.localPosition, _rightHandTarget.localRotation, _leftHandTarget.localPosition, _leftHandTarget.localRotation, _rightElbowTarget.localPosition, _leftElbowTarget.localPosition);
EditorUtility.SetDirty(_dataSO);
}```
This is, I assume, for some kind of editor tooling?
I mean, they would just be sending your the first link from googling "unity currency system"
You can search that yourself.
If you give ANY amount of details for what you want, we could suggest something more helpful. But so far you have said nothing, and praetor gave the best answer so far
Right, I have it saved By this code
{
Save();
}```
That did it, setdirty() works
I'll use this whenever I want to save scriptabledata at runtime now thanks!
Yep - note of course this only works in the editor
BTW if you want to make this action undoable, you can use:
https://docs.unity3d.com/ScriptReference/Undo.RecordObject.html instead of SetDirty
noted thanks
Do you have Sprite Mode set to Single or Multiple?
Also this is not a code question at all
Hi, with debug.log, could i pass a specific variable on an object as the context, to highlight the specific variable in the editor to show which one has the error? how would i do this?
You can pass a object as the second param, but AFAIK you cant really highlight a variable, you can use nameof on your variable though, for example: Debug.Log($"value of {nameof(someVar)} is: {someVar}", this);, if that was on a Mono script on some object, that object would get highlighted ("this", referring to the script attached to the object) with the name of "someVar" and its value, if that is what you might be referring to
i more wanted highlight the variable itself, ik you can do this, but i wanted to highlight the variable since i have a very big array and thought it'd be alot easier if i can just click on the error and it scrolls the array to the right value easier, but if that's not possible i'll just have to scroll there manually ig
Whats a better way to handle attacks against enemies, more specifically preventing an enemy to get hit by the same attack twice?
- ImmunityFrame: When an enemy is hit I set a bool "InIFrame" to true and start a Coroutine to set it to false after a short time. While this bool is true the enemy cant be hit. A problem here is if I want to add faster weapons that potentially with alot of upgrades could end up with an attackspeed that is faster than the Immunity time, which would get very frustrating. My game is also multiplayer so the IFrames would be only local for each client so you dont prevent other players from hitting an enemy.
- Random ID for each individual attack: Each attack gets a random ID with something like Random.Range(int.MinValue, int.MaxValue). If an enemy has already been hit by an attack with this id it wont register. I dont know how likely it would be here to randomly generate the same value on 2 different attacks? Maybe do something with not a random value but time since the game started/ current time?
I guess both are okay? Am I missing something? Which is a better idea or does it just down to the individual needs?
question why are you making an enemy invincible after it is hit
Well if i swing my sword I dont want it to hit the enemy every frame that theyre colliding
Just once
And some enemies consist of multiple colliders that would all trigger OnTriggerEnter
Or is there something I am missing?
Isnt an IFrame/ ImmunityTime pretty standard?
and if it is crucial to your game that you retain that function i would say set a maxInv float that represents the max amount of time an enemy can be invincible and then when you hit an enemy you set a bool isHit = true which stops it from being hit again and then you can start incrementing a currentInv float to track how long its been since going inv then when it hits max you can reset the bool isHit to false and reset the currentInv float to 0 or the max if you want to decrement it instead
this will allow for a looping logic
you should have sword collisions in an Ontrigger or OnCollsion method imo
they only get called once per collison and you can specify enter , exit , stay
Yeah but for each collider on the enemy right?
oh your enemy has multiple colliders?
What ive been told is to do OverlapBox or BoxCast
in that case make a collider manager and have themall contribute to the isHit
Some do, theyre 2d but some have weird chapes
Thats also a good idea I didnt think about
happy coding!
I also could use a PoligonCollider instead of several Basic ones I guess?
But idk how much worse that is for performance
you can really use whatever you want , and if your game is 2D dont worry about performance imo
majority of the phones could run anything we could make in 2d imo
yeah i guess
you arnt limited to just 2D objects in a scene if you havent figured that out yet
same here rarely use it
I am making a 2D Platform Fighter and I'm trying to track weather or not my player is grounded by using Physics2D.BoxCast(). This works pretty well, however the BoxCast seems to not perfectly synchronize with the players movement. By rapidly flipping the Contollstick left and right and spamming jump near a wall, you can wall jump, which is not supposed to happen. When running into a wall there seems to be a few frames, where the box will clip inside the wall. Here are 2 videos to demonstrate this. The green lines were made with Debug.DrawRay() and are supposed to represent the box. Here is the code for my Movement, Jump and IsGrounded: https://gdl.space/govizotari.cs. Help would be greately appriciated :)
The last time I had to solve this problem, the issue was as follows: An attack had a certain duration and hit all enemies coming into contact with my sword. To detect colliders, we used Physics.overlapSphere() within a coroutine. All hit enemies were added to a list. Before hitting an enemy, we checked that it hadn't already been hit (by checking the list). At the end of the attack, the list, contained within the coroutine, was destroyed.
I don't think this is the most performance-optimized way, but for usability and bugs, this system was perfect.
if you are using 2D why not just tell the game its grounded if its simply colliding with something
Oops, I answered the wrong message xD
(Sorry)
wouldn't that also allow wall jumps? Or is there a way to track if the bottom of the Collider collides with the ground?
I know you can have music playing through scenes with donotdestroyonload but how would you be able to it when playing through a set of scenes but not all of them?
see what i would have done is made each enemy detect its own collisions with the sword and kept track of it had been hit already , and 2D raycast checks are great when they work but i still prefer box colliders and such
haha i just solved this for myself if u wanna know
I actually do pretty much the same to prevent hitting an enemy twice when they have 2 or more colliders
I will rethink my approach to see what works best)
just add a collider for bottom and one for whatever else
Here you can use my audio manager should help
Youll obv have to repurpose some stuff
I think it's better to handle collision of an attack within the attack script. Otherwise, there could be unintended invincibility if two different attacks hit an enemy simultaneously. The first attack might make the enemy invincible for the second one. Unless that's the intended behavior?
if you want it to solve the case of being immune to a specific attack for a short time yet not immune to anything else, then yea you'll need some form of ID associated with it. Either that, or actually check within a specific attack to make sure its not damaging the same enemy multiple times, by maybe storing which ones its already damaged.
please, !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also even if raycast are tricky some time, I think physic.OverlapBox/OverlapSphere is a better solutions than using colliders (from my POV)
i was going to format the thing as cs using the 3 backticks and cpp but it was to long
discord recommended uploading as file
Forsure i do like me some raycast
Yeah thats what I have been told. I have some problems with collision consistency so I will try these next and see how it works
its just a pain sometimes
which is why we prefer that you use a paste site
can someone help me with my TMP_Dropdown issue now ? 😂
I do not work on 2D with unity, but for 3D, I stopped to use raycast to prefere sphereCast in some case
what issue?
the item images only show briefly when opening the dropdown or closing it
i posted video in #📲┃ui-ux
oh if that command will let me paste it ill do that from now on
Would I put this collider on the player as well? Because if so, how do I check that the collision only happend with the ground collider and not the entire body?
It is not related to colors about state event ? (On mouse hover)
(Not sure)
i would put one as a non trigger on the player itself and then attach some smaller trigger ones
yeah im not even sure how the dropdowns work to be honest first time using them
If the ground collider is the only non-Trigger, wouldnt it still collide with walls and allow wall jumps
correct but if the ground trigger is unable to collide with walls becuase it is underneath/inside the player then it will never be able to collide with the walls
Hi, im really stumped on this, i want to be able to detect when an object is visible by a specific camera ('PovCam'), ive tried multiple solutions and nothing works, this is the current code
raycasts id think
ive tried this as well
im using a linecast rn, which i think is a raycast between 2 points
This part of the script fade the colors related on mouse events.
I guess you made a script that change the colors of the elements in the list.
Then the dropDown script do his job and fade your elements to white because your mouse is on it.
(That's my guess)
i like your assumption!
seems highly likely they are conflicting
well actually no there isnt a script modifying each item
the script is only changing the preview color box and the background color
You can check your ground by using physics cast (ray, or sphere)
And you can sort your colliders by using layers 🙂
is there a cone collider?
nope =/
lame 😦
using BoxCast rn but that lead to the issue I mentioned above
this issue
ohhhh
Unusual requirement - I need to write out SVG files - anyone used an API to help do that with Unity?!
Use a mesh collider and assign a cone shaped mesh to that collider
mmm that would be hard arnt SVG's vector graphics
SVGs are an XML description of vector graphics - actually fairly simple
are you trying to convert existing pngs or something into svg or text data into svg
the problem is that it always returns false, no matter if the object is blocked from view or not
better formatting
What does this pos represent
What returns false? SetActive?
vectors into new SVGs - writing out text is easy but there are APIs that are focused on SVG XML output, only they tend to have a lot of .NET library reliense and be draw-focused for WPF also
Or the if-else?
pos of the object the script is assigned to
If/else statement
Perhaps you can use Visual debugging to see where the linecast points to
you seem to understand really well what an SVG is, have you attempted to create a script that takes in the text and tries to format it correctly before exporting it somewhere as SVG?
doing that rn
I have used Unity's vector package that reads in SVGs but I need to simplify them and output new. I will have to delve into the format, maybe it is simple enough to just write out some XML for my needs. I should use artist tools but I wanted to automate...
yeah if you want to automate id say try to figure out what makes up an SVG and then you just need to make a script to take in your text data and parse/format it into a SVG
Sorry I still don't quite understand the suggestion. You're saying I should have two BoxCollider2Ds on my Player. One of them is not a trigger and when colliding with Ground sets isGrounded = true and the second one is a trigger and larger. And then the first one is supposed to be inside the second one?
slapped it on so I see 2 options, doesn't seem to be working when testing
Hello can someone help me modify BlurValue so that calculatedSize matches expected Size?
using UnityEngine;
[ExecuteAlways]
public class calculator : MonoBehaviour
{
public float size;
public float expectedSize;
public float calculatedSize;
public float difference;
// Update is called once per frame
void Update()
{
int EffectSize = Mathf.Max(1, Mathf.FloorToInt(size));
float ExtraSize = Mathf.Clamp01(size-EffectSize);
calculatedSize = BlurValue(EffectSize, ExtraSize);
float total = EffectSize+ExtraSize;
expectedSize = (total*2+1) *(total*2+1);
}
public static float BlurValue(int EffectSize, float ExtraStrength){
float average = 0;
for(int z = -EffectSize; z <= EffectSize; z++){
for(int w = -EffectSize; w <= EffectSize; w++){
average += 1;
if((w == -EffectSize || w == EffectSize) && (z == -EffectSize || z == EffectSize)){
average += ExtraStrength*ExtraStrength;
}
else
if(w == -EffectSize || w == EffectSize){
average += ExtraStrength;
}else
if(z == -EffectSize || z == EffectSize){
average += ExtraStrength;
}
}
}
return average;
}
}```
I don't know what am i missing or doing wrong. Basically it's calculating the area in a discrete way (to make sure for othe processes so it's normalized)
I just learned about MonoBehaviour.InvokeRepeating for the first time. It seems very nice but I have never seen anyone use it over Update(). One thing i could imaging this being good for is for example on each enemy to check for the closest player every second instead of every frame. Is this a good idea? Can I use this instead of Update() on everything that I need regularly, but not every frame, or is there an argument/ reason against it?
It's an old method from before coroutines existed. Coroutines are better in every regard
It becomes unmanageable when you start having multiple "thread" in parrallel.
Some things to consider
https://www.codinblack.com/how-to-run-a-method-at-certain-time-intervals-in-unity/
Invoke and InvokeRepeating do not stop after the game object is deactivated.
How would I achieve the same with Coroutines?
private void Start(){
StartCoroutine(CheckClosestPlayer());
}
private IEnumerator CheckClosestPlayer(){
yield return new WaitForSeconds(1);
// Logic
StartCoroutine(CheckClosestPlayer());
}
My first guess would be like this
But it feels weird to restart coroutines this often. Is this not bad for performance
private IEnumerator CheckClosestPlayer(){
while(true)
{
yield return new WaitForSeconds(1);
// Logic
}
}
An infinite while loop with a yield statement.
Make sure to cache the yield instruction prior to the loop
ohh thats a big problem
Ah yes I forgot about this
Coroutines will stop when Gameobject is destroyed I assume
What do you mean with caching the yield?
//Coroutine
var wait = new WaitForSec...
while(true)
{
yield return wait;
...
}```
Oh i didnt know thats possible! Very neat!
I can use this in a few places in my code already
Thanks alot!
And if you need to fire this in Start, you can simply make the Start method a Coroutine by changing the return type to IEnumerator - you'll not need to start it manually.
Oh yeah I saw that before
Will come in handy for the enemies
Then Ideally I would spawn my enemies wth small delays so this doesnt fire every second on all enemies but spread out throughout the second
Or is there a better way to achieve this?
ECS but that'd be an entirely different beast.
Other than that, for what you're doing it should be fine.
Maybe pool your enemies if instantiation is expensive but more often than not it's the destruction of objects invoking GC that's overly expensive.
Yeah I will have to see if its a good idea in my case
My game is multiplayer so that complicates it a bit
But I dont have so many enemies that it would become a problem I hope
I want to put in an URL and then have Unity download each file in the directory.
Does anyone know how to do this?
I cannot figure it out, as when I GET the url path it just gives a blank string in return
UnityWebRequest
Yep, used it a lot in the past, but cannot get all files in the serverdirectory
private IEnumerator DownloadDirectoryContents(string directoryURL)
{
// Make a UnityWebRequest to download the directory listing
UnityWebRequest request = UnityWebRequest.Get(directoryURL);
Debug.Log("getting url: " + directoryURL);
// Wait for the request to complete
yield return request.SendWebRequest();
// Check for errors
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Failed to download directory: " + request.error);
yield break;
}
Debug.Log("got url: " + request.downloadHandler.text); //BLANK
// Split the response into lines to get the filenames
string[] lines = request.downloadHandler.text.Split('\n');
// Call ImportData() for each file
foreach (string line in lines)
{
string fileName = line.Trim();
if (!string.IsNullOrEmpty(fileName))
{
ImportData(directoryURL + "/" + fileName);
}
}
}```
Maybe show what you've tried so they can help you better
The code after //BLANK is not tested. First I need to get all files in the directory, which is where I am getting stuck
you would probably need to use ftp protocol rather than http as directory listing is usually disabled
Ah okay
I will need to look into that, as I am not sure if that will be the most flexible solution. Maybe I will just type out the full file name for the current prototype
maybe hmm been a while since I touched folders on webrequest
You could just zip the contents too
Not too bad of an idea to zip it yeah
you can enable directory listing for http on your web server but that is very insecure as it opens up your file system to the world
may be better writing your own backend API's to do this
Thanks for all the ideas, I'll discuss with the team and start working on it 👌
You were the one doing it too. Answer yourself. And it's not a code question
Is there a way to selectively preload localization tables?
E.g. preload only string tables, while avoid preloading asset tables.
If not possible out of the box, how can I selectively preload those myself?
Can anyone tell me why this code would make my Rigidbody object "jump" upward on the Y axis while moving "forward" on the X Axis?
Rigidbody.AddForce(new Vector3(30,0,0), ForceMode.Impulse);
because your transform is rotated
Just checked and No, rotation is all 0's
it would only jump upward with this if it collided with a bump or ramp or something
Yeah, that is what I was thinking. But my ground is just flat. I will say, that if I increase my normal movement speed than my character start to move upward slightly as the speed increases
Not sure if I have something increasing Y axis for some weird reason
try changing the code to transform.right* 30
You'd have to show your code
one second
{
RaycastHit[] hits;
hits = Physics.RaycastAll(new Vector3(transform.position.x, transform.position.y + .5f, transform.position.z), Vector3.down, battleGroundMaskID);
for (int i = 0; i < hits.Length; ++i)
{
RaycastHit hit = hits[i];
if (hit.transform.tag == "battleFloor")
{
//check distance
if (hit.point.y + .1 >= transform.position.y)
{
battleGrounded = true;
knockBackFloorYVal = transform.position.y;
break;
}
else
battleGrounded = false;
}
}
if (battleGrounded)
RB.drag = groundDrag;
else
RB.drag = 0;
}
void battleSpeedControl()
{
Vector3 flatVel = new Vector3(RB.velocity.x, 0f, RB.velocity.z);
//limit velocity if needed
if (flatVel.magnitude > battleSpeed)
{
Vector3 limitedVel = flatVel.normalized * battleSpeed;
RB.velocity = new Vector3(limitedVel.x, RB.velocity.y, limitedVel.z);
}
}
private void PlayerBattleMovementFU()
{
if (inMainBattleMenu)
return;
if (battleBlockFlag)
return;
battleSpeedControl();
battleRigidBodyCheckGrounded();
if (playerControl == globalControllerScript.PlayerControl.player) //player controlled
{
battleMoveDirection = new Vector3(inputMovement.x, 0, inputMovement.y);
RB.AddForce(battleMoveDirection.normalized * battleSpeed * (battleSpeedMultiplier), ForceMode.Force);
}
}```
Is there any advantage to make a singleton based in monobehaviour if I don't need any of that behaviour in my class? 🤔
You can put it in your scenes and reference it via the inspector, and run coroutines on it
other than that, no
the coroutines one I hadn't considered 🤔
thanks ❤️
Being able to run coroutines is handy, yeah
[field: SerializeField] private TextMeshProUGUI AttackText { get; set; }
[field: SerializeField] private TextMeshProUGUI DefenseText { get; set; }
Do you append your properties with "Text" even tho the type should be enough to clarify what it is?
I am thinking if I should abolish this 😛
Sometimes I use something like AttackLabel
oh Label I like it, tho in my case its AttackValue, would Label still count?
I guess TmPro might imply a lot of things like text formatting, so adding Label/Text might not be a bad thing.
If the class this is in just has TMP Text references, you could get away with just Attack. But just the property type is not enough context for me.
yeah the class is CharacterAttributeUI or something
😄
Btw do you ever use plural in your class names?
CharacterAttributesUI -> Attribute vs Attributes
Sure
Attributes object:
https://i.gyazo.com/5ab11d69998a0aa1b0c2b1a233569eec.png
Hierarchy:
https://i.gyazo.com/de6eb249f14cf7996dcfce4137b60244.png
Do you think I should create a class for an attribute so I don't have to manually add reference for a text field for each stat, but instead a reference to that stat container?(Attack, Defense etc.)
Or is it an overkill?
if it's a simple project then stats can be as simple as enums with a dictionary of values pointing to each enum entry
but if you do have stat modifiers, then making a system of containers to keep track of everything could be of use
I do have Attributes class to return "total" of anything.
But my question is mostly about the UI, if its worth adding another UI class for each stat separately.
Eh, I'd just have a StatsUIManager if needed
looks fine to me
great
So this might be complicated topic or maybe even not worth it.
But is there a way to create a helper function for this type of script?
public void Init(Character character)
{
Character?.ExperienceManager.OnAttributeChange.RemoveListener(UpdateAttributes);
Character = character;
Character.ExperienceManager.OnAttributeChange.AddListener(UpdateAttributes);
}
And second script with same logic:
public void Init(Character character)
{
characterAttributeUI.Init(character);
Character?.HealthSystem.OnHealthChange.RemoveListener(UpdateHealth);
Character = character;
Character.HealthSystem.OnHealthChange.AddListener(UpdateHealth);
}
They subscribe to different events etc, but their logic is the same.
Something along the lines of:
public void Init(Character character)
{
HelperFunctions.ChangeSubscription(Character?.HealthSystem, character.HealthSystem, UpdateHealth);
HelperFunctions.ChangeSubscription(Character?.ExperienceManager, character.ExperienceManager, UpdateAttributes);
}
I think this could work, but idk if its worth it.
it's awkward to try and write a generic type-safe helper method for this because afaik you can't constrain a generic parameter type to be a delegate
[InfoBox("Values Per StatModifier", EInfoBoxType.Normal), Header("Flat Increased Values"), Range(1, 100),
field: SerializeField] public int Health{ get; private set; } = 1;
//causes error
Anyone have any suggestions how to fit attributes nicely? They seem line sensitive, so you can't split them up that well
Normally I give them their own brackets and lines:
[field: Range(1, 100)]
[field: SerializeField]
[field: Header("Flat Increased Values")]
[field: InfoBox("Values Per StatModifier", EInfoBoxType.Normal)]
public int Health{ get; private set; } = 1;```
what's teh code look like and what's the error say?
yeah those need to be [field: Header(...)] as well
ahh, I understand
they only work on fields, not properties
Right, because when it's in its own box it has the field tag, as opposed to one field tag when combining them all
ty
Now you have multiple field: might just write private int health; and save typing 😄
where can i download older versions of cinemachine?
From package manager
where?
If it does not show up you can specify the version you want in Packages/manifest.json
like this?
o wait nah thats wrong, im not sure which file im supposed to be in. i cant find a file called manifest
It's outside of Assets folder so you wouldn't see it in Unity
This looks like right file
ohhh ok, i found the right file now. thank you!
the file i had edited was some random package.json
I usually use the word "Display" mostly cause I find typing attackText.text = ... more odd than typing attackDisplay.text = ..., and I use it as a naming convention so I know anything with "Display" in the code, is likely to be a text type, though I think "Label" may be more descriptive as a convention
Makes sense!
I also had similar concern of typing text.text before
Hello, im new here amm and i dont know if I can do a question?
Oh, don't cross-post
Just stay in #💻┃code-beginner
so im making a race game and i wanted to try and make my own wheel collider because i had some issues with the unity one and this seemed like a fun and usefull thing to do. i have started with making the suspension of the car. the way i make this work is by having my wheels as child of my car. i then get a start value and use that to modulate my car up and down with addforce. this works nicely to a certain point. when you get on slopes or things like that the car launches into the air. i cant find why its so unpredictable and what im doing wrong. https://gdl.space/ejukepires.cs this is my script. other coding tips or tricks that could help me are of value to me as well.
Anyone have issues with a List/Array clearing upon entering playmode? There is no code creating a new list or anything. It is private as well so no other class is altering it.
that's not enough info to really diagnose what is going on, a list wouldn't just clear itself for no reason
Oh I think the issue is that I renamed the list and something else is now its previous name. Seems serialization has caused some issues
[SerializeField] private List<GameObject> townsPeoplePrefab;
public Transform shopPosition;
public List<GameObject> townsPeople;
[Header("Game References")]
[SerializeField] private VampireSpawner vampireSpawner; //later will have to inject and shit
private void Awake() {
Debug.Log("Array has items: " + townsPeoplePrefab.Count);
//townsPeople = new List<GameObject>();
Debug.Log("Array has items: " + townsPeoplePrefab.Count);
StartCoroutine(SpawnTownsPeople());
Invoke("SpawnMonster", 5f);
}```
Sorry bunch of random debugs trying to see where its cleared but every log statement says it is 0.
townsPeople was the old name of townsPeoplePrefab
I think clearing that list is what was clearing the other one perhaps
//townsPeople = new List<GameObject>();
commenting out this line changes it a bit where it now looks like the townspeople isnt being cleared in the inspector but it is still saying there are 0
Might be because of my fast script reloader asset. I think it is improperly recompiling
this is usually the case when weird compiling issues happen
Manually recompiling isnt fixing the issue tho. Control+R is how I am doing it but is there a better more extensive way?
but also townsPeople = new List<GameObject>(); would not affect the townsPeoplePrefab variable at runtime
Yes my exact thought. I think it is because townsPeoplePrefab was first named townsPeople before I changed it. So with some sort of compilation issues its clearing the list but idk
This was an array and the other a list so I don't know why it was giving me issues then too.
again, at runtime that would not have any affect on it. show a screenshot of the inspector outside of play mode
The screenshot I sent was outside of playmode
movePosition = targetPlayer.transform.position + new Vector3(attackRange * Mathf.Sign(targetPlayer.transform.localScale.x), 0, 0);
if (Vector3.Distance(transform.position, movePosition) > settings.moveSpeed) {
transform.localScale = new Vector3(Mathf.Sign(targetPlayer.transform.position.x - transform.position.x), 1, 1) * scale;
movingSpeed = Vector3.ClampMagnitude(movePosition - transform.position, 1) * Mathf.Min(settings.moveSpeed, (movePosition - transform.position).magnitude);
transform.position += movingSpeed;
} else {
if (actionType == ActionType.Power) {
StateSet(PlayerState.Strike);
} else {
if (!reversalAttack && !counterAttack && (TargetPlayer != null) && TargetPlayer.CounterAttack()) {
StateSet(PlayerState.Idle);
} else {
StateSet(PlayerState.Strike);
}
}
}```
guys why is the transform.position not changing in this code? the transform.position is not changed anywhere else
the list has 0 elements in that screenshot . . .
yes and the one you are checking the count of has no elements
Oh I see those items belonged to the old list I guess it transferred over that makes sense now nevermind
do you have a charactercontroller?
Since I renamed
i mean, it does at least have whatever this component is. show the full code
what do you mean? i checked what code executes and the code in this IF statement is the one that runs, but the position doesnt change
if (Vector3.Distance(transform.position, movePosition) > settings.moveSpeed)
that doesn't prove that nothing else is overwriting the position anywhere
yeah, it did work before a change but not sure why
Yeah its not just a slap it in and it will work kinda thing , just take a look at the script and im sure you will be able to understand how it works
you will def need to repurpose methods out of it for your own needs
vs code is causing me lots of grief. from what i've learned online, i think it's the intellisense not working. but also, none of my scripts can access other scripts.
solutions i've tried
- uninstalling and reinstalling vscode and .net
- deleting project files and having unity regenerate them
- deleting the entire unity project off of my computer and reinstalling it thru github
- removing and updating all relevant visual studio unity packages
- opening it from Assets/Open C# Project
the image attached shows intellisense not working. it's like each script is completely isolated from every other one, including the libraries.
does anyone know what the hecks going on 🙏
make sure that !vscode is configured. if you continue having trouble with it after following all of the steps, you should consider switching to a real IDE that is less likely to randomly break
!vscode
yeah i've tried that, ill just switch to visual studio then
it wont let me launch unity bc i have a pub network how do i fix?
#💻┃unity-talk is the right channel. And don't cross post(ask in multiple channels) next time.
ok mb
Is using scriptableobjects to store relevant data not a sufficient save/load solution? I thought it was, and it when using a scriptableobject to store 'completed levels' it works fine in Unity. But when I build to phone it seems to forget that info when closing and opening the game
changes to scriptable objects do not persist in a build. it only does in the editor because you are changing the serialized values on an asset
So I know json serialization is often the solution for a PC game - is that also the normal save load solution for a mobile game?
yeah
Do you have to encrypt to prevent save cheating on mobile?
The game has microtransaction items so
if saves are stored locally then anyone dedicated enough will manage to modify it. the only true way to prevent cheating is to store all that data server side
Hmm... well I still can't even decide where free with micro transactions is better than just charging straight up... do small games with no marketing (assuming they are fun + high quality) make any money with the free with micro transaction model? or does that require economy of scale to do anything
guess I should do market research... blegh...
if i were publish fast, i would charge in my view, there is less code i need to to inside app
Hey all!
Anyone got some tips for an online player counter?
I have one implemented already that ive coded myself interacting with a vps i own which is able to queue requests to increment and decrement the online player count.
works great only 1 issue though if you close the game from task manager it never calls OnApplicationQuit which decrements the online count.
How can I use this function:
instance.GetComponent<Button>().OnSelect(() =>
{
});
Trying to detect when a button is selected(it's used for selecting a category of list items, when I "select" different category I want to update a list)
Above throws an error, but the only thing I found in docs is outdated.
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.Selectable.OnSelect.html
pretty sure for an accurate count you'd want some sort of heartbeat where clients regularly tell some central server that they are still online, then if the heartbeat isn't received after some arbitrary period of time that client is no longer considered online
Thanks that explains pretty well what i need to do!
i know for socketio, which i am testing for my game, there is a on connected/ on disconnected event. everytime someone connect you can add 1 to counter, then disconnect minus 1
Seems like I digged out forgotten technology, it doesn't seem to be used anymore and I cant google much, other than Select Handler, but I was hoping to do it through my manager class instead of creating a class for a button.
Thanks for that info! i think ill incorporate that into it
i treid fishnet but it too high level for the type gamie i make
cant you just subscribe an event to a method for the button ?
What do you mean?
i guess i should ask what is it that you are trying to do
I want to call a function when a button is selected, but I dont want to attach a script on a button if possible(tho I am doing it now since nothing else works for me :P)
thats what i thought
I want those buttons to act as category selection in game, to update inventory list with different items based on their category.
Since enums can't be used in the inspector, I have to do something else.
Otherwise I'd use EventTrigger
may i ask why you dont want the button to have a reference to a script in the onclick method
Because I dont want to click a button, I just want to move between buttons with something like arrow keys/d-pad and it should automatically switch categories without having to presss [x] or enter
Maybe button is not a right component for it?
enums can be used in inspector if you do somethign like this
Public ENUMNAME enumdropdown
public enum ENUMNAME
{
Type,
Type1,
}
It cant be used for function calls, at least didnt work for me
there may be another function like socket.ConnectedClients to get exact number of clients as alternate but i have to review that
you would have to create some code that says that a type of the enum is = to some method and create a way to call that method based on the selected type
I dont understand what do you mean 😐
let me try to explain easily
why are you trying to do this
Well, I can achieve what I want by adding a script to a button...I was hoping for a simple solution.
why is it that you are trying to attach a script to the button and not just assigning the script as a reference in the inspector of the buttons on click method?
are you trying to procedurally generate the buttons?
I added this script on a button and that solves it:
public class InventoryCategoryButtonUI : MonoBehaviour, ISelectHandler
{
[field: SerializeField] private InventoryCategories Category { get; set; }
public void OnSelect(BaseEventData eventData)
{
InventoryUI.Instance.RedrawInventory(Category);
}
}
I just wanted to avoid having to create this script.
Because if you do that, then you can't use functions with enums are arguments.
that's not an answer to the question i asked. what is the actual purpose of this code, what is it supposed to do and why have you decided to use reflection to refer to the list by a string of the variable name
public void RedrawInventory(InventoryCategories categories)
{
}
You can't call this function from Unity inspector onClick event.
maybe i dont understand what you are trying to do... but hey aslong as you got it to work!
remember nobody cares what the code looks like in the end only the final product
I didnt, I just went the route that had to work, I wanted to avoid adding a script to a button.
oh my god
did you even bother reading what i asked?
no, it most certainly is not
at this point, no. because you won't bother providing info on why you've decided to do this specifically or what the goal for this code even is. which is what i was asking about, i do not give a shit about whether this is for your friend, for the president of the united states, for a homework assignment, in order to take over the world, none of that is relevant to the actual code
Tbh this question is confusing me as well, what are you asking for exactly here? His purpose of writing this code?
obviously yes because it makes absolutely no god damn sense to be using the name of the field and reflection for this at all
it's just some weird fucking XY Problem that they refuse to explain https://xyproblem.info
Idk try to debug it and separate GetType() and GetField() and see which one gives null, then you are one step closer to fixing it.
I never used GetType() not sure what it does, does it GetType of your current object/class?
Returns
Type
The exact runtime type of the current instance.
i am not asking for any personal details. are you just intentionally ignoring what i'm actually asking about?
i was trying to understand the fucking point of the code. not why you decided to sit down at your computer andwrite the code, but what the code is actually trying to fucking accomplish
No reason to discuss it any further, maybe you two are not match for each other 😛
then show them this: https://xyproblem.info
and then find out what the code is actually supposed to do because you are currently attempting to solve an issue that makes no fucking sense to even have
I kinda agree, I am confused as well.
Is it trying to find an item on a List of Sprites called Hat, by using a string? So its trying to compare object Name(in hierarchy?)
Why can't your friend ask for help then? It's really frustrating when trying to help someone via a proxy without the full context.
Well the best we can do to help, is tell you to debug your code like I mentioned and see where the issue happens step by step.
Well, if you don't have a home, just buy it are not on discord, just get on discord.🤷♂️
my guy, whatever this is supposed to be solving is what should be discussed, not this. because this is some hairbrained attempt at solving something else. so instead of trying to fix this broken solution that makes no sense to use in any context, we should instead be focusing on the actual problem
This code to me looks like some weird complex puzzle with no purpose, but idk maybe thats his assignment.
I doubt you ever use that kind of code in real projects(but I could be wrong)
Which is why its hard to help without more info.
This whole situation feels really silly to me.
Just tell your friend to get his ass up here instead of running errands for them
Tbh when you help people all the time here it can be frustrating sometimes 😄
i'm just absolutely flabbergasted that anyone would answer the questions i asked in the way that you did
Not that I spend much time helping <_<
"what is the purpose of this code"
"i'm helping my friend"
"what is the code supposed to do"
"i'm helping with his homework, why do you want my life story just help with my code"
Well anyway, I will bring back my question with my attempted solution that I dont like, because it forced me to create a script specifically for this.
public class InventoryCategoryButtonUI : MonoBehaviour, ISelectHandler
{
[field: SerializeField] private InventoryCategories Category { get; set; }
public void OnSelect(BaseEventData eventData)
{
InventoryUI.Instance.RedrawInventory(Category);
}
}
This is on a button.
Can I achieve it without having a script directly on a button, but rather use my Manager class and do:
var instance = Instantiate(ButtonPrefab, parent.transform)
instance.getComponent<Button>().OnSelect()//??
The issue is mostly there due to enum, each button represents a category which is meant to update List of items based on selected button.
Perhaps a Dictionary<InventoryCategories, Button> would do?(Asssuming that I find a way to call a function on button Select)
EventTrigger on a button, calling a function in my inventoryUI.Redraw() and then comparing Button instance to dictionary?
Dictionary<Button, enum>
There should be an event you can subscribe to on the button.
OnSelect isn't an event on a Button. but you can use an EventTrigger that will raise an event when OnSelect is called on it by the EventSystem
onClick is the only event, oh...what if I add EventTrigger and simply use that in code...
let me see that lol
No idea how to use that in script, it says that I cant use lambda expression.
instance.GetComponent<EventTrigger>().OnSelect(() => { });
The reason I cant do it from the inspector is because I have enum(for each category)
public enum InventoryCategories
{
Healing,
Combat,
Key
}
And there is nothing I can find on google about OnSelect, except ISelectHandler, but that requires a script on a button directly.
I'd just use a script with IPointerDownHandler or something.
because OnSelect is still not an event there. but the event is in the EventTrigger's triggers list and you can subscribe to it in there
Thats what I did since I couldnt figure it out.
So I need to pass BaseEventData to OnSelect right?
no
because that is not the event. that is just the OnSelect method called by the EventSystem
So there is no way call this:
instance.GetComponent<EventTrigger>().OnSelect()
I dont understand how this is supposed to work.
i feel like i'm talking at a wall
that is not the event
that is literally the exact same method you have implemented from the ISelectHandler interface. you do not call that manually. nor can you subscribe to it because it is a method. the event on the EventTrigger is in the triggers list like i already told you
I got that, I am trying to understand what its purpose is(OnSelect) since I can call it directly from script.
oh
thats what I thought, so this is like Invoke()
BaseEventData eventData = new BaseEventData(EventSystem.current);
instance.GetComponent<EventTrigger>().OnSelect(eventData);
I was just playing with it and this code compiles, not sure what it does tho.
Either way I understand that its not an event like onClick
no, that is the OnSelect method called by the EventSystem, exactly like your OnSelect method for the component that implements ISelectHandler because the EventTrigger implements ISelectHandler
congrats on fixing the worst possible way to refer to a variable at runtime 👍
maybe next time you need help it will be with something that actually makes any sense to do
and hopefully whatever the fuck you did actually solves the initial problem your "friend" was trying to solve
So actually chat gpt did give me a solution, trying to understand how that works tho as this is a new way for me
private void AddOnSelectListener(Button button)
{
EventTrigger eventTrigger = button.gameObject.GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry
{
eventID = EventTriggerType.Select
};
entry.callback.AddListener((eventData) => OnButtonSelect((BaseEventData)eventData));
eventTrigger.triggers.Add(entry);
}
private void OnButtonSelect(BaseEventData eventData)
{
Debug.Log("Button selected!");
// Add your custom logic here
}
Kill me
this is just adding a new entry to the triggers list instead of using the entry that should already be in it
that second screenshot doesn't necessarily show that you are not missing a closing brace. unless your !IDE is correctly configured, in which case you need to save your code and let unity recompile it
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Welp, that was it. I forgot to save it
Just testing you haha 
I will prob just stick with a script on a button lol
Not sure if that is a bad thing, but it works with that code?
it doesnt seem to create multiple events either, so its calling my function only 1 time even if I create that trigger multiple times.
eventTrigger.triggers.Find(x => x.eventID == EventTriggerType.Select)
Perhaps I should do that?
It's probably a better thing. Since you only implement what you need in it, as opposed to an event trigger implementing all the possible events.
But if the event already contains all of them by default then I dont need to add it manually?
I never used this kind of code, so I am experimenting with it :d
So, I'm planning on working on a system that requires a list of prefabs in specific locations to be instantiated.
Part of that plan is a scene dedicated to "capturing" these prefabs and storing them in a Scriptable Object in edit mode. So I'd have a script that takes everything in the scene with a specific component, captures its Parent and Local Transforms, and stores them in the Scriptable Object so the collective object can be spawned from that SO.
Since Scriptable Object Runtime Edits are persistent in Editor, I should be able to simply have a normal script that edits the SO directly, and it will retain the changes due to the changes happening in editor.
Is this a good idea, or am I thinking about this from the wrong angle?
private void AddOnSelectListener(Button button, InventoryCategories category)
{
EventTrigger eventTrigger = button.gameObject.GetComponent<EventTrigger>();
if (eventTrigger == null)
{
eventTrigger = button.gameObject.AddComponent<EventTrigger>();
}
EventTrigger.Entry entry =
eventTrigger.triggers.Find(x => x.eventID == EventTriggerType.Select);
entry.callback.AddListener((eventData) => RedrawInventory(category));
}
Testing this code now
Yeah that doesnt work, its null
I meant your own custom script on the object replacing a button or event trigger entirely
yeah i agree, I should use my button script, otherwise in few weeks I will get confused by this 😄
You mean you basically want to use the scene as an editing tool to position the prefabs?
Is there a reason not to just load the scene?
1 last test tho, I will attach event on a button EventTrigger manually to see if that works
Pretty much, and I'm using it to design "items", not scenes. So I'd make a custom piece of equipment out of prefabs, and store that "Equipment" so I can use it like a sort of "cluster prefab". This will give me an early approach to item customization, which I can adapt to runtime cases of creating these "clusters" later on.
https://i.gyazo.com/714688960a4e91da0dc5ccf89852dfaa.png
This works, I understand now.
Its weird tho.
Does EventTrigger.triggers use some custom List?
In the inspector you can't attach 2 of the same event types.
But there is nothing preventing you from doing that in a script?
eventTrigger.triggers.Add(entry);
eventTrigger.triggers.Add(entry);
Nevermind, its basically same as subscribing 2 times
Even tho you cant do that in the inspector, but it works in a script.
Is there a reason you're doing this rather than just having another prefab of the combined objects u want? I dont really see the use case
You can't create prefabs during runtime, so if I want item crafting that lets you combine items, I have to make my own implementation for testing it before starting work on an actual runtime item crafting system.
for(int i = 0; i < (int)InventoryCategories.Length; i++)
{
var instance = Instantiate(InventoryCategoryPrefab, InventoryCategoryUI.transform);
InventoryCategoryButtonUI categoryButton = instance.GetComponent<InventoryCategoryButtonUI>();
categoryButton.Init((InventoryCategories)i);
}
Is there less ugly way of doing this?
Specifically casting enum to/from
You probably can create the prefabs at runtime, with some editor code. But why do you need to create these at runtime at all? I assume you are talking about editor play mode because SO wouldnt persist on a build. So you would have to save this data to a file regardless
You can only create prefabs in the editor, not in a packaged build. I plan on holding item cluster templates in SO assets, which I can create and edit in Editor.
For the actual built game, I'll need different methods of creating the item clusters, namely a custom item crafting system that hooks into the same parts for storing data.
I can just have the SOs hold a class which is shared with the serializable one that Players will be making/saving to JSON.
This seems a bit different from what I thought above, so you mean SO for the use in editor but just a regular class and json for the runtime?
This seems fine I guess
Yeah, the usecase here is "I don't want to make an in-game item crafting system until I've tested that the underlying item systems are functional"
So using a scene that acts like an editor only item crafter is my plan
Does that make sense?
Plus, I can assign the editor-only SO's to enemies as template items for them to equip
Hello-
Current I'm using Physics.Raycast for NPC's pathfinding, however they seem to get caught on objects (More specifically, objects beneath/above the raycast)
I was thinking of changing it for Physics.Boxcast (https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html), but I'm worried about the performance difference between the two...
Does anyone know which is faster? Or if Boxcast is any different performance wise?
Raycast is faster that any other cast. That being said, the difference might not be significant enough.
It's something you need to decide yourself based on the context of your game and use case.
Use the profiler to see how much impact it has on performance in your case.
As for your issue, might want to explain a bit better or provide a video. I don't think I understand it correctly.
why is it that if i do
if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
{
Debug.Log("combination pressed");
}
directly in Update it work but if I call a public void method containing this code in Update id doesnt work?
Currently, I'm using dynamic pathfinding. It uses a couple Vectors for pathfinding- The NPC moves towards the target position, and if there is a wall in the wall, move to the left/right and continue until the direction you were going at is good
You'd probably want to show both implementation as likely there are other differences.
working:
// Update is called once per frame
void Update()
{
if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
{
Debug.Log("SO pressed");
}
}
public void KeyCombiner()
{
if(Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.O))
{
Debug.Log("SO pressed");
}
}
void Update()
{
KeyCombiner();
}
@dusk apex
second way
this the not working one
Are you trying to two variation on the same object or different objects?
it just in a script that attach to canvas object and i comment out one method vs the other, i dont run both at same time
Hey all I'm working on an inventory system and im running into a problem when moving the items to other slots in the inventory. when an item is picked up it seems to only want to move to other slots when you drag from the original slot it was picked up in. I was hoping someone could maybe take a little look and see if there's something logically im doing wrong, the data all sends correctly its really just the drags that seem to messed up at this point. https://hastebin.com/share/yobapapeju.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can't see why that should produce different results. Can you have both ways with different logs and test to see if both logs are printed?
sure
thank, both work now and when I ran together i see they both print
perhaps i forgot to comment something that blocked one of method from showing
Hi friends, I have a 2d grid of tiles and I can delete some tiles from the corners then I want to show a number of tiles in the text on every side and inside the cut as well, how can I do this easily?
First, how are you doing this? Is it via scripting or gameobjects?
I am generating this object grid via scripting
Could I see what the script looks like?
https://paste.ofcode.org/fcPM4Pps8y5kDTNe6eLjEs. this part of the code that generate the 2d grid
objects are tiles arrage in 2d array
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PanelMover : MonoBehaviour
{
public float moveSpeed;
public bool isOpen;
public GameObject panel;
public bool closeOnStart;
public bool openOnStart;
public Vector3 closedPos = Vector3.zero;
public Vector3 openPos = Vector3.zero;
private Coroutine moveCoroutine;
private void Start()
{
if (panel != null && isOpen && closeOnStart)
{
ClosePanel();
Debug.Log("Panel closed.");
}
else if (panel != null && !isOpen && openOnStart)
{
OpenPanel();
}
}
[ContextMenu("Close")]
public void ClosePanel()
{
if (moveCoroutine != null)
{
StopCoroutine(moveCoroutine);
}
moveCoroutine = StartCoroutine(MovePanelFromPosToPos(panel, isOpen, closedPos, moveSpeed));
this.isOpen = false;
}
[ContextMenu("Open")]
public void OpenPanel()
{
if (moveCoroutine != null)
{
StopCoroutine(moveCoroutine);
}
moveCoroutine = StartCoroutine(MovePanelFromPosToPos(panel, isOpen, openPos, moveSpeed));
this.isOpen = true;
}
public void TogglePanel()
{
if (!isOpen)
{
OpenPanel();
}
else
{
ClosePanel();
}
}
public IEnumerator MovePanelFromPosToPos(GameObject panel, bool isOpen, Vector3 to, float speed)
{
while (panel.transform.position != to)
{
panel.transform.position = Vector3.MoveTowards(panel.transform.position, to, speed * Time.deltaTime);
yield return null;
}
}
}
free code for you guys , moves a panel from one place to another using the given speed , can tell it to open or close on start (enjoy)
also has context menu buttons for debugging purposes
you can also toggle or just open / close
asked this across multiple servers but quick survey
both are equally valid, there really isn't a "correct" answer here, do whichever makes the most sense for your project's style and architecture
although i would personally take that position, rotation, and scale and throw those into a TransformData struct and use that and the other two arguments. since that TransformData could then be reused for other things, like save data and the like
I'd argue many parameters is bad when most of them are optional
Then an object would suit better
But then again, an object is less convenient to work with
So yes, it really depends
theres two arguments made here
i preferred 2 because some arguments are optional, you wont always render a box with all the parameters and you might even be able to reuse the object if you call it multiple times
but low level programmers prefer 1 as if you pass in a whole object, the whole object gets put on the stack rather than some arguments being put on the register, making your code much slower esp since this is called every frame.
also, args.material is bad syntax
even my lecturers are split on this
everyone is split on this
right, like i said both are equally valid options. choose whichever makes the most sense within the context of your project
Anyone know the process for making your own custom LayoutGroup? The documentation is kinda.. rough.
There is no documentation or formal process. The code is open, just look at what the others have done and replicate what matters for what you want
Ya giving it a look at now.
It's just it seems to require 4 method implementations, none of which are kinda clear.
What's a good place to find the implementation of some of these classes? Specifically the HorizontalOrVerticalLayoutGroup class?
In your project
Odd, it's not letting me inspect it.
Alright never mind took some fenagling