#archived-code-advanced
1 messages ยท Page 42 of 1
Exactly
honestly just do a big pattern match
ya
if you wanted to generate that at runtime with reflection i don't think that's terrible (as long as you aren't doing the reflection every time)
but i would just do a big switch statement
also keep in mind that if you refactor your class definitions, that may well beak your type dropdowns (or old savegames if they also rely on the type)
be careful directly serializing classnames
Yeah suppose that would work - I would have to add to the dict everytime I make a card but same issue as what you just wrote
i find it can be nice to have that step
Some sort of CardLookup class that the SO references, and the CardLookup just returns an instance of that card's controller?
it's the step where you map the 'design time' configuration to the 'runtime' entities the game core will use
seems fine
I find that I need to do this with most things so I sometimes have it as a more explicit step as part of the game starting
but running as a server you'll have different considerations
for instance if you might be hosting a bunch of games, you don't need the 'game' to store that lookup
you could have it cached somewhere that is shared between all games
I'm new to networking and have no idea how I would cache anything to be shared across all servers
but yeah, that sounds sensible
i just meant on a single server between multiple instances of the game
but if you do have multiple servers then yeah you could do that too
how would the CardLookup reference the correct card? Lets say the SO passes that card's ID - I would have to hardcode a dict that maps the IDs to the correct type? Is there a better way to resolve that without the ID having to be changed in 2 places if they were to change?
ionno, that stuff gets harder if it's some stored procedure and not just data
I've got a single player game with a bunch of state in the world that accumulates. changes to the world, items you've retrieved, doors, etc. etc. it's organized along acts -- act 1, 2, etc. any pointers on how to create a system for devs to load up an arbitrary act and start playing? my current thought is to run some code that manually configures the world state, but that seems very error prone / likely to become stale quickly
well it's 2 lookups:
- card id -> card instance, now you have your 'core' attributes
- controller type -> controller instance, one of those core attributes is this type, so you use it to look up the controller instance you build at startup (or build a new one if you need to)
- you build at design time or when the game starts if your cards are moddable
- you have to build at runtime because you can't represent the controllers as data beyond some kind of ID
do you have a save/load system? or will you need one? maybe time to build that and kill 2 birds with one stone
if your state is easy to update in-place you can build a couple of 'test saves' and you're golden
yea that exists, I could set aside saves at the start of acts -- but then I'd have to recreate them everytime sometime changes in an earlier act ๐ค maybe still the way to go though
it depends how far along you are, cause you have to do that anyway once you have users with your game
like if you update the game such that old saves will break, forcing yourself to use old saves to test will also force you to make sure that doesn't happen
but then you have to solve that problem which may not be worth it if you're still prototyping
yeah, makes a lot of sense. I think I'm always too reluctant to make lookup classes - starts to feel like I'm sacrificing some modularity. But I suppose that's always the tradeoff when it comes to performance
Thanks for your help & patience, appreciate it
I'm meaning more, if a dev adds some new puzzle to act 1, then acts 2 & 3 save files will need updated to reflect that the puzzle is solved by that point. I'm not terribly concerned about players in the future. the game will be one-and-done
ah yeah, that's something you need to solve anyway if you plan to update your game ever, but if you don't then maybe it's not worth it
if things in are constant flux the easiest may just be to have some 'skip to next act' buttons which you maintain as doing whatever specific things are needed
You could make a more generic EntityLookup<T> or something and reuse it if makes you feel better ๐
if the game is self aware enough, you might not need to do anything manual
like if the game understands that it contains objectives and some objectives are required to reach a given act, you could pretty easily make a 'complete all act 1 requirements' button and have it continue to work
nothing quite as concrete as an "objective" more like, to get from A to B you must watch this cutscene, kill this enemy. from B to C you must get this item from the table and open this door. C to D requires solving this puzzle, etc. conceptually, it's easy enough to write it all out and then update things as needed, but in practice I think people will forget to update the metadata and then the things will be act unpredictably/oddly. that said I'm struggling to imagine a solution that isn't either easy-to-forget metadata or bookmarked save files
well if you make it as concrete as 'objective' then you could
if instead your game is built of objectives and objective types with a completion state and some of those types are flagged as required for a given act
but it sounds like that would be a significant restructuring, so maybe your time is better spent elsewhere
likely the ship has sailed on that front -- and it seems like that just moves the state tracking down a layer, which might help keep it from going stale I suppose
it codifies the state tracking as a known thing which the program can reason about
you could do that other ways too if you wanted
I hear you that I could try to hook into save file upgrading as a possible way to alleviate re-recording stale bookmarked save files ๐ค
mark state variables with attributes
doesn't sound worth the time to me, but yeah a simple migration system
you still have to remember to write the migrations, but you can automate running them for savefiles with an older version
maybe you'll be glad you made it when you do ship and then someone immediately finds some small bug which requires you to push a patch which needs to include some state structure changes ๐
Hi guys when i try to export my project to android studio
am missing libil2cpp.so file, and currently getting a crash due to libil2cpp.so not found. Does anyone have any idea how this can be solved?
...performant or the cleanest - namely, iterating through the card pool and using reflection to grab it's controller
i don't know if it's a performance or a cleanness issue really. you could have tens of thousands of cards, and it will perform fine
might be digging deeper into the wrong approach rather than finding a more suitable one
it sounds like you have a server and execute the rules there. if you don't experience pain there, where there would be a lot of bugs, you will be fine in the client. overall the way you are doing things doesn't sound buggy to me, even if it sounds clunky
Hey, for a multi target system i use Transform[] , anyone has a better variable to do so ?
also do you guys think it's optimized enough ?
(mods : can we send short videos here ?)
ref ItemForQuestEntry ItemForQuestEntry = ref RecipeForQuestEntry.ElementAt(i); if (ItemForQuestEntry.ItemID==DatabaseEntityReference.DatabaseEntityID) { if (ItemForQuestEntry.Amount <= SplitItem.Amount) { RecipeForQuestEntry.RemoveAt(i); break; } else { ItemForQuestEntry.Amount -= (uint)SplitItem.Amount; } }
Does this just work? I am not sure how local ref variables work
The intent is to either remove the entry from the DynamicBuffer or to reduce it's amount
ItemForQuestEntry is a struct and RecipeForQuestEntry.ElementAt returns a ref T
multitarget?
what are you trying to do
what are you trying to do?
aiming at multi enemies at once to throw a projectile on each of them
each enemy can be locked multiple times and a projectil can be throwed each time
The intent is to either remove the entry from the DynamicBuffer or to reduce it's amount, I am wondering if the refs make so I don't need to assign it back to the buffer in case it was not removed
var x = listOfStructs[0];
x.field = 1;
listOfStructs[0] = x;
is the appropriate pattern for structs. otherwise, declare a listOfClassInstances and use class instead of struct
just use class
it sounds like you want classes
a transform array sounds fine
yeah, my code works i was just wondering if it eats too much RAM and if there is any better way to do it
i got a video to show how it works, but dunno if i can send one here
yeah, that's how structs usually work, my question is because I am not sure how the refs will affect the code, DynamicBuffers don't support classes
for instance, would this just work?
ref var x = ref listOfStructs[0]; x.field = 1;
what are you actually trying to do
there's a reason dynamic buffers don't support classes
this is a DOTS question ight?
i think maybe put it in the forum
not really, it's a c# question, but the context is DOTS
because i don't know
isn't it overdoing to create a class for DynamicBuffers ?
I am asking how the 'ref' qualifier modifies the behavior of the code. If I just wanted the code working I could just assign it back later
i think your question is too much specific, you gotta find that out yourself
i don't think there's any impact
i think it will
gotta sort out how
i think that's what he really want to know
/// <summary>
/// Gets the reference to the element at the given index.
/// </summary>
/// <param name="index">The zero-based index.</param>
/// <returns>Returns the reference to the element at the index.</returns>
public ref T ElementAt(int index)
{
CheckWriteAccess();
CheckBounds(index);
return ref UnsafeUtility.ArrayElementAsRef<T>(BufferHeader.GetElementPointer(m_Buffer), index);
}
It is a ref return
Instead of the value, ref passes a pointer to where the value is in memory. The compiler translates any modification that is made to the ref variable from a usual "load this value" to "load this value, at the specified address"
so it just make it run faster by using more RAM ?
Yeah, the confusion came at the difference between
ref ItemForQuestEntry ItemForQuestEntry = ref RecipeForQuestEntry.ElementAt(i);
and
ItemForQuestEntry ItemForQuestEntry = RecipeForQuestEntry.ElementAt(i);
The second one is just a value field whereas the first is still a reference even after stored as a local variable, right?
the second is a copy
The difference is insignificant. No need to worry about RAM until it actually is an issue. Use the Profiler if needed to pinpoint the issue.
thanks for the reply. what makes this design clunky out of curiousity?
separate Q - I went through some of your projects on github the other day and some of your solutions are very well thought out. is this typically a result of careful planning, or are there huge refactors involved once the codebase is developed, hindsight 20/20 and all that? I always get paralysed at the start of a project, wondering if my design choices will give me the modularity I need, without over-engineering everything. I'm trying to get better at balancing that.
I have a problem with cosine here. It's a simple helicopter lift&thrust calculation, and I need the cosine to check the helicopters angle. The problem is that the cosine is periodic, even though the eulerAngle.x stays at -45 degrees for example. How could I fix this?
Nevermind! I had to use radians instead! Sorry guys!
hey, it seems my scriptableObject here isnt working correctly. Unity inspector shows be one value, but when i open the file as text, it shows an older one.
has anyone seen this before?
I feel like this is simple, but I don't know how to google it. What does this code give as an answer:
int integerAnswer = (intToUse< 5) ? intToUse+ 1 : 0
I have seen this in some code online.
That's a ternary expression. It's a condensed if statement.
what it gives as an answer depends on what intToUse is
Put your condition in the first part of the expression. If it's true, then it returns the value after the ?. Else, the value after the :.
Ok, that sounds interesting.
So the answer depends on the condition intToUse < 5.
Thank you very much @fresh salmon and @kindred remnant ! โค๏ธ
whats the best way to have an editable list of objects before i use a datatable lol
why is not just a list on a ScriptableObject or component not fine?
For this, do you prefer to implement different factory (zenject) class or not?
There are different buildings. They have same components as well as different ones. There is a prefab for each building.
To create a building through prefabs, the input is level (int) and definition of that building (stat/data).
Definitions are SO. For each building type, a definition type exists.
Building1: BaseBuilding
Building2: BaseBuilding
Building3 BaseBuilding
BuildingDefinition1:BaseBuildingDefinition
BuildingDefinition2:BaseBuildingDefinition
BuildingDefinition3:BaseBuildingDefinition
I can have only one factory class for all and passing int level and base definition to Create method. Then, inside each class, cast base definition to the desired definition type and initialize components based on.
// Building1
public void Initialize(int level, BaseDefinition definition){
var buildingDefinition = definition as BuildingDefinition1;
//...
}
What is your suggestion?
How do you go about video streaming in Unity?
And do you decide to take streaming outside of unity into native app and render unity on a canvas?
What could be the reason for terrain not being rendered in runtime (in build), and how to debug it? It seems bounds are correct, but im not sure which terrain/terraindata variables should i check to know if everything is ok
more info:
- bounds are fine
- I already activated all GOs and monos
- terrain.drawHeightmap and terrain.drawInstanced set to true
- terrain.materialTemplate not null
- terrain collider's collisions are working
My guess would be that the mesh is there, but the visual data (as in the color of terrain etc) is either missing or failing to render
What is your platform ? It could be platform related.
The responsibility for the creation of the building should be in the definition. No need to add an extra layer with a factory. Something like Instantiate that will fill the required dependency/source data, but on the Scriptable Object does the job. Otherwise, you are over engineering your architecture in my opinion.
That being said, I don't really know how Zenject works. I'm not really fan of Injection Dependency in Unity, I prefer to use simpler but as efficient method like ServiceLocator.
not a code issue, #โฐ๏ธโterrain-3d
procedural terrain
Hey, I need to replicate the main mechanic of this game:
https://play.google.com/store/apps/details?id=com.playstrom.dop2
Basically, I need to erase a part of the sprite on touch. What would be the best approach?
I know that I can use Texture2D.SetPixel to set the pixels of the image, but this results in low performance for big images. Is there another approach?
Hey Im having an issue understanding unity authentication
So I use authentication with steam, I got my user Web API key from here https://partner.steamgames.com/doc/webapi_overview/auth as described in the docs, I got the error 401 "unable to validate token", so I tried again asked my mate to create a key of his own, same result.
Then I went to an old project of mine where I still know it worked, copied the key from there, and now it works. Thing is: I have no idea where that key is coming from, can anyone explain me why this happens and maybe tell me how I can get it to work with my own key?
while i don't know what to do in the steam partner dashboard specifically, you have to associate your new app/game with steam there
it will give you a client ID. or sometimes you get a secret.
I dont think I understand what you mean
I have a game ID on steam and I have an API user token, thats the only 2 unity asks me for, now the problem is the API token, because as I said it works with the token of an old game
I dont know what you mean by associate my game with the dashboard, all I can do is create a new AppID, but that I did and is not the problem
Does anyone know how I can deduce a working build app not starting on mobile? It worked yesterday
Is there an easy way of doing this? Its crashing instantly and I can't get any kind of info from the mobile
okay. well you can try visiting https://jwt.io and pasting the token you have. then put the part in Payload here in the chat
Any idea where those are located on Samsung?
or you can paste the token to me in a DM, and i can decode it and look at it for you
you can paste the decoded token output here
Use logcat
installing package and rebuilding
you can remove your name from the Payload data if it's in there or whatever
adb logcat -s Unity ActivityManager PackageManager dalvikvm DEBUG is a decent start, if that still doesn't show anything, just do no arguments and output it to a file (adb logcat > test.log)
use your best judgement
I dont know why the key itself would be important tbh I mean I think its safe to assume steam wouldnt give me a faulty token twice
nothing else should be sensitive
Quick question about Dots. What happens if the entity I get this aspect for doesn't have Grid? Do I get an error message?
well does it decode?
it's not a key
there might be a iss or aud fields that are relevant
more likely than not you misconfigured something
it will tell you in this token
They literally call it a key
okay i think you can definitely try pasting it into the site
and giving it a try
i am very confused. this is the windows command line performing miracles on android?
so i think maybe start fro the beginning on a tutorial
but it is tho
https://docs.unity.com/authentication/en/manual/SettingupSteamSignin#Set_up_a_Steam_account_sign-in
Here step 2 the link leads to this site:
https://partner.steamgames.com/doc/webapi_overview/auth
and here I can only do that key and nothing else
It comes with the android sdk, it just grabs logs
Then I went to an old project of mine where I still know it worked, copied the key from there, and now it works.
i'm not sure what is going on. like i siad, you have misconfigured something. this is consistent with a misconfiguration
Also unity does expect a key
this thing is a client id and a secret... but i think you will sort this out
i would start from the beginning
the site I sent you is what unity expects Im fairly sure
from a tutorial
its not an ID
Just go to the android sdk build-tools folder intead and run it there
401 "unable to validate token" is telling you something about the token, not the key
You should add the build-tools folder to your path environment variable so that it works everywhere but ๐คทโโ๏ธ
thats conflicting with company policy as I cant add stuff cuz im not an administrator
Stupid companies
I agree
I get the token from the key with this code:
Callback<GetAuthSessionTicketResponse_t> m_AuthTicketResponseCallback;
HAuthTicket m_AuthTicket;
string m_SessionTicket;
void SignInWithSteam()
{
// It's not necessary to add event handlers if they are
// already hooked up.
// Callback.Create return value must be assigned to a
// member variable to prevent the GC from cleaning it up.
// Create the callback to receive events when the session ticket
// is ready to use in the web API.
// See GetAuthSessionTicket document for details.
m_AuthTicketResponseCallback = Callback<GetAuthSessionTicketResponse_t>.Create(OnAuthCallback);
var buffer = new byte[1024];
m_AuthTicket = SteamUser.GetAuthSessionTicket(buffer, buffer.Length, out var ticketSize);
Array.Resize(ref buffer, (int)ticketSize);
// The ticket is not ready yet, wait for OnAuthCallback.
m_SessionTicket = BitConverter.ToString(buffer).Replace("-", string.Empty);
}
void OnAuthCallback(GetAuthSessionTicketResponse_t callback)
{
// Call Unity Authentication SDK to sign in or link with Steam.
Debug.Log("Steam Login success. Session Ticket: " + m_SessionTicket);
}```
And this code is poasted straight from unity docs
Anyways, you can just execute the command from the build-tools folder instead
like i said, you can put the token into https://jwt.io
and it will give you an illuminating piece of diangostic information
i'm not saying put the key in there
which in more technical terms is known as the secret
anyway
you will figure this out, good luck out there
You do realise there is a reason Im here right?
i'm sorry, i have no insights as to what is misconfigured
it sounds like you have an earlier project that works. maybe continue working from there
The current project works too
you don't need to be an administrator to modify your user's path variable
but i'm not sure if there's a group policy for that... pretty nuanced thing lol
Well there gotta be a reason it works with some random key I found and not with the key that has a reason to exist
just nope
Its literally like I bought a new lock and it opens with my old keys but not my new ones
I did have a message about jetifier earlier but I am trying to build for android 8 which doesnt have that
ah uh, this is probably relevant...
separate Q - I went through some of your projects on github the other day and some of your solutions are very well thought out.
i try to improve architecturally in a lot of stuff that i make - like to try one new thing. so many games, zero people play, or will have a meaninglessly small audience, so it's really worth it to learn something.
is this typically a result of careful planning
only very rarely. the monster match game was planned. all of its gameplay is so straightforward, you can contain what the whole game does in your head. for the minigames, same thing - they are so small, experiences fewer than 10 minutes, so the whole thing can fit inside my head. otherwise for something new, better to get something working and fun, and then rewrite it if there's an audience.
or are there huge refactors involved once the codebase is developed, hindsight 20/20 and all that?
this is the case with spellsource. the client, whose source code you cannot see, was rewritten after the first prototype. it found an audience so it was worth doing correctly. otherwise i spend a lot of time researching pre-existing implementations, wherever i can find them.
some games like FPSes, retro platformers, and fighting games have so many traditions that it's not worth changing anything. the architectures are all very tightly coupled to things like user input on purpose, they have a very specific UX players expect, and writing that from scratch means reinventing a ton of details that end users are really sensitive to. i'd probably use Unreal for an FPS because it has all those things.
balancing
imo there's no hard and fast strategy to how you write something in the beginning. unless the game follows a very specific tradition, you should write the fun and innovative thing first before anything else.
you have to set unity to use the jdk, gradle and ndk paths that it provides
use the android sdk it ships with
what is the error message that you got?
its been a while, let me just run a build and provide the output
these aren't really advanced programming questions by the way. a lot of people suffer through misconfigured editors trying to build for android
and then you try a bunch of random stuff to fix an error you didn't understand
you will have to google the error and do exactly what it says
and comprehend whether or not it worked for people to decide if you do it
tbf, I fixed this problem 3 weeks ago. then the office decided upgrading to windows 11 was a good idea
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':unityLibrary:com.voxelbusters.essentialkit.androidlib:generateReleaseRFile'.
> Failed to install the following Android SDK packages as some licences have not been accepted.
build-tools;30.0.3 Android SDK Build-Tools 30.0.3
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
Using Android SDK: C:\Program Files\Unity\Hub\Editor\2023.1.0a20\Editor\Data\PlaybackEngines\AndroidPlayer\SDK
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Im assuming this is probably my issue
To fix that, I had installed the Licensing Library via Android Studio but that doesnt seem to work
I just reinstalled it and it doesnt even ask me to accept the license
i believe this is fixed in a later unity version
but basically something is messed up when you installed the sdk
normally you are prompted to accept the license in unity hub at installation time
cd 'C:\Program Files\Unity\Hub\Editor\2023.1.0a20\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\bin'
.\sdkmanager --licenses
this will also work from Windows Powershell
but this will not resolve the error completely
i believe one version of unity ships with build-tools;30.0.2. i assume you have not modified your build.gradle
this is a regression
i don't think it has anything to do with windows 11
what version of unity are you using
oh
it's right there
why are you you using 2023 alpha?
well that pretty much settles it
you should be using 2021 LTS
clearly you had installed, previously, a more appropriate version of unity
do you use source control?
I took over the project from a previous dev. he decided on the version. not sure if downgrading is going to happen safely
you can look at ProjectSettings/ProjectVersion.txt, or let hub tell you the appropriate version
hmm
do you use source control?
I ll make a backup and load up a different version in the lts
like git?
I do
then no need for backups right?
technically true
๐ฏ true
I can always roll back
this is code advanced
so you installed the version that hub said huh?
and he chose 2023 alpha
the project is likely not going to be complicated enough for this to matter
do you have any meaningful uncommitted work?
if so, you will want to commit it
then do git clean -dxf in order to remove the pre-existing Library folder and other dirt that may be in there
if you git clean -dxf it will also remove uncommitted files everywhere
and if you're like, well i'd rather create a duplicate folder
it's your prerogative
you're going to have to go into the deep end of the pool some day
but yeah, i wouldn't use an alpha version of unity
and expect things to work
or you have to do this stuff a million billion times faster
like trying to accept the license the way i described
Reading the project documentation did mention some features that were being used from the 2023 version of unity but those might not even matter
regardless, I should probably get to an lts as well as fix the license but that could happen during that migration process
what is the idea
is this a VR game?
AR
and why does it have to be on android?
is that the device you own?
or is it for an android based HMD
there's a lot going on i apologize
this is both android and iOS. with priority and testing on android at this time
i am trying to be helpful but also trying to go at 10x the speed you've been going lol
do you know what feature it needs in 2023 concretely?
related to anchoring of ui elements in UITK. but not much specifics are mentioned
that seems so low value
I doubt these differences even matter cuz there is very little ui relance on anchoring. most of it is vertical stacking
anyway the game at some point did build for android right?
or as far as you know, never
before we updated to win11 it worked fine
the update to windows 11 is a red herring
i agree that there might be some configuration that hasn't been reproduced yet
it could very well be this powershell command
that is seemingly taking you forever to do lol
that you could have done while we were writing here
i am just razzing you it is fine
try the command and see what happens
Hey guys do you know if there is a way to measure and evaluate energy cost in unity?
yeah, most of the reason I'm just typing is cuz I'm currently making food atm. I entered the command before and didn't work, assuming I was in the wrong directory
lol
okay that's understandable
i mean this stuff is frustrating
while it does say the error message, and it does indeed match something in google i parlayed to you
there's going to be other feedback in the terminal about whether or not the command executed successfully
it's going to be a lot of little details
personally, if i were your people, i wouldn't waste a single iota of time on android users
even if it's a branded AR experience
and this is all about CPMs
even if it's a 3d scan of a wendy's hamburger
and presumably android users would eat that garbage
Im tempted to agree, we are a b2b and it's not exactly my choice sadly
lol
i mean zero people will use this thing on android so it might as well be buggy as hell
client wants AR, and we told him it's not a thing anyone cares
I have been saying that for 2 months but the client keeps saying their user base likes the app
it has 50 downloads
okay well when you're ready try figdgeting around iwht that command and reply here
no
you can use the macOS / iOS energy visualizations as a "report" and maybe that would be sufficient for your use case
Will do. it will probably fix it and I can move to the next issue. then round up for the day as this is all unpaid overtime hehe
it has about as much meaning as Lighthouse's Accessibility score
which is meaningful to people who don't know anything
really depends on what your objectives are
I think I've read on chat gpt an answer to put the aplication to run in background. maybe to use as this, but this would not give me a good measure especification of tasks or jobs either way would it? btw is interesting to know what can I do, would be great to have a tool or an external one that could measure it.
I think I've read on chat gpt
hmm...
Its the most efficient search engine atm ๐ dont judge me
Too late
Really? How come?
i spend a lot of time researching pre-existing implementations, wherever i can find them.
...
some games like FPSes, retro platformers, and fighting games have so many traditions that it's not worth changing anything
how do you find the material you need? in my experiences, games are far less open source than other tech, and I find it really hard to know where to start looking if I want to research genre-specific implementations/common architecture.
Thanks for your response - very insightful ๐
for really traditional games i look at the assets in unity. for FPS it's pretty much unreal engine
so like the ultimate fighting engine is a good attempt at fighting games in unity
a lot of traditional games people try to do multiplayer, which seems so hard to me
and unity is really poorly suited to realtime multiplayer games
there might, essentially, be no good architecture for them in unity. like networked FPSes in unity can only really be done to the T of the tradition using DOTS, which is like using a whole different engine
some things which don't have a big multiplayer thing going on, like metroidvania platformers, there are assets that are like 90% of the way there
like the MoreMountains 2.5D Corgi Engine is as flexible as you can get while still feeling like Mega Man movement
for a platformer
and it's a very very popular asset
the source code is open
and the moremountains guys you can talk to directly
there's other stuff like graphics solutions that also have a lot of traditions. jason booth is very responsive on his discord
if you want to learn about How to Do Terrains
if it's not these big realtime traditions there are some gems out there
the spellsource backend, which is open source, is a fork of metastone, a hearthstone simulator
metastone was inspired by xmage
a lot of simulators are inspired by OpenTTD
if you wanted to make a civilization-esque game, FreeCol is very well written
a really well written and coherent java game
also has a very responsive maintainer
if you like point and clicks there's a very capable asset in the asset store, but it's really idiosyncratic... almost TOO traditional
it works almost exactly like the scummvm / LucasArts tools
if you are REALLY scratching for a specific implementation use https://grep.app
Search across a half million git repos. Search by regular expression.
These are just resources you've built up over time as a part of the game dev community?
i think so yeah
i haven't really ever had to ship anything with a huge team so that has affected my opinion a lot
Awesome. Well, thank you for sharing
this stuff makes a lot of sense if it's 1-3 people engineering. which is how a bunch of these old traditional games were made anyway
it's still Within Scope to make a multiplayer FPS as 1 person, it just takes a lot of time
I mean, that suits me more also. Zero chance I'll be switching industries anytime soon
If you ever need a hand with web dev, let me know ๐ ๐ซก
also if you want to reduce your pain as a windows developer and you have a macos background
you can download busybox for windows, saving it to C:/Windows/sh.exe, and then run sh -l for "Unix in Windows command line"
managed to get it to work after I got back from dinner
I avoided the entire unity installed SDK and went through the Android Studio version entirely
reinstalled java, set up the path variable (that was appearantly also missing) by asking our sysadmin
they are going to roll out this change to all pc's in the network so I can have access to our render/build pc to speed up work under load
You need to use device specific tool. Something like android studio provides: https://developer.android.com/studio/profile/energy-profiler
Is it true that we can code in c++ now?
does anyone know a good double-precision vector/matrix/transform library for unity (esp something which implements something like a virtual transform (not tied to a gameobject)?) - I couldn't find one and am contemplating rolling my own (I'm aware of the issues with doubles and performance, we need them because of reasons)
basically, just use Unity.Mathematics in general
oh nice. I was mislead by the unity mathematics intro page which seemed to suggest it was just float4, float4x4 etc
Hi everyone, I have a GameObject with two scripts, A and B, on it. A is a parent class of B. A has an OnMouseDown() function. When I click the GameObject, OnMouseDown() calls twice because "This event is sent to all scripts of the GameObject with Collider."
I only want OnMouseDown to call once, but I need the functionality of both scripts. Other than copying all the code I need from A and putting it in B so I can make B no longer a child class of A, what solution is there?
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hi everybody, I'm trying to figure out how to calculate the scroll sensitivity of a scrollRect so that it moves by an amount of pixels.
For example, I'm creating a fixed height scrollRect with a fixed width of 1000px. I put 15 items inside meaning the width become 1500px but it only shows 1000px. I want the mouse scroll to move 1000px at once so that the second page is displayed
How would I calculate the required scrollSensitivity? I can't figure out the relation between the sensitivity value and the pixel value. Plus I read online Mac and Windows interprets this value differently?
Nevermind I just moved all the OnMouseDown() code to a third script which I added to the GameObject.
i mean, that's just what it suppose to do, unless you want to override it to do nothing in B
which in any case it doesn't make a lot of sense
Hey everyone, I'm having a rather surprising problem with Jobs
I have this IParrallelForJob that works on two 4-element arrays (I've made them constant size just for testing), and yet the Execute(int index) method gets called by the jobs system with the index parameter being higher than 3
[BurstCompile]
public struct InScanConeCheck : IJobParallelFor
{
[ReadOnly] public NativeArray<BeaconData> Beacons;
[ReadOnly] public SightSensorData Sensor;
public NativeArray<ScanResult> Results;
public void Execute(int index)
{
Debug.Log($"{index} / {Beacons.Length} / {Results.Length}");
if (!Beacons[index].Alive || !Sensor.Alive) return;
(...)
}
}```
the debug log consistently returns 4 and 4 for arrays lengths, and indices exceeding their length coming from the Execute parameter
the line below throws exceptions
IndexOutOfRangeException: Index 16 is out of range of '4' Length.
scheduling the job with different interloopBatchCount values changes nothing in this behaviour
show the code where you schedule the job
here you go
// Set up buffers and verify which beacons are in range and within scan cone
var activeBeacons = new NativeList<BeaconData>(128, Allocator.TempJob);
for (var i = 0; i < _beaconData.Length; i++)
{ // copy active beacons from the beacon buffer into a shorter list
if (!_beaconData[i].Alive) continue;
activeBeacons.Add(_beaconData[i]);
}
Debug.Log($"Active beacons list length: {activeBeacons.Length}");
var results = new NativeArray<ScanResult>(activeBeacons.Length, Allocator.TempJob);
var job = new IsBeaconInScanConeJob
{
Beacons = activeBeacons.AsArray(),
Sensor = _sensorData[_currentSensor],
Results = results
};
var jobHandle = job.Schedule(_sensorData.Length, 4);```
there's some array copying voodoo here, that i wrote trying to narrow down the problem
but the entire thing is rather straightforward
anyone used csx in recent unity versions? share experience
can you log _sensorData.Length and see what it is
as that will be the max index (-1) since you have set that as the job length in the Schedule
well
thankfully this is just me being blind
not jobs malfunctioning
let me just verify it works
yeah, you are probably wanting to use activeBeacons.Length or results.Length instead
and naturally it works
sorry for making a rubber duck out of you
and thanks for spotting the obvious
hehe, you know for next time to always check that length now :p
I think csx is for simple scripts - basically a 'method', Unity 'scripting' is basically full C# programming
Are you referring to il2cpp? If so, then no, it's a scripting backend that translates your intermediate language to c++, that is then compiled into native
I have this very weird thing going on with my scriptable objects. Whenever I load data on them and quit play mode, there's two situtations:
- When I view my scriptable object in the inspector, the data in the scriptable object doesn't get deleted/cleared.
- When I don't view my scriptable object in the inspector, the data clears
Does anybody know how I can fix this problem because it's extremely annoying for the players in my game.
you should really only store immutable data on scriptable objects
it is WAD that you can change stuff in them in playmode in the inspector and have it still have the change on exit
But how should i do that
I still do have the data after exiting, but only if i view the scriptable object in the inspector
wtf does wad mean
working as designed
and how do i store immutable data on my scriptable objects?
what are you using them for?
as a proper save system? like exit application and reload when opened again?
yes
scriptable objects created at runtime in builds do not get saved to disk
a save system is not a use case for scriptable objects
as i said, they do when i view them in the inspector
that explains a lot
yeah or something similar
ok thanks
just in case you want a source
`When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting.
In a deployed build, however, you canโt use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.`
doesn't sound like an advanced issue. also https://dontasktoask.com/
then explain the issue
ask in #๐ปโcode-beginner where your question belongs
and maybe try googling it first too
good luck getting answers. i won't be baited into writing your code for you. and if you had googled it you would have found the perfectly valid 12 year old thread on the forums that explains how you could do that
Is having a 2d overlapcircle running on update more/less expensive than a 2d collider?
profile it
So after getting told in #๐ปโcode-beginner that we won't write it for you you thought the advanced section would be more receptive to just do it for you with no effort. Good luck with that
Try ChatGPT. Should be able to help on basic question.
Eh no, especially for beginners
It's sometimes right, but it's sometimes very wrong
And you can't distinguish between the two
When the question is basic, it is able to be more right than wrong.
There's still a risk a beginner can't take
Also, it can help in figure out the general idea of the script.
I mean, they either work from nothing or work for something that isnt perfect.
At that point, you try it. If it does not work or you are not able to make what you want, you try something else.
And if it works, will the user learn anything about the code they blindly copy-pasted? Keep in mind that when you're new to something, you don't have that ability to determine whether the thing it spat in your face is right or wrong
And that's why it's not allowed to ask or answer questions using unverified AI output here
Anyway it's off-topic for this server
Discussion about whether an AI is right or wrong doesn't belong here
They can learn. I have use it multiple time to study subject where I'm not really good. You can ask to explain each part of the subject. You then can cross verify with your notebook.
It's not about the AI being right or wrong. It's about if referring someone to an AI is a good or bad idea. I have not seen any rules saying that we cannot refer someone to an AI, if there is such rule, I will obliged by.
You then can cross verify
You're forgetting the context
A beginner will not verify because they're confident in the answer being right
It's formatted so well it looks correct, even when it isn't
Check #๐โcode-of-conduct
It's somewhat implied by the rule of not allowing AI code questions and answers. If it needs to be explicitly explained that guiding beginners to use it is also not allowed, then we can update the rules.
It should, if it is something that you do not want to see, as it is not clear for me that guiding someone to an AI agent is something wrong or is the same as using AI generated answer as it's own.
Well, you are basically answering their question with an untested answer.
That isn't really GOOD even if it wasn't AI.
For me, using an AI to learn is an alternative way of searching the internet. It is true that the AI might induce you in error, but being cautious (like you should always be given any source), you can get relatively good answer. Even more when your question is simple or when people refuse to answer your question for any reason.
It is not true that I'm answering a question with an untested answer because, as I stated earlier, I have use AI like ChatGPT to learn from a subject that I do not know a lot about and found multiple answer that helped me. In other words, I know that ChatGPT could be a potential way of finding an answer and that by using it someone could potentially found an answer. It is the exact same as saying google it.
If it is the same, then why not say to Google it?
It is not the same at all. It strips out attribution and accountability from answers, even when it is correct.
using an AI to learn
hmm...
Might be super elitist of me, but days like this kind of make me wish we had a more exclusive channel for #archived-code-advanced. I usually enjoy reading through some of what's been shared here - even if I'm not involved in the conversation at all - but it can be pretty hit and miss. Today was defo a miss
Can anyone explain how does this flow shader work?
Specifically, how do they came up with the values for making the texture flow appear curved?
As far as I know, the shader is adding/subtracting time from the UV coords to make the texture 'slide'.
But I don't understand how to calculate the values for the UV coords to make the texture in a desired shape.
Are these just interpolations across the edges?
This is the tutorial - https://catlikecoding.com/unity/tutorials/hex-map/part-8/#7.2
This is where they make the shader - https://catlikecoding.com/unity/tutorials/hex-map/part-6/#8
(I've made the shader in Shader Graph)
You're asking about the shader, but the UVs are generated from mesh which is outside shader?
The UVs are set through code, the shader uses the UVs to animate the texture
I don't understand How to come up with those specific UV values to make the texture animate that way
Like, what will a UV value of (0.5, 1) do?
I tried testing it but it gives usually confusing results, I can't quite understand
When you are saying specific UV values which part are you referring to? The UVs are created to go from 0 to 1 to be able to wrap and use tiling texture to have continuous visuals.
This one
Those UV values are responsible for making the texture appear curved
With UV values like second pic, the texture appears straight and flows in a straight direction
With UV values given in the first pic, the texture appears curved and spreads out in a circular direction
This is the shader function responsible for animating the texture
It's still just uvs that are lerped as input to pixel shader? If you look closely you can see the lines between the edges in the lower part of first image.
I'm pretty sure it's just UVs
It's warping the texture using UVs
This is the same shader created in Shader Graph
Sorry I don't fully understand what information you're asking for. Do you understand how UVs are interpolated from vertex to pixel shader? If you keep the same UVs on the same vertex (if you're using indexing this is no issue), you will have seamless texture transition between triangles. They are simply nudging the UVs to get a more circular shape.
I don't understand the nudging part
Which values should I use to make the texture appear circular in shape
Look at this image. Red is UV.X green is UV.Y
The middle square is right now textured in a regular 0->1 way which you would expect the image to come out unwarped.
Possibly some sqush in Y direction.
Presuming triangles are the same shape, the outmost vertex on the side are 0.5 offset on UV.X from the ones next to them to continue the default visual.
Now you have something like this
Not referring to anyone but I heard people saying you can code unity in cpp nowdays and I wanted to check it out since I use cpp because c# sucks
You're the first person I know who says c# is worse then c++
yes, If I'm correct, It'll still appear straight? Flowing along Y direction?
Yes. I accidentally flipped the colors, but no matter.
Now the idea is to pull the lines so it makes more of a circular shape.
E.g. to round the lines in the side triangles you move the UV in the side vertex UV.Y "upwards"
This means, the V coords on the outer two upper corners will become 1 instead of 0.8?
Yes, some number above 0.8, depending on what angle you want the lines.
What about the lower coords
Does anyone have idea how to convert the following code to the mathematics API:
axis.Normalize ();
angle *= Mathf.Deg2Rad;
Vector3 torque = axis * (angle * s.spring) + s.damper * deltaAngularVel;
return torque;
Oh, I see, the lower coordinates are the same thing
The outer verts are moved upwards by 0.05
The math class doesn't really have good documentation and I couldn't find a way to multiply quaternions or find delta rotation between two rotations
Exactly, to smoothen the curve.
a way to multiply quaternions
math.mul(a, b)
find delta rotation between two rotations
math.mul(a, math.inverse(b))(for the rotation from b to a)
I was a bit confused at this at first why the middle point wasn't further down instead but realized the default space was based on the middle vertex^^
Is there a way to get the axis and angle out of the quaternion
Ok, I seem to get it now. It's just like usual UV mapping with the coordinates moving around to get the shape we want. ๐
Thank you, I've been at it for a couple of days now trying to understand how it worked
not sure - I assume so
Found a way to visualize the UVs ๐
Depends on what you mean. If you want the "forward" of a rotation you can do [Your Quaternion] * Vector.Forward.
I want to get the torque I need to apply for the given rotation
And why is the torque in Vector3 ?
I'll add it angular velocity and use that to rotate the object
I tried this but doesn't seem to work:
Not sure how mul() behave with Quaternion and Vector3 multiplication. It is probably an overload of the operator. That being said, I would try to use a Vector4 with 0 as 4th coordinate.
Yeah, the problem is with that statement
Any idea how to multiply quaternion and float3
The following snipped produce the same results for both method. I have tested it.
Vector3 forwardOverload = transform.rotation * Vector3.forward;
quaternion quaternion = math.mul(math.mul(transform.rotation, new float4(0, 0, 1, 0)), Quaternion.Inverse(transform.rotation));
Debug.Log($"[Overload Operator] {forwardOverload} [Mul] {new Vector3(quaternion.value.x, quaternion.value.y, quaternion.value.z)}");
Even better
Okay just one more question
how can I decompose the quaternion to angle axis
But no idea about the axis
The angle is fine
Rotate it with forward.
It will give you the forward axis.
If you want up, you rotate by up.
Yeah but I want it as an angularVelocity/torque
Do the same as I did. Make a small script with quaternion.ToAngleAxis() and quaternion.rotate(q, new float3(0,0,1)) and compare.
I'll try although this doesn't seem the correct approach
I'm not really sure what axis is ToAngleAxis
I think that wants euler angles right
not axisangle
Okay I did a bit of matrix multiplication and got this :
This retrieves the angular velocity required to go to q2 from q1 in 1 sec
I see, I was not aware of Angle Axis representation of rotation.
what is your goal? like making a space game
Something to do with changing gravity
every since im using the Unity Test Framework with playtime tests, i get this wierd error:
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.TestTools.TestRunner.PlaymodeLauncher+BackgroundWatcher.OnPlayModeStateChanged (UnityEditor.PlayModeStateChange state) (at Library/PackageCache/com.unity.test-framework@1.1.33/UnityEditor.TestRunner/TestLaunchers/PlaymodeLauncher.cs:113)
UnityEditor.EditorApplication.Internal_PlayModeStateChanged (UnityEditor.PlayModeStateChange state) (at <434908727417408abd02bbd1a0835ef8>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
it causes the scene to get reset every time i change something + run the scene
error only appears after first running a playtime test
Why do you multiply by 2?
Ohh right, the reverse. Missed that, thanks!
which data path should i use in builds
because Application.datapath doesn't work
System.IO.Directory.GetCurrentDirectory()
this one neither
It definitely "works", whatever that means
It changes, depending on the platform you're building to, but it will return a correct path
Though if you need to save stuff to retrieve it in a later run, you should be using .persistentDataPath instead
Does this act like the assets database, in the unity editor?
does that mean that i can use folders from the assets folder
No, folders from the Assets are bundled into the executable, they cannot be fetched afterwards
you can never use folders from Assets in a build
what are you trying to do? You should have started with that
Use Resources or Addressables to load assets at runtime.
cool
yeah a lot of this stuff is pretty nuanced
You'll want to use some combination of:
https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
https://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html
or Resources.Load/Addressables, depending on what you're trying to do @icy aspen
read and write json files
what would be helpful? it sounds like you are creating a free-body character controller of some kind
Then you want persistentDataPath for writing/reading files created at runtime
And streamingAssetsPath if you want to read json files that are created at editor-time
can i use folders from the assets then?
yes you can read and write from persistentDataPath
assuming there is something there to read
ideally you should be using Path.Combine or Path.Join rather than manually concatenating the string for the path
you'd have to show code
This will start working as soon as you follow boxfriend's advice:
#archived-code-advanced message
right now you're trying to write to a directory you're not allowed to write to because you're missing a path separator
(notice the lack of / between Documents and the name of your JSON file)
this isn't #archived-code-advanced
there are tutorials online for saving games
there are assets
they'll cover stuff like paths
can you give me an example on how i should use this with my particular code
The docs have examples for how to use it:
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-7.0#system-io-path-combine(system-string())
you are in the wrong channel
and now i have to use that
we're going to assume people in the advanced channel can handle basic docs and code examples
let's switch to the beginner code channel then
I'm debating on integrating Firebase into my Unity game to handle a lot of entity data for different tiles, AI characters, and structures. I'd like to have a nice database to keep all of these different entities in the same place that I can easily manage rather than writing a bunch of helper functions, using resources.load, and other stuff. Any thoughts on using Firebase + Unity?
you shouldn't use firebase to store static and potentially versioned game data
What about for maintaining and managing a lot of data for different entities with different categories?
i'm not sure how firebase makes this easier
i see how a database lets you store data... but unity already has many good, robust ways to author and store data
if you choose to not use unity to store the data, you will be recreating all the models to represent that data in unity anyway, so you'll wind up with 2x the schema, and going from 1 to N schemas entails versioning, serialization issues, etc.
@native nebula does that make sense?
Yes, it makes sense. I think I'm not explaining my current situation well enough
it sounds like you want to author e.g. an RPG not inside unity.
then you want to use those not-inside-unity-authored assets inside unity
that is completely not the case
hmm
hold on
well the first question really is, what kind of game are you making?
So basically, I'm building some editor tools at the moment to help me mass-produce generated structures, entities, etc. for my game. I'm building the structure editor, which will allow me to save structures as prefabs then spawn them in-game with different logic and such. Then I have the tile editor I'm working on, which creates entities as tile types, with properties like price, sprites, name, z-index, etc. These tiles are connected to a construction system, which detects these tiles and adds them to their respective construction category for the UI. I also have a ledger system, which works with the construction system to manage the expenses of some of these tiles and entities.
I'm at a point where adding a new entity or tile can be expensive in terms of code and how much time it'll take. I would love to have a system where I can input properties from some fields (ie the tile editor) then the other systems will feed directly off of that and add the new entities accordingly
mostly a lot of system design revamps
It's for a coffee shop management game, 2d top-down. you build ur own coffee shop from the ground up and compete with other coffee shops in the city you start in. the goal of the game is to buy out all the cafes in your city, then expand to other cities
so I'm considering Firebase as a solution to help contain a lot of properties for a variety of different entities, that I can then call api requests to from these systems and handle them automatically
firebase would contain static game data like the items you can stock in your coffee shop?
I'm at a point where adding a new entity or tile can be expensive in terms of code and how much time it'll take.
whose fault is that? ๐
๐
yeah data for those items, then for AI characters, tile data, etc.
adding firebase to your nice sounding coffee shop sim to manage static data
is going to make you hate game development
i don't disagree that it would work
it's going to be 10x worse faff though than whatever you're doing now
it sounds like you are more comfortable making automation tools using whatever firebase expects you to do, perhaps in a different programming language, than in c#
I need to really seperate and hash out these systems first of all
i get that. but then just make the tool directly on your computer
hold on
and do not involve firebase at all. if you want to emit e.g. templated prefabs, they are just ordinary text files.
lemme show you the top-level view for the systems i have / plan on having
if you really don'tw ant to build editing tools in unity, don't. you don't have to
okay
@undone coral systems placed in sectors
this makes sense to me
okay cool
i would just caution that simulator games tend to have "fake" decoupling
it really depends on how complicated of a game you want to make
yeah, atm i have a clearly defined scope I'd like to achieve
if it's more Tiny Tower than it is Puerto Rico
what
have you played tiny tower and/or puerto rico?
ive played tiny tower
okay in a lot of simulator board games
but you've played sim board games. like settlers of catan has action cards
yeah
if you want behavior like that, your game is tightly coupled
do you wanna hear about the scope btw
sure
so the scope is set in a city, with minimal information such as city laws and demographics that afffect employee pay and customer needs/wants
i mean there's not really much else to go off of that
okay well all these games wind up with a crazy ants architecture
my honest to goodness suggestion for you - and i rarely say this - is to paper prototype your sim
so that you can limit the implementation to the interesting ideas you actually have instead of totally ...
well it's already released on steam
oh
lmao
well then what the fuck am i talking about then lol
well I'm quite literally overhauling everything
standby i'll brb
there are two
i c
for unity specifically there is a format similar to node packages
for c# there is nuget, which is hard to use in unity
what's the other
is this a realtime simulator like game dev story?
realtime simulator
uh
there's kind of a similar game out there called Espresso Tycoon, however, that game is 3d and unreleased
basically there are four approaches to making simulators in unity:
(1) gameplay is built over time, decoupled, via GameObjects and scripts on them, with a bunch of Manager classes. tightly coupled game behavior happens on various singleton classes. (it sounds like you are here. rimworld for example)
(2) separate game state (in pure C#), game logic (in pure C#) and a decoupled, via gameobjects and scripts, approach to rendering the game state (what most people migrate to. this is how my games usually work)
(3) ECS with Game Objects
(4) full DOTS
well you shipped a game
and most people who use DOTS in the beginning don't ship games
ECS with game objects is a shippable compromise
the full DOTS is really hard
this game is def. similar to rimworld in anything but game premise lol
(2) and (3) basically differ in how you write the game state and game logic. in both (2) and (3) you are writing game objects with *View scripts on them, that query the game state and render stuff
so you get to use the really robust unity rendering featureset you are familiar with eithe rway
what option do you think has the "easiest" game-scaling opportunities?
it's just a matter if you want unity's specific approach to expressing game state and game logic or if you want to do it in pure C#.
probably (2), because ECS requires you to use a lot of stuff for the sake of performance that won't benefit you
performance doesn't just mean "scale up"
for example, NativeArrays
yes
that's why i'm saying in terms of scaling up to more sophisticated gameplay, i would write it in pure C#
yeah sorry, for scale up I mean adding a shit ton of new entities haha
instead of ECS
i hear you. like item types
consider that Cities Skylines predates ECS and still scales really well
yeah, shop items, tile data, entity properties
yeah
so i would prob choose 2, and i think you sort of already have
one approach you should consider is
Sure, Data Oriented Design (DOD) predates ECS. It's just a ecosystem that (tends to) make the default way of implementing something the DOD way
data orientated design ๐ฅด
didnt realize you were a Unity Staff member, sucks i got rejected for yalls swe internship ๐ฆ
I forget myself sometimes, that's why I have to delete half my messages
yeah definitely already on track
i feel that
class Item : GameEntity {
public async UniTask Use(Context context) {
this.quantity--;
context.FireGameEvent(new BeforeItemUsed(this));
await OnUse();
context.FireGameEvent(new AfterItemUsed(this));
if (this.quantity <= 0) { context.FireGameEvent(new ItemDepleted(this)); }
}
protected abstract async UniTask OnUse(Context context);
}
class CaffeinateWorkers : Item {
[SerializeField] private float speedMultiplier = 1.2f;
[SerializeField] private float durationSeconds = 30f;
override string description => $"Increase worker speed by {(speedMultiplier - 1f)*100)}% for {durationSeconds} seconds";
override async UniTask OnUse(Context context) {
var workers = context.GetAllEntitiesByType<Worker>();
foreach (var worker in workers) {
worker.speed *= speedMultiplier;
}
await context.GameTimeElapsed(durationSeconds);
foreach (var worker in workers) {
worker.speed /= speedMultiplier;
}
}
}
yeah i have something similar to that already
okay
youre using decomposition right
then i think you are in a really good place
sort of... you can see that the text of the special items is written in C# code
i'm not programming inside the inspector
so if you had some one time use item that made your worker speed 20% greater for 30 seconds, you want to do that in C#
you don't want a "IncreaseSpeedEffect" and a "DurationEffect" or whatever
just write it in code
you could have those things, but then you're creating a LISP, and as you'll see in an earlier discussion i've written into this chat, that's hard to do and your main obstacle
I have a script called EntityBase that a lot of different entities inherit, then properties change. ie:
EntityGrass:
EntityGrass : EntityBase {
void start(){
SetEntityName("Grass")
SetEntityZIndex(0)
SetEntitySprite(spritePath)
SetEntityIsTerrain(true)
}
}
if you wind up having a lot of items that modify worker speed, you can progressively modify this script
yes this is fine
just think about how an async UniTask abstract method can be used to let you author the spell-like behavior directly.
it makes sense to me right away
this just gave me an idea
"player manages a cafe selling magical potiond to medieval fantasy monsters"
that sounds insanely fun
yeah
no firebase since that requires LISP to work well
well
i might analyze my current system structure and see what i can abstract and simplify
Hello! I am trying to make a border shader for hexagons that use decals. I am using URP and the issue is the decals are rendering below water which is in a transparent render queue. I have tried forcing the water shader to use depth write, but the decal still does not respect it. I want the decal to project ontop of a transparent material. Any ideas on how to get the decal to do that?
Quick question (hopefully): I have an A* pathfinding program. I want to run it both directions, so that if one of the routes returns that there isn't one quickly, I can stop the other so it doesn't take too long searching all possible options.
Basically I want 2 coroutines and as soon as 1 returns empty I want to stop the other, but if neither returns empty I want to get the shortest one.
How can I solve this? I tried looking online but either my coroutines aren't actually going Async or it just doesn't stop the other, it still halts for a moment when I click an unreachable spot.
Pretty sure you shouldnโt post your question to multiple channels
can you share your code?
of course, one second
this is my current A* code
public static IEnumerator FindShortestAStarAsync(TileManager tiles, Hex start, Hex end, bool flipped = false, System.Action<List<Hex>> callback = null)
{
List<Hex> route = new List<Hex>();
Dictionary<Hex, float> priorityQueue = new Dictionary<Hex, float>();
List<Hex> checkedHex = new List<Hex>();
//Hex retrieved from Hex
pointers = new Dictionary<Hex, Hex>();
var startPoint = start.cubeCoordinate;
var endPoint = end.cubeCoordinate;
var current = start;
var maxDist = CubeDistance(startPoint, endPoint) + (end.transform.position - start.transform.position).magnitude / 10;
pointers[start] = null;
priorityQueue[start] = maxDist;
while (current != end && checkedHex.Count < priorityQueue.Count)
{
current = FindLowest(priorityQueue, checkedHex);
checkedHex.Add(current);
if (current != end)
{
priorityQueue = checkNeighbours(priorityQueue, current, end);
}
}
if (checkedHex.Count < priorityQueue.Count)
{
route = GetRoute(current, flipped);
}
if (callback != null)
{
tiles.priorityQueue = priorityQueue;
callback.Invoke(route);
}
yield return null;
}
this will run completely synchronously
Yeah it's CPU bound, putting it in a coroutine doesn't magically make it not block main thread.
The limiting factor is how fast the CPU can run through the algorithm.
a "quick fix" is to do some amount of work and then yield for a frame, perhaps you let this coroutine run for 50 iterations per frame
it means you'll need to wait for it to finish, but it will allow two coroutines to run for 50 iterations each frame each, and cancel the other when one returns finished
shoutout also to the UniTask plugin
int count = 0;
while (current != end && checkedHex.Count < priorityQueue.Count)
{
count++;
current = FindLowest(priorityQueue, checkedHex);
checkedHex.Add(current);
if (current != end)
{
priorityQueue = checkNeighbours(priorityQueue, current, end);
}
if(count % 50 == 0)
{
yield return new WaitForEndOfFrame();
}
}
so something like this?
Basically yeah you would have to insert stop/resume points into your algorithm, and communicate between the two and cancel if one completes.
yield return null;
There are issues with doing it this way though, particularly if the algorithm takes a long time, then you would also want to split it across multiple frames. On weak machines if you only allow it to run a short amount of time per frame (so to maintain FPS) then it will take a lot more frames to complete.
The best would be to offload it to a different thread so it can go as fast as it can while not blocking main thread, but often that's not a trivial solution.
in this case the algorithm shouldnโt take too long. the area isn't so large that it should cause problems
Hello everyone, i have searched everywhere, talked to chatGPT, but i cannot get the thing i want..
I want an Inventory system where i can store my ScriptableObject spells, and then be able to drag a Clone of the spell onto another panel, and then be able to use the spells from that panel. Basically the same as how World of warcrafts spell system works.
If someone knows how to implement this system and guide me, il pay 30 euro for it.
im hella desperate
ScriptableObject is only a dataholder. So do you mean panel in case of inspector or in game UI?
in game UI
@midnight violet
or if it would be like Minecrafts inventory so i can use the spells on 1-8 keys
Then you have to create a class, that gets filled with the data from your scriptable object. But the fact, that you ask this AND you tried using chatGPT lets me assume, you are not at all related to an advanced problem and rather should take a look at some unity basic tutorials. Check unity learn about UI and also scriptableobjects and craft your knowledge to put the things together
i just thought that this was an advanced problem so i'd ask advanced coders even though im a beginner
so, it took some testing but now I realised that if it surpasses 50 iterations, it actually doesn't return a solution at all. It most likely has to do with how i'm doing the callbacks, so what am I doing wrong here?
public static List<Hex> FindShortestAStar(TileManager tiles, Hex start, Hex end)
{
List<Hex> res = new List<Hex>();
tiles.StartCoroutine(FindShortestAStarAsync(start, end, false, returnValue =>
{
res = (res.Count > 0) ? ((returnValue.Count > 0 && returnValue.Count < res.Count) ? returnValue : res) : returnValue;
if (returnValue.Count == 0)
{
tiles.StopAllCoroutines();
}
}
));
tiles.StartCoroutine(FindShortestAStarAsync(end, start, true, returnValue =>
{
res = (res.Count > 0) ? ((returnValue.Count > 0 && returnValue.Count < res.Count) ? returnValue : res) : returnValue;
if (returnValue.Count == 0)
{
tiles.StopAllCoroutines();
}
}
));
return res;
}
}
The case of a full inventory, yeah, that might be advanced. But your actual issue is, how to get data into UI elements, how to handle dragging of UI elements. Noone will have the time to do a 1:1 tutorial with you about a full ui system and this active chat is a bad place to try to keep this topic up and running. ๐
Can you explain your issue?
am I returning before getting an answer, since it doesn't have an answer after the first frame in that case? and if so how do I fix that?
gotcha, well thank you for your time
so, I explained above, I have an A* algorithm, but I want to start it from both sides so that I can know faster if there is even a path possible, because usually one side is smaller so if the smaller one returns a path of 0 then there's no path possible, and I can stop the larger algorithm earlier for more efficiency. I'm doing this by using 2 coroutines, which are started in the function above. Right now i'm introducing a delay of 1 frame after every 50 searches so that it doesn't run synchronously
however, if it has to search more than 50 neighbours, then i don't get a response at all
it always returns empty
The problem here is, you start an async task (I guess because of the name) but immediately return your res which is a empty hex list, right?
yeah I think so, but I don't exactly know how to solve for that
make your findshortestastar async itself for example
and then? won't this still need 2 frames and thus not return anything on time?
The problem is, you want a) something in time, which would be mainthread, but that would block it but b) also try to use a coroutine which can always take longer than expected
You gotta rethink your loading I guess.
well okay, actually, i don't have to wait for the answer I think. it only calls the function and doesn't need the route after that. the update function just checks if the route exists, so I could use a callback on the main async function to just set the route whenever it gets a result
Is this like being called on ONE list or on multiple? Where do you use that return value?
Rather than both algorithms being coroutines and having messy logic coordinating them, one approach is to only have one coroutine that acts as coordinator, each frame executes a small chunk and if either algorithm succeeds, signal the other to terminate; if both still pending, yield for next frame.
Or alternatively, you could really look into running them on separate threads.
so, I have a tilemanager which handles clicks and then uses those to find paths between the tiles the player is standing on and the tile clicked
the return value is just stored on a value in tilemanager, which is the read on update to use a linerenderer and draw the route
And you got any performance issues with it yet, why you want to call it two times?
so I don't have to await the value, I can just make the whole function async and then set the value on the tilemanager with a callback so I don't have to wait for it
Yep, thats what I would do, if you do not need it in realtime. Just let the list be empty or the last result until you get a new one from async and in callback do your list path line renderer whatever thing ๐
yeah I got performance issues when I just had one sided A*, because if I were to try to get to a point that was blocked off it would check the entire board before realizing it couldn't make it there
so it would lag out for a couple of frames
that sounds like you gotta refactor your actual pathfinding maybe? Instead of trying to chunk it down to smaller parts of the same code? I dont know your code tho ๐
in theory this should work, but it still doesn't function if I have to check more than 50 neighbours? the problem is probably somewhere here but I'm stuck on what is causing the wait
int count = 0;
while (current != end && checkedHex.Count < priorityQueue.Count)
{
count++;
current = FindLowest(priorityQueue, checkedHex);
checkedHex.Add(current);
if (current != end)
{
priorityQueue = checkNeighbours(priorityQueue, current, end, pointers, out pointers);
}
if(count % 50 == 0)
{
yield return null;
}
}
as far as I know there aren't many good ways to find if a position is reachable in the first place without checking everything, so this seemed like the best solution. the pathfinding it self works perfectly
Ever thought about using navmesh?
i have, but since it's a homemade hex grid and I've recently learned about A* i wanted to make it myself
So what if you put your pathfinding in full async code, like a Task.Run() method that actually runs not on the mainthread, maybe that helps already
Ah got it, good approach and attitude ๐
why thank you
Well the wait is just a big code check that is blocking your mainthread. If you use the task system, that might already fix your blocking
i did try doing that as well but I honestly just couldn't figure it out
Ultimately your problem is just having a CPU bound chunk of code that takes longer than 1 frame but you don't want it to block main thread and affect FPS, so you either spread it out to many frames or run it on a separate thread.
yeah exactly, but the spreading out over many frames doesn't actually work currently
Here's what I would do.
But there are also other issues like "deciding how much work to do per frame" which will have disproportionate effect depending on how strong the client machine is.
Just using a Task is not making it take away from mainthread. You actually gotta call Task.Run() with all its code callback stuff to be on another thread
That might help you: https://blog.logrocket.com/performance-unity-async-await-tasks-coroutines-c-job-system-burst-compiler/
If you are doing the separate thread route, you might also be interested in Burst and Job system.
๐
alright! I'll do some research into that more then, thanks a lot anyway
There is an example a bit lower on that page about IntensiveTask which they use to run on an extra Task, that might be your way of handling it ๐
If you are using Burst you pretty much have to rewrite your code from what I can see; but on the other hand, the performance gain is incredible (I benchmarked CPU Gaussian blur and using Burst was 200x speedup) so you might not even need to multithread or deal with all these splitting frame shenanigans anymore.
so what am I doing wrong here?
you don't actually need to know anything special about coroutines or IEnumerator to understand what is going on.
my first question for you is: in this snippet that I am replying to, are you calling FindShortestAStarAsync?
Hi everybody, I have a problem where destroying a gameobject with a mesh filter and mesh renderer will also destroy the mesh renderer materials and mesh filter mesh references of the original gameobject.
Meaning I have a gameobject A, use it to instantiate gameobject B. I destroy B, and after that, gameobject A has no mesh and materials anymore...
How can I avoid that ?
OK, to answer my own question, the problem seems to come from the trilib asset I use to load assets dynamically. It seems to destroy the reference itself when the gameobject is destroyed. So cloning the references after I've dynamically loaded them fixes my problem. Quite peculiar...
At the moment, you are just doing your AStar twice... You need to redefine the Goal, the FScore and the reconstruction of the path. Also, you should look into how many node you expand before doing anything else. I'm pretty sure you will not gain anything from doing an expansion from both side. In fact, it will probably be slower. If you were doing a Breadth first search, you would gain in performance, but not with AStar.
If there is no obstacle, you should get to your target in a line.
Why do you want to start form both sides so you can know if there's a faster path? They would both reach each other at the same time when you could do it once and receive the same results
So I'm currently in the middle of overhauling a game and expanding its scope. At the moment it's pretty costly to create new items (entities) for the game and therefore it's slower to produce more content. I analyzed why that is and determined three main problems:
- The systems in my game are too dependent on what type of entity it is
- Some systems require type-checking to know what entity scripts to add and remove
- There are too many systems that are dependent on the entity type
- Adds onto the expensiveness of creating new content
- The entity scripts can have different methods that help solve 1 and 2, but not completely
Any thoughts on reducing dependency on type-checking?
just like in ECS, think of an entity as being a single type, with fields that can be interpreted differently by various behaviors. but every entity has the same fields. here's an example
class Entity {
string name;
int cost;
int secondaryCost;
int value;
int range;
int positionX;
int positionY;
}
okay, let's say you had a coffee machine that says, "reduce the maintenenace cost of all adjacent machines by 2"
you'd stuff 2 into value*
you'd stuff the adjacency of 1 into range
what if it's an item "extra large back of beans (makes 60 cups)"
stuff 60 into value
bUt pOsItIoN iS uNuSeD fOr iTeMs
so. what.
now you have 1 entity type
it's up to you to interpret the fields how you want
you can make a very, very simple class hierarchy
but when you subclass entity to implement something special, you don't need to add more to an entity's fields, which is all you're going to be interested in anyway. you're going to declare a property like adjacencyRange and it will write to range
or int numberOfCups => value;
does that make sense?
here's other way to think about this
in ECS, systems are functions, and entities are function arguments
every function can take the same set of arguments. but it's up to the function to interpret them
some systems require type-checking to know what entity scripts to add and remove
this sounds like a different kind fo flaw
- There are too many systems that are dependent on the entity type
- Adds onto the expensiveness of creating new content
use LINQ's.OfType<T>on lists. don't overthink this
@dusty wigeon @native nebula
As I tried to explain, the A* pathfinding algorithm is already very efficient. The problem arises when we try to reach a point that is unreachable. The algorithm with exhaust every. Single. Location. before realizing it canโt get to the point.
Because we know that if a point is unreachable, their areas donโt connect, we can say โin most cases these areas arenโt equalโ, so if we run the algorithm twice from both sides, if either of them returns that itโs impossible, we can instantly stop the other algorithm, which is more efficient. But only if it can run both ways in parallel.
If there is a route found, we can use the double algorithm to double check that we have the shortest route and just take the shortest of the two.
THAT is why Iโm trying to solve it this way
Example:
Say you are the green circle. You want to move to the red circle. From which starting point do you get a faster result?
this is true but only for this case.
In the case where it's more evenly split it will be faster/more efficient to only do one
aye, this is a catch 22: there is no way to know which will be faster until you try to run BOTH. You can pick one at random, at have a 50% of picking the faster. Or, you can run the both, which will make the faster one take twice as long to run.
now if you know heuristically in your game this case is more common, then you are right, this might be an actual optimization
Even then, if it runs in parallel youโll still save a slight amount of time. The only case where you wouldnโt should be when theyโre exactly equal
So itโs always more efficient to run both
But only if they can be done at the same time
well no, not necessarily, not if your CPU/threadpool is already saturated
so I mean, I think you have a decent idea here, assuming certain conditions are true
but I'd also guess that there are probably lower hanging fruit than this? ๐ค
Maybe? I honestly couldnโt find anything online
how big is this grid?
Anyone herecan guide me on the best workflow to implement collisions on a player controller in a 3D enviroment ? Why was wondering if its with capsulecasts and not allowing the player to move in case they hit something or if there is a better way
Considering I would have to have capsulecasts in 4 directions
So likeโฆ a collider?
well I have Box Collider component, does it fire an event or something or does it stop things from going through each other automatically
Having a class "Character" or "Entity" as a God class is something that will always happens. That being said, you should definitely try your best to divide the class in smaller chuncks. One way to fight this is to follow the Single Principle Rule. [1]
Alright, that being said. What can you do to refactor your code ? Unfortunately, most of the time, the only answer you are going to find is: You just need to divide your class ! But, having suffer this situation a small number of time, I can tell you that you can do more than that.
First of all, you most define the context in which the object act. Those context are called Bounded Context [2] and come from DDD (Domain-Driven Design) which is a practical way of structuring your domain/architecture in OOP (Object Oriented Programming). In your case, that would be the system in which the God Class interact. Something like an Inventory System, Animation System, Loading System, etc.
After, you take one context and you try to isolate it. Only one, this is important otherwise you will lose yourself rapidly and will break your whole project. The first step to isolate the code associated to your context inside your God Class is to create an interface that regroups all the function associated with the system. The second step is to create a bridge [3] between your class and new object that will be use to contain every method/data that is link to the given system. Now you have an object with all the data and method extracted, but you still are pointing to your God Class... (I'm out of words/time, if you want more just ask me and I'll write the remaining later)
[1] https://medium.com/@carlos.ariel.mamani/the-god-object-or-god-class-anti-pattern-bfb8c15eb513
[2] https://martinfowler.com/bliki/BoundedContext.html#:~:text=Bounded Context is a central,being explicit about their interrelationships.
[3] https://en.wikipedia.org/wiki/Bridge_pattern
It stops things that care about physics from going through it automatically
Rigidbodies and CharacterController
well it does work if I add a RigidBody to my character but it shakes uncontrollably if you are hitting something and not letting go of the key
Perhaps its best if you look up some simple Unity tutorials for a character controller
Those often show the best practices
Just stop if your FScore is over a threshold. Can also stop after a specified time or after a number of hex visited.
Yeah alright, those are probably the simplest solutions, if a bit limiting
Itโll do for now
If it's unreachable, the A* algorithm should be able to detect that. if you have some terrain that's seperating the end goal and the start goal, if you have checks for blockers then it's fine. Doubling the algorithm won't be more efficient that way
i think i showed you yesterday but that's what i have atm
What exactly do you mean by that? โIf you have checks for blockers?โ
this is fine then
the issue is reducing other systems' dependency on checking the entity type
Does your A* algo. check if the next tile is "walkable" ?
After, you take one context and you try to isolate it. Only one, this is important otherwise you will lose yourself rapidly and will break your whole project. The first step to isolate the code associated to your context inside your God Class is to create an interface that regroups all the function associated with the system. The second step is to create a bridge [3] between your class and new object that will be use to contain every method/data that is link to the given system. Now you have an object with all the data and method extracted, but you still are pointing to your God Class... (I'm out of words/time, if you want more just ask me and I'll write the remaining later)
So what you're essentially saying, is to treat the systems as nodes and the class as a large parent node. The large parent node will have bridges, or paths, that point to the systems..?
you could also try a flood fill, maybe?
Iirc thatโs slower than A*
it is
Iโm trying to improve it
flood fill one of the two separated terrains, if the start and end goal aren't in that flood fill, you know they are unreachable
why is that bad?
you have to do that work somewhere
somewhere, somehow, there is a type
you can use the type hierarchy to make this simpler
it becomes expensive to add new entities
or place the functionality that is calling .OfType inside the type itself
how do you figure?
expensive in what sense?
can you give a concrete example?
Expensive in terms of code to write and time taken to write that code.
if you have a lot of switches that go through a dozen types
sure i have a notion doc. i wrote up today analyzing some of this
I mean, since Iโm already precalculating all the neighbours I might as well count how many connected points are in their respective chunks. That way I donโt have to calculate anything. I can just compare the amount of points in the chunks to see if theyโre in the same area
you probably want ot migrate that behavior into the type itself
that's what i determined too
for some of the properties at least
for example, if you have something of rht eform
if (target is CoffeeBag coffeeBag) {
} else if (target is Item item) {
} else if (target is GrassTile grassTile) {
} else if (target is ...
yeah
is this generally for rendering code?
or for game effects?
Current Process
-
Create new entity script (ie EntityChair)
public abstract EntityChair : EntityBase { void Start(){ } } -
Complete EntityChair script
Basic Needs
void Start(){ SetEntityName("Chair") SetEntityZIndex(2) SetEntitySprite(pathToSprite) }EntityChairs can be rotated from the player with different sprites
void ChangeSprite(){ if (EntityRotation == 0){ SetEntitySprite(pathToWestSprite) } if (EntityRotation == 90){ SetEntitySprite(pathToNorthSprite) } ... }EntityChairs could also be connected to each other
void CheckNeighbors(){ if (myTC.Neighbor.west.GetComponent<EntityChair>()){ SetEntitySprite(pathToWestConnectorSprite) } }
@undone coral
yeah
so for rendering code
use interfaces
for example ITileHasDirectionality for tiles with directionality
No, not all. The end goal is to get to architecture with bounded context. At the end, you should have multiple class that represent each context. That would be an Actor, an InventoryHolder, a Damagable, a StatisticHolder, etc. Then your systems interact with each context that it needs.
so you'll check that type, but not by an exhaustive search
rendering problems are very often solved by interfaces
this is a Good Pattern
essentially the current process is this:
- Create new Entity script
- Initialize properties for Entity in that script (including specific, special methods)
- Integrate new entity into other systems @undone coral
usually i advocate against using interfaces (they typically have 1 implementaiton)
yeah
the integration you can simplify using interfaces, since you're really talking about how many objects are usefully simulated in a type hierarchy, but the "rendering hierarchy" is very different
i did have interfaces at the beginning actually
for example ITooltip
i had stuff like IEntityName, IEntitySprite, etc.
so if you want something to show a tooltip, it seems natural to use an interface fo rit
since you can hover over so many things
yeah, i mean it's an art to reduce it to the fewest interfaces you actually need
i wouldn't necessarily do it that way
th einterface should be the way it is rendered
not just a way to share a property
so like ITileView versus an ICharacterView, and entities that ordinarily would implement those interfaces could have an IInventoryView for when those entities are in the inventory
so instead of your tooltip code concatenating together the IEntityName.name and IEntityDescription.description
declare interface ITooltip {string name; string description;}
Keep in mind the way you are currently doing it (coroutines) they aren't actually running in parallel.
once you realize how to combine them, you can
So ITileEntity would implement tile properties, ICharacterEntity would implement maybe some tile properties, but more importantly AI controls

stick to its traits, not to recreate a type hierarchy
gotcha
like ICharacterRenderable... like maybe a Barista and a Plant only have Entity as a common ancestor
but they both are rendered as animated sprites with positions
that may change over time or whatever
so your rendering system would want to be able to query for all the ICharacterRenderables and do that all in one pass or whatever
Yeah Iโm aware. Thatโs what I was trying to figure out before
heuristic game AIs are like, a whole different beast, especially for simulators. usually all of that code is authored separately. if you have some kind of really abstract approach, I can see how you could do
interface IAI {
float activeValue { get; }
GameAction[] availableActions { get; }
}
with many things returning no value or an empty array of actions
this is really hard to do
so a GrassTile : Tile, and Tile : Entity
Yeah so if you aren't going to multithread them, then this optimization would be pointless because it effectively halves the speed of each algorithm.
that's still fine
that's how you have it right now i think
that's a Good Idea
it's when you have something that has to look like a tile
like a coffee spill
but is actually something else - it's not a Tile
do you see what i mean?
tiles and entities
Honestly if you are hitting performance bottleneck, I would really suggest look into Burst, unless what you are doing is really not Burst friendly.
hi, i'm having a problem with AI. When i record a video of the unity3d screen with a screen recorder software the AI choose almost always the same strategy. what could cause this? a fixed seed?
What AI are we talking about here? Artificial General Intelligence?๐
i think the problem is not related to the AI algorithm
because i get that issue when i start to capture the screen
There's not much we can help you with without knowing the details.
So it's machine learning stuff. In this case you better of asking in #archived-machine-learning
ok
Is it possible to combine skinned mesh renderers?
I would like to have my weapons "baked" as one draw call after they're customized with attachments.
Is that sort of thing possible?
good luck with your materials though... ๐ค
Does this apply to skinned mesh renderers as well?
I got one material for the whole game ๐
This is for meshes
SkinnedMeshRenderer is a renderer which renders meshes
then you're fine
the accessory meshes would need to be vertex weighted too - you might have to do that in code, though It's probably possible to do it ahead of time, not sure.
Honestly I wouldn't bother with this though it's probably not worth it
Oh! Ive already weight painted them.
Why is it not worth it?
how many of these weapons are actually being rendered at once?
It's probably not a huge performance gain
Did I mention it's on mobile? So even a few draw calls make a huge difference!
So I have 10 players with their weapons
Without mesh combining its too many draw calls, with all the weapons and their attachments
How do you expect these objects to move and rotate(or even just exist) individually if you combine their meshes?
What do you mean? They will be separate objects for each player? For example rifle A and its attachments will be "baked" to b one object, rifle B will get the same procedure. But rifle A & B are still separate objects.
So player A has rifle A, player B has rifle B, and so on
Does that make sense?
So you want to combine a regular mesh with a skinned one..?
No, my guns with all their attachments are skinned. All of the attachaments are rigged with their gun. So I want to combine skinned with skinned.
The gun rig with the character rig?
No. The gun armature has a gun object, and all of its attachments as separate objects. I want to combine meshes under the gun armature.
For example:
Rifle armature A
-gun mesh
-suppressor
-scope1
-scope2
That might be possible, but would probably require some intricate coding.
I see.
Google seems to provide some results for combining skinned meshes.
Yeaaa I saw some paid assets, I wanna avoid those.
That being said, I'd agree with Praetor about wether it's even worth it.
If it's something static like a gun, I'd probably use regular mesh renderers for everything and let dynamic batching combine stuff.
I think it'll take some time, but the performance gain will be worth it. Because I already have so many dynamic objects in my scenes
If I were you, I'd check the profiler. Honestly, skinned meshes are way heavier than a few render calls.