#archived-code-advanced
1 messages Β· Page 85 of 1
app store
So you're publishing this build to the store/testflight to test?
How are you testing it?
I vaguely remember ios being tricky to test since it only works if you click on a link and not when you manually enter it or something silly like that
using xcode and unity editor, i added a debug to print the application url but nothing shows
first i have to get back the application url, then send it to the server to include it in onesignal push dialog so when the user clicks on the notification. it directs them to that page indise the application
Anyone got a good tutorial on how to get started setting up a dedicated server in Unity?
Like the actual programming aspect of it, not how to set up the server and get it online & stuff.
This one seems promising https://www.youtube.com/watch?v=FjOZrSPL_-Y&t=889s
It came up as one of the first videos when googling "Unity how to set up dedicated server"
Next time just quickly google the question before you ask
π₯Get the Source Codeπ₯
https://www.patreon.com/posts/82134830
If you liked this video please like and subscribe as it helps me a lot, and consider joining my Patreon or becoming a YouTube Member :)
βΊCheck out the Previous Video
The Ultimate Multiplayer Tutorial for Unity - Netcode for GameObjects
https://youtu.be/swIM2z6Foxk
βοΈ Set Up βοΈ
βΊMul...
i think there are existing solutions provided by Unity.
if you want to learn how to set up a server in view of programming, the first thing you should know is server can be written in different language.....you should define the api and how your server handling them (note that the api can be "used" by other front end, the server can have no idea who is sending the requests, you need authorization to solve this)
just like how you set up server for other front end applications
doesn't seem very useful to me
I don't need hosting or matchmaking
I just want to build a dedicated server that is capable of running my game logic and communicating with clients
It's also based on a previous tutorial of something completely different than what I want to do
I'm looking at Multiplay and Cloud Code right now for example
How am I supposed to choose which one I want without knowing a lot about both of them?
What is the role of the server here ?
I'm making an Idle RPG - the clients never interact with each other, they only interact with the server
all my game logic needs to run on the server to prevent cheating, same with data storage
I'm checking the cloud code setup now, it seems like what I need
I just don't know the limitations and it seems pretty hard to find good descriptions of what everything is and does
ie your game is just a display
yup
are you planning to use asset store assets, like plugins or graphics?
If you want to prevent cheating, depending on how your game is, you would pretty much needs a Unity instance for your server. Because, otherwise, you will have a hard time to collision check and validate from the server.
yes why?
there are no collisions, just math
it's pretty much all numbers with some fancy graphics on the client side
Then something like Cloud Code is what you want. You could also choose for any TCP/UDP wrapper in C# or other language you want.
how scalable is cloud code?
https://docs.unity3d.com/Packages/com.unity.package-manager-doctools@1.9/manual/index.html <- Any chance that this package will be made available for external use? I would love to use it to generate DocFX pages for my packages.
Extremely scalable depending on how you make things. However, as I read, I think Cloud Code is not made to keep connection up and do validation but more for things that are inline with a REST API. You might want to create your own server and only use a service to host you server. Something like Google Cloud, AWS would be more inline with that.
thx a lot for the info π
Can someone explain why RenderTexture doesn't render colors?
on HDRP
these cubes should have colors
doesn't sound like a code issue
you're at the start of a long journey
i don't know what i am looking at. on the left, it looks liek the exposure is wrong. on the right, it looks like you have another misconfiguration
I edited the first message, I hope it conveys it better now. So what will be the problem?
what is your goal?
generate icon for gameobject at runtime
okay, and also, is there a specific reason you're using built in render pipeline?
the problem is that the game to which I am adding the level editor already has HDRP, so I cannot change it
okay. you're modding a pre-existing game, or you have the source to a pre-existing game?
pre-existing
okay
and in the viewport, what are we looking at exactly? experimenting with creating the thumbnail, in a plain scene?
To test faster, I test in the editor since it will be the same, but yes
and you're using hdrp in the editor?
yeah because game uses HDRP
i think you should try to create a camera and render to a render texture first in the editor, at design time
so you can see some of the aspects of what is missing
you are trying to use built in render pipeline approach code to an hdrp rendering problem
which is fine, that can eventually work
but there is a lot to do
the first image in your screenshot appears to have color, but appears to be incorrectly exposed. it will need a volume; or you will have to find the game's volumes and use them. the image on the right appears to be flawed some other way.
you shouldn't be rendering with depth. that can have unintended consequences
a render texture can be directly set as a texture for a material
you can also read the render texture's bytes later, using an async gpu readback request, and ImageConversion can turn that into a PNG or whatever for you
@magic scroll good luck!
thanks I will try it
Hi guys, sorry I'm x-posting this from the iOS channel:
I'm having some issues regarding iOS Universal Links and Unity. I want to open my app and fetch the user id when user clicks on the deep link https://refer.mydomain.com/?userid=123456. I have uploaded the apple-app-site-association file to my domain's https://refer.mydomain.com/.well-known/ directory which contains the following data:
{
"applinks": {
"apps": [],
"details": [
{
"appID": "ACBJSD1234.com.mypackage.id",
"paths": ["*"]
}
]
}
}
I have validated the above file using https://branch.io/resources/aasa-validator/ and it shows as valid.
I have also added the Associated Domain capability to the entitlement file with the domain: applinks:refer.mydomain.com. Now I have used the event listener provided by Unity to detect the deep link that is used to open the app. Now the thing is, my app is getting opened when I click on the link, but I'm not getting the deeplink data inside Unity. My doubt is that maybe my apple-app-site-association file is not properly set, specifically the paths key. Can anyone help?
Branchβs Universal Links Validator analyzes your site to check if your apple-app-site-association is properly hosted for Universal Links.
use this instead
https://app-site-association.cdn-apple.com/a/v1/yourdomain.com
and see what it says
i believe the paths should start with a /
and maybe they have to be terminated by a constant string, maybe not
https://app-site-association.cdn-apple.com/a/v1/yourdomain.com
this domain is showing the same data as that I have uploaded to the .well-known directory.
Actually I already tried this as well like this: "paths": ["/*"] but that's also not working
Also, in the official documentation, the syntax of this file is slightly different than what I have seen in many tutorials: https://developer.apple.com/documentation/xcode/supporting-associated-domains Why is that?
If you check https://facebook.com/.well-known/apple-app-site-association, their syntax is like that of the docs but if you check https://twitter.com/.well-known/apple-app-site-association, they are like what I have implemented.
Here's my problem and the thing i do not understand.
I got an elevator with the following parts ( see screenshot )
Platform - Empty object, with a Scale of 1.0, which is moved by the elevator script
Platform.Physical - the visible mesh and the ground collider
Platform.Attach - trigger-collider that makes the player a child of itself.
The player is a Unity.CharacterController moved in Update
The elevator script moves the Platform in Update
I got debug lines showing, that the player character while being a child of Platform.Attached is moved by the exact amount that the whole platform is moved.
This works flawlessly while moving upwards, but moving downwards, the player OnTriggerExits the attach-collider.
The player is a CHILD of the collider and has ZERO movement in local space relative to the collider, they are both moved by the parent of the collider. Yet the OnTriggerExit happens.
The coordinates after moving both objects in Update logged and then in the next physics tick logged:
a) same coordinates -> TriggerStay
b) same coordinates -> Trigger Exit
what the magic?^^
And yes, it's a repost from Physics, because there is no activity in Physics.
I know ur all busy so dont reply if its lame, but I have this issue of trying to retain the fractured peices in the scene after the second fracture. As you can see the 2nd time around the pre-existing peices just get drawn to the impact point and dont generate a new cluster.
Do i need to make an Entity Pool manager and move the fracture prefab into that and wack it on a separate layer?
Player(prefab)
-cube(Fractured Model)
-- Rigid Body
-- Collider
-cubenice(player model)
-- Rigid Body
-- Collider
-- Fracture Script
-- Movement Script
-MainCamera
-- Look Script
Respawn(blankgame object/rs point)
I don't know what exactly you're debugging, but it's likely the transform positions. You need to remember that they don't always correspond to the internal physics simulation position. Moreover, moving colliders/triggers/rbs in non physical way(via transform for example) can further amplify the problem.
Lastly, I don't think CC triggers an OnTriggerEnter, so you probably have an rb somewhere, which doesn't play well with CC either.
Lastly lastly, the timing of CC update could also be a contributing factor(talking about it's internal update, not when you call Move), since it could be out of sync with the physics update making it register an exit out of the trigger.
To summarize, there are many factors that could be causing the issue. You can try eliminating the mentioned factors one by one to determine the cause.
Basically, you need to get new fractured model for each cube you destroy. Wether to use pooling for that or not is up to you. If you do use pooling, you'd either be limited to certain number of destroyed objects at the same time or will need to instantiate new objects to the pool.
Totally not an advanced question btw.
At leat you respond, ill take the hit. thanks man
I'm sure you'd get a more suitable and fast reply for that in #π»βcode-beginner
why when ive got advanced people who are smarter here lmao
Well, with such an attitude it's easy to get a bad reputation on this server so you might end up not getting any help in the long run or even get banned.
its alright man, with enough head banging / gpt and the available doco ive pretty much learned not to rely on human help anymore. Ill sort this eventually. I always do. Just feeling lazy today cuz i had a big win last night π
I also like to empower other people so they never have to rely on developers lmao
Its beauitful thanks bro
I don't know if I should use JSON or SQL to save my player game states
It will be a single player game that runs on cloud code, but players will find lots of items
The database is needed for trading items between players, sorta like an auction house
I know SQL would be really good for this, but I don't know if JSON is good for this but that seems easier to implement in unity?
I do have a bit of experience with SQL, I also know how JSON works, but never implemented any sort of "database" with it
SQL is a data querying language, while JSON is a data exchange format, they are not comparable.
sure they are, I can use both to store my game data
What you probably mean is "storing my data in database and querying my data with SQL" vs "storing my data in file as JSON and querying my data in memory"
probably
Is this some authorative game?
not sure what that means
Doesn't sound very singleplayer when you can trade
But anyways, it mostly boils down to "can I fit all of my data in memory."
I highly doubt that, so I should go with SQL?
If the answer is no, then some kind of database is needed (the querying doesn't have to be SQL), otherwise you can choose to have everything in memory (the format doesn't have to be JSON)
does unity have any build in mysql database / sql support?
or does it support some other database type?
No, but are you going to write your server in Unity?
Because the client should never have access to the database.
will be in cloud code
No, you'd need to bring in something (and often time you don't want to go raw SQL either if the database has any real complexity)
shouldn't get too complex I think
I think you have asked about it before though, I'm not sure what a Unity server can get you since it's not like you can make use of what it gives you, I'd suggest just writing a standalone backend
You get much better DX, at the very least not having to confined to Unity's old C# version and all the caveats with NuGet packages.
any suggestions?
I have written a nodejs server before, but had a really really hard time figuring out how to prevent getting ddos'ed
I'm sure I can write .NET as well with some basic tutorials
You don't solve the DDoS problem by using a different language/framework, and you don't usually solve it on the application level at all.
that's why I'd like to use the unity cloud code service, I assume they have something built in?
It's typically the job of what sits in front of your backend application, eg the reverse proxy (like nginx) or DNS (like Cloudflare)
I'm also not a big fan of having to work with Javascript and C#, makes things a bit confusing
It doesn't matter what language the backend is in.
If you like C#, then sure go for it.
.NET is a runtime, C# is a language.
And yes you can write a backend in C#, the most commonly used is ASP.NET Core.
(Backend specifically ASP.NET is probably what C# being used the most, rather than game dev)
ah that's what I meant, ASP
this is why I hate programming lol
I just love writing code, I hate everything else
Well if you are making a multiplayer game, you will have to deal with infrastructural stuffs sooner or later, so might as well now π
yeah π¦
Cloud stuffs are basically "paying for convenience."
my game has gotten to the point where I need to save the player data in order to continue working on it
but I need to figure out this server stuff to save player data, wanna do it right the first time
could I just save the player data in files with json instead of a database, since that seems to be a lot more logical for unity?
and then save the tradable items for multiplayer in an sql database?
you can use sqlite locally, setup interfaces to exchange with pluggable db, and then the server db exchange would be abstracted
that is a lot of words π¦
you can also setup local server on your machine and work with it as if it was a remote
yeah the issue is not the database management, I know how that works, at least the basics
I just don't know how well it works with unity
for example my items are scriptable objects, how would I save that to a database?
write code that handles exchange at specific points
scriptable object is just a bunch of fields/properties, those can be mapped to columns, for example
there are most likely assets/github repos that do that with reflection
Are you saying to save some player data locally, but multiplayer items remotely? Beware any local data can and will be compromised.
no on the server, not locally
but I guess I won't have a server if I use cloud code
I mean if your server is already going to have a database for tradable items, you might as well just make one more table and store other player data there.
true lol
I'm trying to deeplink into my Windows build.
I'm following this documentation: https://docs.unity3d.com/Manual/deep-linking.html#testing-example-html-file
When I use the HTML example provided, nothing happens when I click the buttons. Shouldn't there be a popup that asks me to pick an app?
UWP?
I have a series of compute shaders (And Graphics.Blits?) that create and modify textures that I need to run in sequence (output of one is input of another). I was wondering what a good way to do this would be?
For additional context it is basically a Photoshop layer system, or a substance designer node graph, each layer creates a texture and has filters that modify it, and has blending modes.
I believe it has something to do with https://docs.unity3d.com/ScriptReference/Graphics.CreateGraphicsFence.html but I don't know exactly the incantations to use it with a compute shader
Oooh, reading the description of the GraphicsFence sounds like what I want. Also apparently Unity already handles dependencies for GPU tasks...?
You don't need to use a graphics fence to synchronise a GPU task writing to a resource and another GPU task reading the resource. Unity handles these resource dependencies automatically.
I'm not really sure this stuff is kinda voodoo to me
Whenever I use a compute shader I'm kinda π¬ π¬ π€ that I won't have scheduling issues
All good, I appreciate the link!
Can you do a write up once you figure this magic out lol
yeah so sounds to me like if you did two Compute Shader Schedules, it would make them go in sequence automatically (assuming they depend on a shared buffer or something), but if you want to use the result of the shaders in CPU-land or someting you need a fence?
Haha yeah will do (if I ever figure it out at least π )
if their work can be parallelized, use cmd.CreateGraphicsFence with GraphicsFenceType.AsyncQueueSynchronisation. pass the returned GraphicsFence object to cmd.WaitOnAsyncGraphicsFence of the dependent graphics job. if their work cannot be parallelized, its better to model their work as void ApplyComputerShader1(CommandBuffer cmd) and ApplyComputerShader2, then submitting a command buffer with all the ordered calls as needed.
i would use what's in the docs because it's probably that the old ones are allowed to use the old syntax
Yeah as I was looking at it more, it was looking more like a CommandBuffer is what I would want. Thanks π
Do you know a good way to await the CommandBuffer?
Ahh looks like CommandBuffer.RequestAsyncReadback might be what I want
if you need the data back into the cpu yes
there are a lot of nuances though
the callback will occur on the main thread, but they don't tell you which player loop π«’
Thats fine, I plan on just awaiting a TaskCompletionSource and set the result of it in the callback.
is it essential that it be low latency? sometimes, due to this player loop issue, your results will be "a frame late"
the jobs api will have a way of expressing a dependency on an async graphics job aka a computer shader that will allow you to start work early in a frame and have it ready in time for rendering
if you know exactly which scene state you need for it
The less latency the better, but not really a big deal. I am moving a system from the CPU to the GPU, so we are dealing with 30 - 90 second delays right now haha
okay
probably premature lol
chatgpt gpt4 does an OK job on one-shot hlsl code. it will make logical mistakes but it will show the right syntax.
having just done this, there are a lot of pitfalls - everyone writes their matrices row major, for example, even though hlsl and glsl are column major, but write vector * matrix instead of matrix * vector, which makes it all work out in the end in the strict context of the shader
hi I was wondering if this was possible? my application creates a directory with saved scree captures of my project. I would like this folder to be synced with a dropbox directory and organize all the cpatures in there? Is it possible or has anyone done something where you connect dropbox api within unity
so that when it creates the folder it automatically syncs to the same dropbox directory
if there is not any existing solution, then just google
https://www.dropbox.com/developers/documentation/http/documentation
yeah I dont presume there is an existing solution and ive been reading docs just wondering if someone did anything remotely the same
ok it looks like I need to setup the http API i have no clue how to start doing this in unity
ive been scouring online too is there any SDK or something that supports this
Hello, does anyone know any reference code that works for computing the correct rotation and position of a parent gameobject, respective to a child's (an anchor), which I want to position on top of another connection anchor?
The quaternions and inverse transformations are getting me very confused, I thought I had a working implementation until I expanded my set of example prefabs. It'd be nice if I could tell if there is Gimbal lock happening or something alike
This is what I had that was working:
Quaternion anchorTargetRotation = _connectionAnchor.Transform.rotation;
Quaternion rotationCorrection = anchorTargetRotation * Quaternion.Inverse(connectionAnchor.Transform.localRotation);
instanceRoot.transform.rotation = rotationCorrection;
Vector3 anchoredPosition = Transform.TransformPoint(rootAnchor.Transform.InverseTransformPoint(rootWorldPosition));
instanceRoot.transform.position = anchoredPosition;
I've dealt with a similar situation by just creating some empty gameobjects and moving them around
In my case, I needed to figure out where to position a ragdoll's root so that one of its bones would have a certain position and rotation
Hey, thanks for the answer! Yes. I assumed that the position does not always correspond because the visual position of moving physics objects is not exactly their real physics position. In my case, i am using Physics.SyncTransforms() which sounds like it serves the purpose of syncing movement done in code to the physics engine.
CharacterController does execute OnTriggerEnter, OnTriggerStay and OnTriggerExit.
The problem i have is that the CharacterController is inside the Trigger Zone with a distance of X between their centers and then i move them both and next frame its OnTriggerExit with the distance being the exact same.
I do not know how to further eliminate factors. I tried different variations of Update, LateUpdate and FixedUpdate and each of them has different flaws. Moving an object in UpdateFixed and having a first person camera as its child leads to horrible visual stutter for example. I tried different physics refresh rates, from 60 fps when the games runs at 60 fps to 100fps for physics and more of less for frames, it doesn't make a difference, the effect is still the same.
Thank you for the info, I tried to do it more "cleanly" by just using maths. Turns out that original code is correct, what was failing was an anchor that I oriented wrongly
You can send HTTP requests with UnityWebRequest.
Again, there are still many unknown factors. Especially for someone that doesn't have access to your project/code.
While sync transform might've been useful I'm not sure if it has any effect in your case since you don't have any rigidbodies involved it seems. All moving objects need to have rigidbodies in order to comply with physics.
Perhaps try giving your platform an rb and moving it with MovePosition or something as well as replacing your character with a simple capsule collider with rb and OnTriggerEnter/Exit callbacks and see if you can reproduce the bug with that setup. Obviously, both rbs need to be kinematic if you want the parent-child relationship to control positions.
That being said, it might actually be contributing to the problem, as it implies that the child objects is moved outside of physics. So, if that doesn't work, might want to make the capsule rb dynamic and maybe use MovePosition for it as well.
hey guys i try to make a ability system so i did a list of abilitybehavior but i cant add different class that Inherit from abilitybehavior so i try to play with thee editor and make this so i can chose what type of abilitybehavior i can add but evrey time i change same scripts its return it back to abilitybehavior and not the class i add heere the code :
!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.
You need [SerializeReference] if you want to hold references to subclasses
You would add that attribute to the behaviours list
hooo ok ty ! you saved me
Can you recommend a tool or solution for managing dependencies for a large Open World project that may be ported to the latest consoles? One that will allow you to keep the architecture solid. I've tried Zenject, VContainer and Reflex, but I feel like I'm fighting Unity more than doing something simple by using them.
how many other people will be working on your thing? how many of those will be engineers? are artists going to put assets into the project directly, or a tech artist will do that? are you using git?
No architecture. Simply use Reference/GetComponent/Singleton/etc. I've done multiple project on multiple console and the way you architecture reference has no impact so ever. Usually, I centralize feature in a single class that is swapped at build time, not runtime. After, I have multiple singleton acting as manager that use this class in transparent manner. (Save, Achievement, Input)
Approximately 6 engineers, we are using Plastic SCM in most projects, and artists will be adding assets directly.
How do you manage scaling your solutions and keeping project organization without architecture?
is it okay that your game will take like 3 years to make?
you can sort of do anything with enough time. so it really depends on what your goals are
is there a pre-existing code base of a working game?
Most likely yes, plus future maintenance and ports to other consoles. I would like to make the right decision now so that I don't have to rewrite half of the codebase later, we are currently in the third month of production, and the code base is growing quickly.
I'm concerned about solutions like Zenject due to performance and future debugging on consoles due to AOT.
I meant, without using fancy architecture for the reference aspect of it. My bad, I should've specified it. Obviously, we have some sort of architecture such as UI, GameState, Sound, VFX, etc. However, we do not rely on dependency injection or any reflection base/code generation architecture because they are confusing, hard to debug and invasive. Fortunately enough, Unity has already an abundance of tool available such as Editor Serialization, ScriptableObject, GetComponent function, etc. Then, you have the Singleton pattern and the Service Registry pattern if needed. With all of that, you are more than able to always get the requiring reference where you need it.
In my opinion, dependency injection is great mechanism in Web development or other software development but does not have the same value in a Video Game. This is particularly due to the serialization nature of a game and the non-existent Unit-Test in a game. It is worth nothing that dependency injection solution favorize the creation of highly coupled class which is exactly what evangelist warn against the usage of Singleton. Also, in the optic that you are going to develop on multiple platform, dependency injection could be a massive irritant due to the fact it is important to control what reference is acquired and when it is acquired. By example, you would most likely use AssetBundle for low end platform. This is something that is not though of in most DI I've seen or it is overly complicated. You cannot just grab a reference, you need to load the AssetBundle before.
Decoupling code is extremely useful in videogames, bro
Yes, and dependency injection do the inverse.
how
People acquire reference to things they shouldve at place they shouldnt
You need to keep things enclosed as well
dependency injection is to just make A=>C<=B instead of A=>B
Sure, it creates a weak reference, it is still a reference
as opposed to?
At the end of the day, if you destroy A, C is not longer valid isnt ?
C would be a more long lived mediator
or at least coded as such
or just a generic point of contact for A and B
so B doesnβt need direct knowledge of the A it is tied to
itβs not rocket science
Not sure I understand, C would be an interface not a mediator.
mediator is maybe not the right name for it, since that has a more specific meaning. interface is more correct
interface, but not actually an interface
If you have A that inherits from C, if A is destroyed, then C is no longer valid. Making your reference invalid. When you work with singleton or service registry, it is obvious that does reference will never be in such states. The implicit contract in a singleton makes it clear of that.
but inheritance is not necessary for dependency injection
However, the principle issue I has with dependency injection (in the architecture side of things), is that it favorize the acquisition of reference through the wrong channel.
When you do not use interface, you do not have A=>C<=B
false
you can easily make C a class that takes in input/output using a class shared by anything trying to work with C
C can have input methods that take in D from B. And call actions that output maybe D or E, which is a format that A can use
like, I have a collision class that can take in collision data (in one format), and outputs a new struct with a processed form of that collision data, then calls an event action.
B can tell C to go in with incominthg collision data.
A can subscribe to Cβs events to know.
C knows it can cancel the request if no one is subscribed, but has no knowledge of B nor A.
We aren't talking about dependency inversion anymore and you are implying a whole set of pattern that has nothing with dependency injection and would not be enforce what so ever with that. What you have done would be the same as using an interface be more complicated. It has its advantage, but still end up as filling the role of an interface.
how is this not dependency injection? The alternative without C is to have B directly get a reference to A, and try to start calling methods.
B now depends on Cβs methods, as does A.
No, you could still have direct reference to C
Instead, you just have a reflection base/gerenation code tool gives you a reference to C.
everyone has a direct reference to C
The point of dependency injection tool is to fill that reference
Whatever C is, does not have anything to do with dependency injection
with the thing you put in the middle, which is C
I have similar feelings, @dusty wigeon but dependency Injection frameworks clashes with MonoBehaviour lifecycle here. However, by abandoning it and using singletons and locators, components 'ask' for references, instead of references beign provided to them, creating a tighter coupling.
No, you are the one that decide what you want.
C is not technically needed, as A could directly depend on B
Yes, and if you want to have better architecture you use C.
We agree
However, it has nothing to do with dependency injection
Dependency Injection is still an ask for a component.
At the end, you still gonna have a reference to the component. If you want flexibility in acquiring the reference, serializefield and scriptable object does more than that.
Also, you can use a reference on a more broad concept such as a player to retrieve a component that he owns.
This, wouldnt be possible in most web framework.
Hence, the usage of dependency injection is a good thing in my opinion in those scenario.
It seems to me that there is no silver bullet here, but what you're describing is probably the most natural in Unity and just straightforward.
anyway thank you guys for your point of view π
@sterile meteor, I do not accept any DMs.
oh, that's a pity, so thank you again here π
Is this like a multiplayer, 3rd or 1st person persistent world game like Rust? Or open world like a GTA style RPG?
It is more like Minecraft Dungeons with coop mode but in open world in listen server architecture.
are you using a pre-existing solution for multiplayer?
Yup, Netcode for GameObjects. I looked at the BossRoom sample architecture, but it seems a bit spaghetti there.
okay. my opinion is you're in a pretty good place. my experience is pretty limited, while i have worked with ~10 engineers on a game before, only 3 were ever touching the unity scene. in my opinion, all the dependency injection choices are bad for Unity. dependency injection generally is poorly suited for games, because all the stuff you spend the most time writing is tightly coupled anyway. the best thing you can do is to give ownership of the tightly coupled stuff to specific people. for example, the player controller, and therefore the way you architect movement in your scene, and therefore the multiplayer, must all be done by the same person
you can make this easier by using ECS, which if your game doesn't need 100% of all the latest rendering features, you will be able to decouple a lot of the networking from everything else.
ECS is "decoupled networking for gameplay." netcode for gameobjects is fine, but since ordinary, non-ECS networking is coupled to everything, you are, in disguise, forcing your game to be authored by 1 person, even though you have 6 π¬
that's why i say 3 years
"spaghetti" is just saying, "one person came and made a ton of changes to other people's stuff."
boss room was authored by at least 6 engineers over time.
it is true that fernando-cortez had to touch everything, but i don't think he authored the bulk of the sample
@sterile meteor https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/tree/v1.2.0-pre this version is closest to where you might get to
Big thanks for the response! I wonder why they changed their custom DIScope to the VContainer.
in a scriptable object how do you automatically create and manage assets when you create an SO ? I tried something like this :
private void Awake()
{
if(_meshTemplate == null)
_meshTemplate = LoadAsset<ThemeMeshTemplate>();
if(materialTemplate == null)
_materialTemplate = LoadAsset<ThemeMaterialTemplate>();
}
private T CreateAsset<T>() where T : ScriptableObject
{
Delete<T>();
var asset = ScriptableObject.CreateInstance<T>();
asset.name = typeof(T).ToString();
AssetDatabase.AddObjectToAsset(CreateInstance<T>(), this);
AssetDatabase.SaveAssets();
var path = AssetDatabase.GetAssetPath(this);
return AssetDatabase.LoadAssetAtPath<T>(path);
}
private T LoadAsset<T>() where T : ScriptableObject
{
var path = AssetDatabase.GetAssetPath(this);
var result = AssetDatabase.LoadAssetAtPath<T>(path);
if (result == null)
return CreateAsset<T>();
return result;
}
but it was causing the error Calls to "AssetDatabase.RemoveObjectFromAsset" are restricted during asset importing
same for AddObjectToAsset
if i use OnEnable i get an exception about some infinite import loop
so there does not seem to be an ideal method for doing it in a scriptable object
What's the best way to handle multiple external factors on a target script with a one way relationship:
Say I have a player controller which has a "CanJump" boolean, I would like this boolean to be the intersection of factors involved in other scripts such that CanJump = ScriptABoolean && ScriptBBoolean...
My issue is that I'd like to not reference these in the script which has CanJump but to append them in some way from scripts A and B. I know I can do this with a list and just change my get from CanJump to resolve this list, but wanted to check if there's a better approach than this solution
make it a property
public bool CanJump => ScriptABoolean && ScriptBBoolean;```
i think this is fine as long as the canjump is synchronized
Doesn't this require the main script to reference ScriptABoolean and ScriptBBoolean?
Doesn't it already? Maybe I don't understand your question.
I'd like to keep this a one way relationship where the main script (which holds CanJump) doesn't need to reference the other two
I'm using two in this example but it should be expandable to however many
The others will need to reference this one then.
yup, how can I append them to it nicely?
sorry if it's a dumb question but what do you mean by synchronized in this context?
when you update the scriptABool the canjump will be updated
bool allJumpTrue = true;
public bool CanJump => allJumpTrue;
public void ResetJump() {
allJumpTrue = true;
}
public void AppendJumpStatus(bool input) {
allJumpTrue &= input;
}```
something like this?
ooooooh didn't realise to use the &= operator
does that apply permanently or just for the current state of input?
no idea what you mean by this
permanently, so you have to reset jump
a = true, b = true
a &= b (a is still true?)
b = false (does a now equal false?)
nono, asking whether a does
I think I've misunderstood &= nevermind
if you don't do a = something; a will not change
&= is a=a&b
a &= b is just a = a & b;
yeah yeah
after assignment b will not change a anymore
so I need to call append after each adjustment of b for a to update properly
ta, that was my original q
well I was imagining that every frame this order of events would happen:
- You call ResetJump();
- A, B, C, D etc all call AppendJumpStatus()
- You use
CanJumpelsewhere in the script
actually i may have a semaphore approach but you need to know how many bool are here so you dont need to call ResetJump
yeah, this works completely fine, I was avoiding this type of approach as I wanted to aim for it to only adjust CanJump once one of the other values changes, since I wasn't sure if it'd be a bad idea to reset and call each append method every frame but I'm presuming the overhead is negligable?
public int ready;
public int number_of_bool;
public bool can_jump{return ready==number_of_bool;}
sadly I'd prefer to keep it dynamic since I'd like to use this approach for other things too and never know when I may have additional factors come into play
ahhh
I suppose if I kept a total that'd work fine
you need to keep the total number of bool, but it allows you update ready from anywhere
there's another option too if you want involving delegates
delegates are probably neater I'd imagine so i'd love to hear
do you pass in the child script's booleans as a parameter each to an append-like method you mentioned before?
so AppendJumpStatus(bool a) which is a method belonging to the main script
and have the other scripts add it to a delegate of AllAppends or something alike?
public HashSet<Func<bool>> jumpSources = new();
public void AddJumpSource(Func<bool> source) {
jumpSources.Add(source);
}
public void RemoveJumpSource(Func<bool> source) {
jumpSources.Remove(source);
}
public bool CanJump() {
bool canJump = true;
foreach (var source in jumpSources) {
canJump &= source();
}
return canJump;
}```
yeah then the other scripts A, B, C, etc call AddJumpSource to add themselves to the list
so for example in script A it might be:
bool IsReadyToJump() {
return fuel > 5;
}
void Awake() {
playerController.AddJumpSource(IsReadyToJump);
}```
ta for the help, this is pretty much exactly what I was aiming for
Last thing though, I don't know anything about HashSets so what's the advantage to doing that rather than
public delegate void BoolSources();
public BoolSources JumpSources;
or something like that?
obviously one less line and you don't have to define a delegate type but curious if anything else
You need a collection of them so you can evaluate each one by one. A list would work too but it's just less efficient than a HashSet for random removing of items.
defining your own delegate type would be fine
it would replace Func<bool> though
you still need a HashSet or List
why is it Func<bool> btw? Is it referring to a boolean function?
func is action but it has return type
Func<bool> means " a function that returns a bool"
it's equivalent to:
public delegate bool BoolSource();```
So you could do HashSet<BoolSource>(); here just the same
right
I'm still not super confident with delegate return types as of yet, I thought only the last delegate Invoked returned its value?
that's why I'm using a HashSet
ahh
that is true if you try to shove them all into one multicast delegate
instead I have a collection of many delegates
and am evaluating each one by one
yup yup makes sense
hang on I'll type up an alternative proposition if you'd care to give it a glance, I'm sure it'll be less efficient though
if it makes it easier to think about you can replace HashSet with List here and it will work the same
If the number of elements is small (less than 10 or 20) it probably won't make any noticeable performance difference either
oh wait nevermind I was in lala land
completely misinterpreted delegate parameters for some reason
Is there any reason why HashSet is more performant with higher elements?
sorry for the bombardment of questions btw, lmk if you're busy or whatnot
hashset is O(1) for add/remove but around O(1.4n) for iteration (suppose reallocated if 70% space is filled, maybe slower in real life)
list is O(n) for both add,remove,iteration
tyvm
I have a question. So I have been experimenting lately with the Netcode for gameobjects. I am stuck trying to make a player reset to his base position on map reset, any ideas how could this be done?
Like so when the map is reseted using the other network command, the players get teleported back to their base positions too.
are you working from one of unity's samples?
No.
hmm. what is your game? it should be pretty straightforward to set the player position
even if you just blubbed it
I thought there was a special netcode function for reseting Netobjects position tho.
i'm not sure if there is
this is simple enough that GPT4 can author it for you
What is a base position? I dont recall this being a thing stored when I used ngo. Anyways you can just call teleport on the network transform and it will not interpolate to wherever you put it
Base position is the position an object is on before the game is started- like the default
by now you could have written this script. it's very simple
Any idee how can I change player name in cloud code unity?
do you mean in the unity player accounts identity provider?
how do you preserve aspect ratio regardless of resolution (Unity 2022, URP)
Do you mean like adding black bar ?
Right under the "Game" tab, you have several dropdown menus, one of which allows you to set a fixed ratio
That wouldnt be set in the build though.
If it can be done through scripts, there's Screen.SetResolution
That would change the resolution.
You need to set the viewport of the camera.
To keep the same aspect ratio
Something like:
public Rect GetViewPortSize()
{
return GetViewPortSize(Screen.width, Screen.height, referenceSize.x, referenceSize.y);
}
private Rect GetViewPortSize(float screenWidth, float screenHeight, float referenceWidth, float referenceHeight)
{
float screenRatio = screenWidth / screenHeight;
float referenceRatio = referenceWidth / referenceHeight;
float scale = screenRatio / referenceRatio;
if (screenRatio > referenceRatio)
{
scale = 1 / scale;
return new Rect((1.0f - scale) / 2.0f, 0.0f, scale, 1.0f);
}
else
{
return new Rect(0, (1.0f - scale) / 2.0f, 1.0f, scale);
}
}
Yo im doing Custom Pool Managing now am i advanced enough yet?
Starting to study ECS
Hi, I am making a health bar system that make use of one canvas (screen space) and the canvas is a child object of a UI camera. I want the health bar to follow the enemy but I dont know why all the health bar is stuck in the middle of the screen. Here is my code:
private void Update()
{
if (objectToFollow != null)
{
Vector2 ViewportPosition = _camera.WorldToViewportPoint(objectToFollow.position);
Vector2 WorldObject_ScreenPosition = new Vector2(
((ViewportPosition.x * _myCanvas.sizeDelta.x) - (_myCanvas.sizeDelta.x * 0.5f)),
((ViewportPosition.y * _myCanvas.sizeDelta.y) - (_myCanvas.sizeDelta.y * 0.5f)));
_rectTransform.anchoredPosition = WorldObject_ScreenPosition;
}
}
_myCanvas is the RectTransform of the canvas. ObjectToFollow is the enemy transform. Is there any solution? Thank you.
anchored position is already in range 0-1
you can just pass the viewport position, maybe with flipping one axis
trying
not working, it doesnt move
can you explain more about " just pass the viewport position", my understanding is change the code like this
Vector2 ViewportPosition = _camera.WorldToViewportPoint(objectToFollow.position);
_rectTransform.anchoredPosition = ViewportPosition;
yes, already should produce results
because full screen canvas matches 0-1 to viewport
i may have confused anchoredPosition with anchors themselves
try anchorMin = vp; anchorMax = vp;
Move it to LateUpdate, so it will execute after Update of enemy movements. You can also try changing the script execution order, so UI will be executed always last.
tried. Still shaking
I used this as a starting point, and none of my HealthBars Shake !
https://www.youtube.com/watch?v=_lREXfAMUcE
The main difference between a Player's Health Bar in the HUD vs an Enemy's is creating the Health Bar in WORLD SPACE.
In stead of overlaying UI on the Camera, the Enemy or Game Object itself has a Canvas attached to it as a child object, and the UI is a part of the Enemy GameObject.
The benefit of this is the Health Bar follows the Enemy aroun...
its 2d diablo style too
I am in 3D
how do you make the health bar face the camera? transform.lookat?
just make sure its WORLD SPACE and make sure to have the bars face the cam
I have tried to use transform.lookat but it makes the health bar look bad (the frame is kind of broken in some angle, like its not completely round)
on HealthBarSCRIPT in UPDATE try ...
transform.rotatino = camera.transform.rotattion;
serialize camera variable, and drag cam ( inspector
You game looks sick ATM BTW, I love Diablo 3 and 2
yea, I tried before, the health bar frame will become kind of scratchy like this. So, I decide to swap to screen space
Thank you
if the healthbar is on canvas, you probably don't want to rotate it too much as it will "skew" the bar just like that
I think I've suggested it to you before, but using a screen position shader for this stuff cuts down a lot of work
yea. I asked yesterday and I have google it. But if I use the shader I cannot make a custom health bar, like adding the skeleton and adding the gold frame in this example.
Recently I needed to do something pretty common in many top-down games: render a whole bunch of health bars for enemies on the screen. Something like this:
Obviously, I want to do this as efficiently as possible, preferably all in a single draw call. As I always do before I start something, I did a quick search online of what other people are do...
After watching the video and the comment, I try changing the rotation of the canvas rather than the health bar and use world space canvas and it works.
Thank you everyone for helping
If you use LookAt to look at the camera, give it camera.transform.up as the up vector (second argument, optional).
Otherwise it will use world up vector which can look a bit off at some angles
good to know. Thank you.
That looks pretty good, but instead of the whole alignment thing they're doing you'd just convert the world position to screen space and you could do it all in compute.
π€
just some minor optimization since they're already doing a lot of work with the shader so might as well just do it all
yea, it looks good at performance. I am considering using it in "normal" monster, and use the world canvas in "elite" monster.
I'm glad you have fixed it! Do you have a reddit/youtube/other site? I would love to follow your progress!
not yet. The game is still on progress. Will make one once demo is made.
@ionic ivy Don't cross-post. Pick one channel
I want to run by a system to help my physics system keep things grounded along changing slopes. Looking for feedback:
- At start of fixed update, one script calls GetContacts on anything that can be grounded to learn current grounding state and slope normal it is on.
- Most scrips run to call velocity changes etc. These scripts also tell physics system if something should stick to ground (bool).
- End of fixed update, during custom physics simulation:
3a) Whenever we move something, if stickToGround, then change the vector for how we plan to move to be along the slope (using normal from part 1)
3b) Right before end of similation, for everything that can stick to ground, cast down to check for floor. If find floor, move down.
And assume anything that is ground cannot stick to ground.
Good plan? Bad plan?
Hi, I need some help.
So I have a 2D array of nodes (Node[,]). Let's call it "arr1"
I have another array. The array is of the same type (Node[,]). Let's call it "arr2"
I want to combine them into one large node.
Both arrays aren't jagged. Both arrays have unique elements, meaning that an element from arr1 won't appear in arr2 and vice versa.
Is there a way to do so without loosing too much performance?
You cannot do better than allocating a new array that has the same space of the two array combining then copying one element at a time.
I see
Your best option is to find an alternative to not have to do that.
Okay, thanks for your help
which version of Unity added delta compile in IL2CPP? 2020 seems to recompile entire project even on scene change.
If I replace a 100x100 tilemap with prefab tile gameobjects(10,000 spriterenders+colliders, no update() calls) how badly would it perform compared to a tilemap?
Going the prefab route makes some calculations easier for my mechanic. But I'm not sure how big the perf hit will be.
profile it, though the memory usage must be huge if you use 10000 gameobjects and the rendering cost
what is your game?
you might consider ECS
@undone coral
It's hard to explain. Basically, the player can move tilemap columns. Like columns 3...100 is moved to cols 1..98 . This requires repainting 80x100 tiles. If every tile was a prefab, I could just move the gameobjects. I'm not sure if that's faster. However, the ability to have monobehaviors on each prefab makes somethings easier.
I think ECS would be overkill for this. I also have the option of using multiple, smaller tilemaps as chunks of the map. That way, the repainting would be limited to current chunks and I would simply move the other chunks.
Sounds like you'd want to use a lookup table and change the vertices directly
Would changing vertices move colliders?
You'll have to update it afterwards
You would lose on the tilemap batching and culling performance optimization.
Have you profile the games on the targeted device ? Same if it seem inefficient, you might be correct. Also, note that moving 80x100 GameObject would also be considerable slow. However, your real lost would come from losing the batching that comes from a tilemap (and the ease of use of a tilemap).
Also, note that instead of moving column, you could offset all your time map and only modified 1 column or 2 if you want to cleanup the extra each time.
Ah I forgot I could offset the tiles. That would probably be faster.
I guess it comes down to how much is being rendered at the time too as spriterenders do actually batch quite well (with a sprite atlas at least), but if you're viewing whole tilemap it would probably be a problem.
I'd use 2 lists instead of 2 arrays, then you can push both lists into a NEW list ( combining both )
Is this what you're looking for?
hi all! I've got a small project (SerializableDictionary): I've got the project itself up on git hub, and on my own system, Iβve created a unitypackage with the project. But Iβm missing the last step in order to make the package installable from gitβ¦ anyone know where to find those docs? no luck in my searches.
what exactly is not working? You should just be able to click on that and copy the url like so:
When I punch in my git repository I get: "[Package Manager Window] Cannot perform upm operation: Unable to add package [https://github.com/glurth/SerializableDictionary]:
Package name 'https://github.com/glurth/SerializableDictionary' is invalid. [InvalidParameter]."
did you forget the .git at the end?
I just dont know what SHOULD be in that repository, should it be the package file I made, or the source project?
I dunno, I just copied the path from my browser... π
That's not exactly the right path
You need to click the green "Code" button and then copy that. or just add .git at the end. No matter though, I tried and there is still another bug
you need a package.json file in your git repo
should the package I created be in there? or just the source project
just the package
AH! ok, lemme tryu a new repo with that. thank you!
You can take a look at how one of my packages looks like:
https://github.com/Gruhlum/Basics
Coincidentally, that packages also includes a tool to create packages with one click
I see the folder I exported my package into contains ONLY the file" SerializableDictionary.unitypackage" will I need to geretae that package file manually or sothing?
wait.. now I'm confused.. this looks like it DOES contain the source code...not just the package
the unitypackage file is only necessary if you want to manually add the package. it is not necessary for adding a package via git
I am not 100% sure if the unitypackage can actually be installed via git. You might have to do a "regular" package
AH, ok cool. thats clear things up alot! so this package.json file appears tobe what I'm missing. not sure how to generate that.. do I do it manually?
(Imma try just modifying the one I found in your repo @fickle mango
it's a PITA, if you don't want to install my whole package, this is just the script for the package generation:
https://gdl.space/asoxotidiq.cs
ah, that's why you wrote it? cool, thanks again !
ye, there should be a tools button at the top once you add that script, generate it from there and drag your package scripts into the Runtime folder, or the Editor folder if they are Editor scripts.
ok! progress, but not quite there yet: do I need to open up the folder it creates in unity to create these files (and a bunch of other stuff I prolly DONT want) or, should I just copy over .meta files too (dunno if that actually works)?
@fickle mangoalso- cool tool!
yes you need the meta files as well
yes
not having much luck. Now it wants .meta file for files that don't even exist in my main project... (just in the package folder the tool created) What a nightmare this is! And no unity docs for this?
mhh ye I just tested it, these files need to have meta files as well. gimme a sec
Hey guys,
I had posted in #archived-code-general but wasn't sure whether it was better suited to here and didn't want to repeat text across channels
I've been having this problem for well over a week now and have yet to receive any advice on it, so it made me think to post in here just in case the people who frequent here would be able to better spot my problem.
Here is the link to the thread I made in general if anyone would be willing to take a look.
https://discord.com/channels/489222168727519232/1172973780633665556
what worked for me was dragging the generated folder into your Assets folder, then all the meta files will be generated -> push to git again and it should work now. I'm going to bed now.
alright. thanks fo the help bud.. mch further than I would have got without it! gnight @fickle mango
is there a way to add custom log types? For example: Debug.LogCustom("customized log")
not sure what you mean. do you mean you want it written to a seperate file? or to show up "different" in the console?
i'm writing a custom in-game console and wanted some error messages to display with stack trace and some not (or with even more customization). Currently I'm just subscribing to "logMessageReceived" event from "Application" and using a switch statement for handling different log types
neat! well, you cannot add to the Debug class itself, but you can certainly make your own Logging class to call Debug.Log in some ...particular... way. As far as different "types" of log, I assume you mean like normal, warning, error? As far I know, NO: there is is no way to add another type like that. However, you COULD prepend some kind of "logType" text when your custom class calls Debug.Log.. then when displaying the logs in-game, check for such text in the log message itself.
that's a great idea actually. I could define a phrase like "[no stack trace]" and look for in the "logString" to determine how it should be displayed. Thanks!
I can't figured out, tried a lot things. Used chatgpt, nothing works.
I just want a ball that bounce around between two walls left and right with a floor.
It's a 3d world, but the ball will move only in a 2d direction. The ball should move between those two walls and have always the same height unless it collides. The problem is that I can't freeze X or Z because the walls are not always placed in a X or Z direction.
If the ball can ignore the parents rotations (walls & floor) and keeps moving in the X direction, that would be also a solution for me.
Not sure if that is possible
#π»βcode-beginner or general at least. You'll need to include more details (in the right channel) like your code. What you are describing right now doesnt make a ton of sense like why this is parented in the first place
I understand, I moved it to the beginner channel
hey guys so i work on ability system when i can add alll type of thing and then create endless abilities do you think its good to Continue with this or is it a waste of time? its for my new game i working on
Real question, why would you decide to go with a custom implementation of behavior instead of relaying on the prefab/monobehavior ?
Because the game I'm building, i want to create monsters when the player can play as the monster and evrey monster can have cupule of ability and some have melee attack and range attack and to create system that work for melee and range its mess
It wasnt my question.
Why, instead of doing your own behavior system did you not use a prefab ?
A prefab already has the capacity of adding component.
I think because it's more convenient for me than going through every prefab and change, and the behavior act like mono but they are not i create new list of the behaviors so i can change stuff in real time
something like this
{
[SerializeReference] private List<AbilityBehaviour> _behaviours = new List<AbilityBehaviour>();
private HolderAbility _holder;
public void Init(List<AbilityBehaviour> behaviours ,HolderAbility holder )
{
_behaviours = new List<AbilityBehaviour>( behaviours);
_holder = holder;
OnStartAbilit();
}
private void Update()
{
ActiveAbility();
}
public void Destroy()
{
OnEndAbilit();
Destroy(gameObject);
}
public void OnStartAbilit()
{
foreach (AbilityBehaviour item in _behaviours)
{
item.OnStart(_holder,this);
}
}
public void ActiveAbility()
{
foreach (AbilityBehaviour item in _behaviours)
{
item.Active(_holder, this);
}
}
public void OnEndAbilit()
{
foreach (AbilityBehaviour item in _behaviours)
{
item.OnEnd(_holder, this);
}
}
Does not seem like a really convenient way of doing. You would not get the context of the prefabs when editing it, you would have to implement multiple behavior that are not necessary. You would not get to have Prefabs Variant. You would not get hierarchy division.
In my opinion, you are just rewriting the wheel and additing unnecessary additionnal step
the component im adding its mor like add force change transform add box colider in the time the attack do dmg and stuff like that
Everything can be done from a prefab.
ye i know but its in Play i need to add thos scripts anyway
its not for the before the game this in the game
i have prefab in i just give it Behaviour like range , force , new child
You are still able to add component on prefabs on play mode.
or active animation
i see
i think i know what you try to say
to add thos on the prefab and not form my editor
like this ?
Transform behavior should be its own component
no its not like transform its use to move with transform
Same for the force
why is that?
I mean, what is the difference between both ?
Why not use what you already have
At the very least, you should have a component to take on the responsability of moving.
its using the main transform to move
using transfrom.positon += new vector 3()
and the force to its just behavior to use to move
public class TransformMover {
public void Update()
{
transform.position += velocity * time;
}
}
If you need an Awake, a Start, an OnDisable or an OnEnable you do not have anything to do extra
If you have multiple variant you could do:
public abstract class Mover : MonoBehavior
{
...
}
public class TransformMover : Mover
{
public void Update()
{
transform.position += velocity * time;
}
}
public class ForceMover : Mover
{
public void Awake()
{
rigidbody.AddForce(...);
}
}
and if i want to move only in the start or in the end or chnage the rot to ?
In the mover
ye its doing the same i did
As I said, it is the same. You are reinventing the wheel
i have here something that call to start end and update on evrey behavior
public class HolderBehaviours : MonoBehaviour
{
[Space]
[HideInInspector]
[SerializeReference] public List<AbilityBehaviour> behaviours ;
private HolderAbility _holder;
public void Init(HolderAbility holder)
{
_holder = holder;
OnStartAbilit();
}
private void Update()
{
ActiveAbility();
}
public void Destroy()
{
OnEndAbilit();
Destroy(gameObject);
}
public GameObject InstantiateObj(GameObject obj, Vector3 startPos, Quaternion startRot, bool isChild)
{
GameObject prefab = Instantiate(obj, transform.position, transform.rotation, isChild ? transform : null);
prefab.transform.localPosition = startPos;
prefab.transform.localRotation = startRot;
return prefab;
}
public void OnStartAbilit()
{
foreach (AbilityBehaviour item in behaviours)
{
item.OnStart(_holder, this);
}
}
public void ActiveAbility()
{
foreach (AbilityBehaviour item in behaviours)
{
item.Active(_holder, this);
}
}
public void OnEndAbilit()
{
foreach (AbilityBehaviour item in behaviours)
{
item.OnEnd(_holder, this);
}
}
}
Yes, you did exactly what a component is.
i just dont want a lot of scripts on one prefab
You already have lots of script on 1 object.
And you know, you can use sub object to class them if you want.
Ability
- Movement
- Collider
- VFX
- SFX
- Animation
- etc.
ok
i dont see the different from what i did
i just use one mono and not for evrey one
The major difference is that you are essentially recreating what a MonoBehavior is. It has multiple impact:
- A new user most understand the system you have created
- Your system has more risk of not being robust
- Your system does not integrate as well as using component. Feature such as CustomEditor, Prefabs override, Nested Prefabs, Tag, Layer will not be part of your behavior.
Note that I'm not saying that it won't work.
Non-component behaviours is not a very complicated thing for the "user to understand"
I feel that. I don't think what you are doing is insane
Still, it is a step higher. When I am dealing with MonoBehavior I already knows what method works. If I want to use message broadcasting (animation, by example), UnityEvent, OnTriggerEvent, Awake, LateUpdate, I do not need to learn how it has been implemented.
its just feel so overload and tiring i try to create ability system with all kind of ways but every time i try to make different btw range and melee all my code became mess
but the component simple not different from mono
It is. I listed an extensive list of feature that would not be usuable.
and its for me to create an interface that i can easy create ability
ye but its not problem to add the OnTriggerEvent
Nothing remove you the ability to do that. You can still have "modifier", "condition", "effect" or whatever you want to call it. My issue is with the fact that you are replacing the concept of MonoBehavior with something that is less practical. And, again, as I said it, it is the essentially the same and will work.
Sure, however I will need to know that. If I used MonoBehavior I wouldnt need to have this overhead.
That being said, having move the actual data that deals with the world to a prefab is definitely better. This way you would be able to easily edit things such as collider/trigger, VFX, SFX, Animation, etc.
I'm still looking for a way to determine multiple points of contacts between two colliders, which is not tied to the timing of the physics update
specifically, I move red ball from old position to new position, and I want to get those 3 points of contact between the red and blue colliders. But GetContacts tells me what it was at start of the previous physics update (eg the 1 contact for the old position)
Can't use spherecast at all to, right?
.Cast methods all seem to return only 1 hit per collider
I'm in 2D, btw
Circlecast probably has it too
circlecastall may return all intersection points
doesn't actually say on the documents but I'm pretty sure spherecast does or maybe I'm thinking of another method
but it uses the physics2D library if that matters
it looks like CircleCastAll just retrieves hits for all colliders allong the path, as opposed to multiple hits per collider
I have an idea, but this might need some hammering out:
- Cast, get hits normally.
- For each hit that hits a CompositeCollider2D/PolygonCollider2D, then:
make a new ContactFilter2D that tries to ignore that contact normal. - Cast again. Check for double hits.
actually, normal filter does't work....
Could just fan out some rays even not the ideal solution
that... is going to be a problem
Raycasts are weirdly similar in cost to casting my whole box collider
Hello, I am building an asset store asset and I need to check if TextMeshPro is installed (for compatability with other versions). There doesn't seem to be a define symbol for it and the only thread I can find remains unanswered. Any ideas?
It appears back in 2018 Unity, there was a define called TMP_PRESENT but this does not exist in current versions.
if hashcodes are 32 bit integers, how does a hashset/dictionary not cost 2^32 bytes each, just to hold empty buckets?
How are you getting 2^32 bytes from 32 bit integers? A byte is 8 bits.
you mean you need an array of size 2^32 for the "buckets"?
A hashset doesn't reserve an empty bucket for every possible hash. That would just be a normal array. Typically there's one bucket reserved for each element in the set
it will modulo the total number of buckets, usually a prime number
but then how do you quickly access something by its hash? in O(1) time?
^ bucket index = hash % number of buckets
hello, does anyone know why this compiler error is here? This happened afterI pressed connect to unity cloud in the unity hub, I then disconnected it but its still showing this
I cant play the game or anything now because it just says theres a compiler error
What if compiler didnt liked the space in path C:\Users\dynam\Co-op Survival because it does not seems a bug that comes from your project
Im just tryna understand what changed it cuz ive had this project for like a year now
what should I do about the space to try and fix it
Copy the project into another folder and rename the new one without spaces. Open new one and try it
Also get rid of the "-" in path
is there any other way? the project is 77GB
Wow dude
Like install something for the post processing stack?
haha yeah
I dont think so man you should try the easiest thing before trying the hardest
ight fair enough
Do not forget to Regenerate the project files from Edit>Preferences>ExternalTools again in newly copied project
@regal olive im trying but i dont have the space to copy the project
Can you backup the project to an external drive, you do not need the Library folder
I hope SteveSmith solve your problem sir i have no idea then
im on a laptop unfortunately
Im sorry Im trying to follow your guys instructions i just have a bad situation lol
So you have no USB drives?
I dont have one big enough
The Library folder will be very large. How big is your Assets folder?
43 GB
do you have 43 gb space?
here ill just uninstall something real quick
Im deleting some old projects, hopefully that will clear enough space
okay so what should i copy over @upbeat path ? the whole project?
i have 128 GB space free now
No, just the assets folder
No, delete the Library folder
no, I would not tell you to do it if there was a danger of losing anything
okay π
so in my main project, deleting the library folder rn?
and I have the assets folder backed up
perfect. Now in the project folder delete all .csproj and .sln files
yes
did I say that? No I did not
okay sorry
I thought you had deleted the Library folder, I still see it
im deleting it now
sorry i had it backed up and i forgot to delete after
okay i have that deleted now
Now rename your project folder to remove the -
So the old name was Co-op Survival - Built-in, should i just rename it to something else, like the games name UndeadHorizon ?
CoOpSurvivalBuiltIN will do or you can just call it Fred, it's up to you
ok start Unity Hub, you will need to remove the old project name and Open->Add from Disk the new one
wdym
this error was just in the editor in playmode aswell
like it wouldnt let me go into playmode because of it
Open will take some time as it needs to rebuild the Library folder
Even so, you should not have been able to enter play mode if you had compilation errors
Alright π , yeah it didnt let me enter playmode earlier sorry i phrased that weird
Always fix compilation errors before you do anything else, not doing so can cause problems
okay
getting there..
@upbeat path its probably going to take another 15-20 mins i think
I would expect so, at least. But once you clear your compilation errors you should be good to go
Oh, dont forget to change the Product name in ProjectSettings->Player if needed
okay π
@upbeat path
i just opened a scene i had, i havent edited anything but it looks like untiy isnt importing the scripts properly
Not it's not, it looks like it's generating an invalid .csproj file
is this HDRP or URP?
Standard
In the Package Manager remove and re install the Post processing stack
okay i did that
if you're not using post processing just remove it
im pretty sure im using it
i uninstalled and then reinstalled it
Regenerate project files
where do i do that
Project Settings->External Tools
Sorry, Preferences->External Tools
This is pretty much what it's complaining about it seems
yeah, delete it
why is it being used as a file name?
wow, where did that come from?
compiler error is cleared
awesome my project is back to normal
thanks a lot @upbeat path I really appreciate it
is there anything I can do for you for helping me out?
yes, implement and use version control on your projects
Should I use git?
yes
yes
π
Also get yourself some external drives so you don't run out of disk space
okay
real quick one last thing
I dont know if you can see it but that particle trail
It looks like the color changed from before
do you think theres some post processing stuff messed up or nah
no idea, not my area of expertise
okay nevermind this is a simple little thing ill mess with it
thanks again, ill get Git working with my project ASAP
perfect, enjoy the rest of your evening, I'm off to bed
you have a great evening aswell!
Anyone that has any knowledge about how to use Cloud Code with Multiplay (help):
#archived-unity-gaming-services message
I know there's an #βοΈβeditor-extensions channel but I'm not sure if this necessarily fits... I'm generating some GameObjects with a script and running SaveAssets after, but I've noticed that specifically after adding some code that manipulates RuntimeAnimatorControllers, every time I "regenerate" my scripts, I get some odd errors interacting with the generated objects until I manually recompile the main component I'm editing
I guess my question is that I know there are some SetDirty and other interactions when editing/manipulating gameobjects with editor code...
Is there something more I need to do with a GameObject I've generated with an editor script in order to correctly "update" its variables when interacting with a RuntimeAnimatorController?
Run Set dirty on any object you Touch and then do a save on the AssetDatabase
@olive cipher do you SetDirty before editing or just right before saving the assets, or does it matter?
SetDirty Marks an object as "I need to be saved"
So right before saving
you can declare your own in an asmdef
hashmaps and hashsets are O(hash collision chance * number of elements / capacity). if you are putting something that does not have a good hash function into your hashset or hashmap, you will get a lot of collisions and the hashmap will have to iterate through a lot of elements to find your item.
it is a misconception that they are "O(1)"
you're going to be reinventing ECS to solve problems if you are observing any performance issues. if you do not hav eperformance issues, that's great
true, but when people say O(1), they mean itβs not really supposed to depend on the size of the hashtable
and it theoretically should not. the overhead is supposed to be the cost for quickly knowing exactly where in memory you are supposed to go (in theory)
amortized O(1) just like List.Add
when you add some elements until the list capacity becomes n=2^k, the time needed for each insert is n/(4+8+16+...+2^(k-1))=n/(2^k-1-1-2)=2^k/(2^k-4)=1 when lim k->infinity
(if the current capacity is 8, an array of length 4 is copyed, 16->8+4 (previous copy), 32->16+8+4....)
i don't know what issue you were reporting in the chat, but often people shove Vector3s into dictionaries and hashsets and get surprisingly poor performance.
it's not about the capacity alone. it's exactly what i showed in that expression
hash collision chances can be very high for many kinds of game data storage
yes, it would be amortized O(1). not trur O(1)
idk why c# list's capacity start from 4 btw, i feel it is quite small
that could be caused by a shitty hash function
many lists are small, and if you didnβt ask for a lot of data π€·ββοΈ
it's more complicated than that. there's no universal hashing function that is also fast. it is very case by case if you are affected by vector3's hash function or whatever
you can read it and reason about it carefully
Luckily the initial size can be set in parameter.
i don't know what you are trying to do specifically
you donβt need a universal hash, but you need your hash to be not dumb
given your dataβs structue
like if you have a hashset of Vector3, but all the z values are 0, your hash function is probably going to give you a lot more collisions
you should consider using ECS if you need something sophisticated in terms of performance or control, especially if you are trying to author performance sensitive CPU code
you can also use burst and native collections
I think a small initial capacity for lists is neat if you want to create an array of lists and you're not sure which lists are going to be populated the most.
if you dont like the initial capacity, change it, it's a parameter in the constructor
what is the best way to handle collections for using non-allocating methods?
like when ray casting, results get populated into an array or list.
is it best to go for List vs array, and static vs non-static?
List vs Array- not MUCH diff there.. however SOME of these functions that populate collections allow you to pass IN the collection to be populated. This is advantageous because it help with GarbageCollection, like this guy: https://docs.unity3d.com/ScriptReference/Physics.RaycastNonAlloc.html (not sure if this ACTUALLY answered your Q)
I should probably start swapping my stuff to NonAlloc
mostly focus on methods that get called a lot, and would thus create lots of garbage
I'd check the profiller first.. if it's spending alot of time on garbage collection then yeah, worth a shot! if it's minimal impact, might not be needed.
Really should just be the default behavior considering how much these methods are usually used
Impressive, you are working on networked FPS shooter?
Can someone assist me with this wheelcollider issue?
https://i.gyazo.com/eaabdfd7c121f5131e73fd2e3d8d3456.gif
Hey guys. I'm creating a DB using Sqlite and I'm trying to delete the database. File.Exists returns false even though I'm 100% sure the file exists at that location and I'm 99% sure the permissions are fine.
Does anyone know what might be up?
Path concatenation should be done with Path.Combine() instead of string concatenation!
Ok ill give that a go but i dont see how that could change the outcome, if the string im logging is identical and if i paste it into finder it goes there to that file
I'll see what happens
Just code safety and IO standards. So you don't end up with a // or no directory separator at all, if you change one of these contstants
Ok ill change that thanks for the tip
What's the best way to go about storing a string with an int? Right now I have a list of strings and I want to associate an int with each.. I could do a list of ints and each time just get the correct index , I could do a multidimentinal array , maybe a dictionary that'll have a string , int or a scriptable object... I'm also thinking of ease off data entry as I will have 40,000+ entries.. maybe a json with string , int and convert to dictionary?
Any constructive thoughts/help is appreciated
what is the relation between string and int? dictionary would imply the string is a key and the int is the value. By what you described, I think you just want
class StringAndInt
{
public string a;
public int b;
}
Struct would be easy and take json data .... i have an example of this in another project actually , and i made it load data from firebase into a struct for a while .
Thank you
Yeah that's why i asked.. i know a dictionary uses one value to get the other ( in my case it would be like use the string to get the int )
Dictionary <stringοΌint>
@fresh salmon I got one more related question for you
Do you know why, in this case, the "Database.DB_PATH_PREFIX" does not get added to the path?
Doesn't seem like a valid path to me. = and : might be invalid path characters
It works before I changed to "combine"
It's to connect to a sqlite db
Oh.. maybe i dont use path combine then
LMAO
Yeah Combine checks the paths you feed to it
Path.GetInvalidPathChars() will give you the list of chars that are invalid for the current platform
Itneresting ok, but it works when it's just a string.
Yes because Combine checks the paths you feed to it
If it contains invalid characters, pretty sure it's ignored, or you get an exception
But if they're invalid, why would they work when it's just a string
is what I don't understand.
Because string concatenation does not use Combine???
Therefore the strings are not checked for invalid path characters
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=netstandard-2.1
If the one of the subsequent paths is an absolute path, then the combine operation resets starting with that absolute path, discarding all previous combined paths.
Application.persistentDataPath returns an absolute path. so that's where the returned string starts
I figured out my issue
and i will also look into that thanks for the link
thanks guys
yep itβs a online co op survival game
you should use the edy's vehicle physics free package, and use one of his templates to set up your car
I'm making a custom C++ game engine, and I'd like to do something similar to what Unity does by auto-serializing public members of MonoBehavior classes, which subsequently allows for the member to be drawn in the editor.
My question is: how does Unity actually do this auto-detection? It seems like this feature is closely tied to reflection, but at least with the C++ reflection libraries that I've looked at, it seems that you have to manually "register" your members for iteration later on.
How does Unity do this without the user of the class having to do any manual registration?
I've researched C++ reflection libraries, specifically RTTR and Meta. Both of them require manual registration of class data members.
Unity uses reflection, full stop. C# happens to have a virtual machine with a fully fleshed out type system running the show. C++ doesn't have this. The metadata about function names and such simply doesn't exist in the compiled binary by default. So you're at a huge disadvantage if you want to do things the Unity way.
I recommend just abandoning "the unity way". Anyway this isn't really a Unity related question...
Thank you.
Also the reason unreal uses the UPROPERTY macro
I would give it a shot to go through their source, as its open source, maybe you can find what you want
TechGeek on the Unity Developer Community discord worked on Unreal and develops engines, you may want to ask in that server for suggestions
I know they're working on something wild right now
That's a good tip, thanks. If it can be done with a macro that's a pretty close second. I just don't want to force the user to type this ugly statement every time
RTTR_REGISTRATION
{
registration::class_<MyStruct>("MyStruct")
.constructor<>()
.property("data", &MyStruct::data)
.method("func", &MyStruct::func);
}
Anyways, I'll stop posting on here now since it's no longer Unity related.
Thank you as well. How do I find this server?
I don't think I can share it here, but searching that name should bring it up.
It's the second biggest unity discord afaik
Dm'd you an invite
Thank you both.
For those who knows about the Probuilder API, is there a way to change the UV scale automatically on creating a mesh?
#π οΈβprobuilder may be better.
you can use Boost.Hana (https://www.boost.org/doc/libs/1_76_0/libs/hana/doc/html/index.html) instead of your own macros, or CppReflect
What is your structure? I develop one too and I'm stuck. I don't know when initialize server and matchmaker because I hav lobby and game scene and both require network functionalities
Hey people, so DOSember is coming up fast. It's an event where poeple play old DOS games on Twitch during the month of December. I'd like to build a virtual room with a computer that I could play the games on in Unity. The site Good Old Games has a tone of old DOS games on sale and they mostly use DOSbox to emulate them. I know that you can run emulators through Unity but I'm not sure how. Any advice would be appreciated.
Welcome to Arcade Paradise, the 90βs-fuelled retro arcade adventure. Rather than washing rags for a living, you decide to turn the family laundromat into the ultimate arcade. Play, profit, and purchase new arcade machines, with over 35 to choose from, to build your very own Arcade Paradise!Take the laundromat business made up of dull chores from...
$19.99
798
Hi all, I've seen 3 different ways to do event handlers..
Make the event a ScriptableObject and drag and drop it on the Listeners/Callers,
Make it a static class and subscribe/call that
Make a Singleton to handle all the events
Is there a consensus on which one is the better approach? or is there one I'm missing which is better?
"event handler" is pretty vague. The three things you listed there are just a few possibilities and not at all exhaustive.
There is no consensus "best" way to do event handling. It depends on your individual project and its needs
yeah sorry, I mean like OnEnemyDie, OnTakeDamage, etc.
I've just been throwing event Action<T> on my GM, but it seems messy as the project grows.
These look like events that should go on the particular enemy and/or entity taking damage
If you need them to be "global" you can make them static
there's no good reason to put all your static events in one class
there are plenty of ways to go about it, but general idea is to create a middleman between subscribers and dispatchers
yes a global event bus / central dispatcher is an approach as well
This would involve making topics as data basically - e.g. eventBus.Subscribe("enemy-death", listener);, eventBus.Publish("enemy-death", params); as a quick dirty example
yeah, this is something like what I'm looking for. Thanks!
Anyone have any idea...how a Capsule Collider's bounds, can move away from where the collider actually is?
The bounds is AABB ?
Not exactly sure what you mean by move away
shouldn't
What are you seeing that makes you say/think that?
Gizmos.DrawCube(bounds0.center, bounds0.size);
During runtime it's gradually going further down.
The Gizmo is...yet the GameObject and the Collider are not moving.
where is that gizmo coming from
oh sorry I see it
where did bounds0 come from?
Bounds bounds0 = GetComponent<CapsuleCollider>().bounds;
Does your capsule has a rigidbody ?
Yes
can you show the inspector for this object?
Do you do something with it ?
the full inspector
No.
Sorry was in Debug mode when I grabbed that shot. Dunno if that matters.
Other than collision detection.
show the full inspector
including the top bit
and any other components
also try disabling some things like the animator
Oh and you might want to add the transform.position of the object
The bounds are in local space arent they ?
you've got Animator, NavmeshAgent, and Rigidbody all on this thing - those things will often conflict
for a Mesh, yes
not for COllider
Unfortunately I can't due to NDA...names of some of the components (scripts) prevent me from showing.
Oh I see
well is the object marked as static?
No
Looks like it's the Nav Mesh Agent causing it. π
Or if I Freeze Position on the Rigidbody's Y axis it also stops "sinking".
right because it's just falling
Okay. So I'll have to add/remove the RB based on whether or not it's a player controlled (does or doesn't have Nav Agent) version of the GameObject.
Since it's not happening on the player controlled prefabs that have a RB but no NMA.
making it kinematic should also work
How can I profile a shader so that I know which instructions are taking so much time? I made a custom terrain shader and is taking around 6ms to run (which doesn't make much sense since it's quite simple)
You'd need to use a native measurement tool for that. Your target platform should provide one.
You'll also probably want to make sure shader debug symbols are being generated if you want to get as much info as possible. Defining the environment variable UNITYSHADERCACHE with a value of a folder location to put the debug symbols will force them to be generated, iirc.
Problem About Adding Modifiers
How can i sort/filter a dropdown list options?
What kind of dropdown?
Based on a list or array, reorder/filter the the list/array like you always would.
Child objects? Reindex the children
The textmeshpro dropdown ( ui ).. based on a list .. i try not using arrays
"i try not using arrays"
?? okaaaay. Odd.
But anyways, reorder the list. You can have two lists, one for all items, one for shown items
here is where I serach th list after its added to the options
// Iterate over each string in the itemList
for (int i = 0; i < itemList.Count; i++)
{
// Check if the current item in the itemList contains the searchText (case-insensitive)
if (itemList[i].ToLower().Contains(searchText.ToLower()))
{
Debug.Log($"{searchText} Exists in {itemList[i]}");
}
else
{
Debug.Log($"{searchText} Does Not Exist in {itemList[i]}");
}
}
Ok, so you look to be mostly there for what you need
I thought about searching the list then only add whats being searched
why not just using a hashset then you dont need to iterate the list
oh i misunderstand
you must iterate the list since you cant simply store all substrings
you may conside using Trie if you really want to store the substring and search it efficiently
When I call GetValue() it returns the basevalues. Not the modifiers added.
Hey, I have a question about UniTask, or more generally timesplicing -
I'm working on a project (2021.3 LTS) which has a bunch of separate async UniTasks being started while loading the game. They are started in different places from different objects and are doing a lot of work with Unity objects so likely need to stay on the main thread, collectively exceeding 1000-2000ms a frame. Since each task doesn't know about what other tasks are currently executing in a given frame, throwing in various await UniTask.Yield() seems a bit cluttered and random
My goal is that I can centrally stop continuing all tasks if, say, more than 50ms has elapsed since the last frame, and defer those continuations until the next frame. Anyone have insight on if this is possible & how to go about it, or if this is approaching it the wrong way?
Depends on what's actually in each task
But a simple way is to just check Time.realtimeSinceStartup - Time.time.
a few things but it largely follows a similar pattern: 1. load a text file, 2. parse the text file for various strings & data, 3. create objects for each line, populate fields on those objects, create child objects, etc, and finally 4. some additional processing/interaction between the objects
Have you profiled it to see what's taking most of the time, the reading + parsing part or the object setup?
Because if reading and parsing are the bottleneck, they can be offloaded to a separate thread.
it's mainly in the parsing of text and allocation of objects, so could probably move some of the parsing to a background thread
but each step individually already exceeds an acceptable frame time, hence looking for a central solution
I have something along the lines of this https://hatebin.com/wfbccfyuqa pseudocode, though this would need to be included in every task individually, I'm not sure if there's a way to make UniTask behave like this for all tasks running
That's basically what you have to do for work that must happen on main thread and they are exceeding your frame budget.
Move as much work as possible to background threads so they don't hang your main thread.
(Keep in mind moving work to background threads doesn't speed things up, if reading a file takes 100ms it will still take 100ms, it just won't freeze your game in the mean time)
yeah, it's just to keep responsiveness in the loading animations
Yeah just extract that while into a utility function and insert it everywhere, don't think there's any better way.
There's no auto magical splitting your code, because that's just not possible.
can someone take a look at my thread
drop me a link
You could "register" each UniTask you launch with a custom class that will make note of their start times. This class can have it's own aync process that, checks these times to see if any have exceeded some maxRunTime, and/or if they have been completed, and should be de-registered. You could even wrap UniTask in custom class that will do this registration automatically when a task is created, launched.
I have a hitbox system which currently uses OnTriggerStay to detect hits and requires their attached script to determine whether they're active or not if they can hit stuff but was curious if anyone's done any implementations before which don't require each hitbox to be a separate gameobject per actor, whether it's because it uses pooling, instantiation (which I presume isn't a good choice) or overlapspheres.
I'm asking this as it'd be nice to just be able to say to any actor use x hitbox from a large library rather than having to have the desired ones each be setup as their own gameobjects per character
Sounds like you just want to cast yourself instead of using the unity collider methods, is that right? Overlapshere isn't gameobject dependent and you can pretty much cast them via a manager/singleton GO if you wanted to.
Yeah, as I've made sure all colliders right now are just sphere colliders I was thinking it'd work fairly well and all my hitbox data is SO based so it would be pretty feasible
You get more control over casting yourself anyway, but usually you do want them in your fixed update.
I'm presuming coroutines to time how long a HB is active for isn't a good idea though if it's going to happen constantly, would keeping track of my own timers within update (or fixed update) per hitbox be better? or would the difference be negligable?
something I never checked but presuming is the case is that the OnTrigger methods are in sync with fixed update? but yeah i'd def need to tie it to that
No too sure about the absolute accuracy of coroutines waking, so that's something I'd say test to get an idea.
ah accuracy wasn't my main concern but good point, I was more thinking about performance as I've heard they aren't super performant in larger quantities as they produce lots of waste? I'm not very knowledgeable on it so forgive me if that's complete rubbish
I use them quite a lot for minor timer systems like character buffs/debuffs which I've also created similar systems by instead polling them through a single update system. I can't say I noticed much of a difference testing with about 2000+ coroutines running at the same time compared to polling. There's probably some optimization unity does under the hood for coroutines for when they are awaiting, but I'm not entirely sure. Maybe someone else has more insight for that ;p
ahhhh, I've never used anywhere near that many before but glad to know it's a possibility to consider. I usually use them rather sparingly and currently only use them for Iframes and hitbox lingering as far as i remember
Coroutines for the most part are single-threaded, and they do probably have some overhead compared to polling them yourself through a single system, so it comes down to if awaiting does reduce the amount of polling each coroutine does per update I'd presume.
sry dumb question but is polling referring to reducing a timer by the time delta each frame/fixedupdate?
polling meaning that you're checking if the routine is sleeping or not per update
ahh right right
Polling IN GENERAL just means checking every frame.
You could be checking anything. The value of a bool. The distance between objects. If an int is greater than another int
Just to add some more clarity
yeah so it'd only be polling for the duration of a hitbox, ta for the explanation
i'll do a little digging on coroutine performance for my case then, but presuming it's going to be insanely negligable as i doubt i'll have more than 20 hitboxes active at once ever
Anyone know of a tutorial or detailed explanation anywhere out there for the Package Manager, that will help me to use it in the way described in the image?
I don't want to go the .dll route, because I'll be sharing more than just scripts between the two projects.
I also can't use the folder junction route, because I'm going to have this up on Plastic for collaboration and version control.
Excuse me, do any of you know how to make record and share clip feature in game?
I want to make a feature so player coukd record a short clip of their gameplay and share it through
either download it
This typically isn't done in game. It's usually done on the hardware the game is played on.
So there's no API where unity could do it?
You could probably find a 3rd party API that does it.
Or try to make it yourself, but as stated it is not something you usually do in the game itself.
Okay thank you so much
Can anybody help me on this, i tried to screenshot in editor using this code, but each time i took another screenshot, somehow it shows the previous picture, not the new one:
void Start()
{
// Ensure the recording folder exists
System.IO.Directory.CreateDirectory(photoFolder);
screenshotPanel = screenshotImage.gameObject.transform.parent.gameObject;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && ableToSS && PauseHandler.ableToPause && !PauseHandler.isPaused)
{
string screenshotPath = Screenshoot();
StartCoroutine(DisplayScreenshot(screenshotPath));
}
}
public string Screenshoot()
{
string screenshotPath = photoFolder + "/screenshot.png";
ScreenCapture.CaptureScreenshot(screenshotPath);
return screenshotPath;
}
IEnumerator LoadTextureAsync(string imagePath)
{
// Load the screenshot into a Texture2D asynchronously
byte[] fileData = System.IO.File.ReadAllBytes(imagePath);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(fileData);
// Wait until the texture is fully loaded
while (!texture.isReadable)
{
yield return null;
}
// Assign the Texture2D to the UI Image component
screenshotImage.sprite = null;
screenshotImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
Debug.Log("Texture loaded successfully");
}
Is the image being overwritten in the directory?
yes
what happens in the DisplayScreenshot() coroutine?
IEnumerator DisplayScreenshot(string imagePath)
{
ableToSS = false;
Time.timeScale = 0f;
Debug.Log("DisplayScreenshot coroutine started");
// Load the screenshot into a Texture2D asynchronously
yield return LoadTextureAsync(imagePath);
screenshotPanel.gameObject.SetActive(true);
screenshotPanel.transform.localScale = new Vector3(0, 0, 0);
screenshotPanel.transform.DOScale(new Vector3(1, 1, 1), 1f).SetEase(Ease.OutBack).SetUpdate(true);
Debug.Log("DisplayScreenshot coroutine finished");
}
public void ExitScreenshot()
{
screenshotPanel.transform.DOScale(0, .3f).SetEase(Ease.InBack).SetUpdate(true).OnComplete(() => {
screenshotPanel.gameObject.SetActive(false);
PauseHandler.ableToPause = true;
Time.timeScale = 1f;
ableToSS = true;
});
}
}
Are you calling ExitScreenshot() at all in between SS?
not its for a button
It's changing the timescale to 0 which is interesting
the button supposed to show afte Dsiplay
so when in Play Mode and i pressed space, i want the game to pause. Thats why i made it to timescale 0
Ah, I see
even though i removed the scale, it doesnt matter
it still shows the previoue picture
not the new one, even if i take another picture it stills the same
in the directory folder the file is succesfully ovewrite, but somehow when in display it didnt show the same? i dont know if its delayed or not
Well, you have it working async, so make sure the coroutine is resolving completely
so ive tried to not use coroutine, its even funnier, it just keep taking picture for small period of time. Somehow its delayed and not synced with the input from keyboard. I already made a flag for this
`byte[] fileData = System.IO.File.ReadAllBytes(imagePath);`
did you author this, or a chatbot?
this isn't how you load textures in unity from the file system
you're not showing the DisplayScreenshot function, nor whreLoadTextureAsync is called
ChatGPT GPT4 does indeed give the wrong answer if you phrase the issue the way you did
also, what exactly is your goal @mellow sail ? there are better ways to get an image that represents the last rendered frame.
Could you show me the correct way? Actually i already solved it . I still uses the same script but the reason it didnt work out well because it seems after i called Screenshot(), it still try to write the file in the directory but i already called the DisplayScreenshot(). I solve it by adding a yield return new waitforsecods to wait the image to save in the destined path
i first need to know how much of this you authored versus the chatbot so i can get a sense for how much you comprehend what is going on
Most of it, except the load part
okay
it's from a tutorial, "how to take a screenshot in Unity"
Yup
For debug perpose and for a presentation on how i achieve screeshot feature that could be save to directory. The real target was to capture in build version not editor, but since i havent found the way for that, this is the closest to achive. Its for demonstatrion purpose in my college
The screeshot is a gameplay that player could somehow share one day from the game itself
okay
pretty sure your while (!texture.isReadable) is wrong. You can use https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html instead to load the texture and you can yield that properly
well i guess you'd have to know. there's no way chatgpt can go directly from your simple ask to the correct API call. tough cookie. https://chat.openai.com/share/9f14afe2-49c4-41ba-975c-3d61761d4a71
it does math on words. you can use it to help overcome a parade of tedious obstacles. you can't use it to query documentation that it wasn't trained on, like the unity docs.
the answer it gives in the chat isn't even 100% correct, because it doesn't understand static IEnumerators apparently
by the way, if you're turning this in as an assignment, i can tell you now, everybody recognizes ChatGPT's commenting style
record a clip is also a different problem. there are actually al lot of APIs for this, such as the ones that are built into iOS that unity exposes.
that are far and away the best approach
I see, its not for an assignment. I just wanted to share the abilty and brute force my way out using AI hahaha π . I realized its not the best way, but it really does confuse me. Thank you for the help
Yes it seem, i havent refactored my code yet. Im going to read it after this
if you are loading from file you can just use this:
unless you are using an old hdd or taking huge screenshots it will be instant
i think the most important thing is to start reading stuff 10x faster than you do today lol
hi. anyone knows how to redirect all unity Debug logs to console in Linux? (not headless. normal windowed build)
i've used this but it doesn't work
public static class RedirectToStdout
{
#if LOG_STDOUT
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
private static void StartRedirectToStdout()
{
Application.logMessageReceived += Application_logMessageReceived;
Application.logMessageReceivedThreaded += Application_logMessageReceived;
}
#endif
private static void Application_logMessageReceived(string condition, string stackTrace, LogType type)
{
switch (type)
{
case LogType.Error:
case LogType.Assert:
case LogType.Exception:
using (new ConsoleForegroundColor(System.ConsoleColor.Red))
Console.WriteLine($"{condition}\n{stackTrace}");
break;
case LogType.Warning:
using (new ConsoleForegroundColor(System.ConsoleColor.Yellow))
Console.WriteLine($"{condition}\n{stackTrace}");
break;
case LogType.Log:
Console.WriteLine($"{condition}\n{stackTrace}");
break;
}
}
}```
(ignore the using lines)
Check the -logFile <pathname> command line parameter here https://docs.unity3d.com/Manual/EditorCommandLineArguments.html
that saves to a file, not stdout
In linux stdout has a file handle
isn't it &1 or something
ah, interesting
thanks . that's a good lead, will look it up
ok didn't find the stdout file handle (was above my grade), but I found out in Linux there's tail -f command, so
myUnityGame -logFile ~/log | tail -f ~/log (be sure to touch ~/log for the first run)
well yeah that's the roundabout way
on linux you can do myUnityGame and it will log to the console, no? otherwise you can try myUnityGame -logFile -. - is interpreted by unity on macOS and Linux as attached console. however, this will only be the case if you start the application from a terminal (i.e., the application must have a tty attached)
does this make sense?
if you double click on the game in Ubuntu, i'm not sure if it attaches a tty to the process it does not attach a tty, so -logFile - would be meaningless, i.e. standard out doesn't go anywhere
i don't think this does what you think it does, but it will work*
./myUnityGame -logFile - is what you should use
absolutely! thank you. this is much simpler than the previous method
I still don't understand why Console.WriteLine doesn't work though. that's odd (building with mono)
it just don't. you can use microsoft logging and create a handler that translates microsoft logging to unity logging.
oh im not trying to convert Console logs to Debug logs, I was trying the oppose actually, to get the Debug logs to show up in console (a failed attempt. code's here:#archived-code-advanced message )
but well, that doesn't matter now anyway, because -logFile - works fine
hi, i have a very unique problem which i don't understand why it happens, i have two scenes login and game scene which the player go back and forth between them
i have a list which i add items to in game scene, it works fine when i login and open game scene and add items to that list
but when i go back to the previous scene and open game scene again it duplicated the atem in the list, it adds to it twice
Sounds like you have data persisting between scenes, due either to static variables or DDOL objects
i think it has some proble with loading scene or the scene is loaded twice
When you use such things, you are responsible for managing your data yourself
look the list is empty when i load it but when i add items to it, it add to it twice
then you're adding twice
without further details I'm not sure what else you want me to say
You have some state hanging over from a previous scene
either a static variable, a DDOL object, an event subscription you never unsubscribed from, etc..
as mentioned already
i start the game for the first time, i go to game scene and add item to the list it only adds one ( no duplicates ) then i go back to login and open game scene again, it adds duplicate
You said that already
And I already told you what the problem is.
Without seeing your code etc. it's not possible to be more specific