#archived-code-advanced
1 messages · Page 7 of 1
i'm a little confused because the texture format doesn't have alpha right?
so why wouldn't it be full white
did you mean TextureFormat.ARGB32 or whatever?
i'm also not sure if unity reads pixel data into RGBA32 regardless of texture format, or if it gives you the texture bytes as is
you're at the start of a long journey
which specific reflection probe setting? you mean if you turn off reflection probe use in all your mesh renderers?
at least in HDRP, there's a native call early on during camera rendering (the culling step) that determines if a visible mesh is influenced by a reflection probe, and thus the reflection probe needs to be rendered
i assume it works the same way in URP because it has to work that way for all probes
this is regardless of whether or not it's realtime or not
if you have a realtime / on demand / on enable rendered probe, look carefully in the hierarchy to see if the flush is occurring during to the probe's rendering
essentially because the probe's camera sees geometry that is eligible for batching
srp batching is normal, i think unity writes about the approach extensively
there are certain settings that can put you in worse jeopardy than others
as background the reason i know all this stuff is because i was diagnosing an issue with reflection probes in a project of mine that sent me deep into the source code for this stuff
that concluded that there are bugs in the unity culling code you sometimes have to work around
All I have is a single baked ref probe
so it's very possible you are encountering a real bug - it is probably not culling probes for you, so if you have X more than N in your scene, for example, where N is the "optimized" limit in URP for probes, it has to choose N of X probes to use during rendering (blending) for an object, and this choice might "jitter" between even nearby objects, which means that they will appear to need their own rendering command instead of many objects sharing the same rendering command (i'm not going to use the word batch or draw call here because that's even more confusing, with legacy baggage)
That causes SrpBatcher.Flush to take 8ms
okay and when you turn the probe on and off during playmode (you don't have to mess with the mesh settings)
does srp batch flusing go away?
the features probe blending and box projection here may also cause distinct render commands
and do you have a blend distance set on the probe?
maximum two of the probes
so N = 2, but you only have 1 probe
it's possible that there is some weirdness with 1 probe
srp batch flushing might be a red herring btw
Dont know about turning it on and of Im mot at my pc anymore sadly. I will try tomorow
okay
like sometimes the accounting shows up in weird places
if it's taking 8ms more CPU time to use a baked probe than not, that's weird
however, that doesn't necessarily mean there's anything wrong with the probe
do you only use Lit & shader graphs you've made yourself?
srp batch flushing taking a while is just saying that suddenly it cannot optimize many objects sharing the same render "command" - but it could also mean that some scene configuration changes where you are NOW eligible for srp batching whereas you weren't before
that's what i mean by red herring
and it may be in your game, you use GPU instancing (which isn't compatible with srp batching)
I dont I know about that
and just because you check the gpu instancing box doesn't mean it will use gpu instancing
okay
for example, there might be a shader that samples the reflection probe
and it may interact weirdly
Thats the shader I made
did you build it in shader graph?
A what I call a unlit with environment reflections
No I dissasembled the whole brdf structure and SampleGI method
there's no such thing as unlit with environment reflections
at least if you want to use reflection* probes as they exist in the engine
you can always take that cube map and funnel it in instead
this is most likely to make your problem go away
you mean you are doing this in code and not shader graph?
I could do try that too
Yep
okay well try using the cube map directly
and don't have a Unity reflection probe at all
there should be a CG include with how to sample the reflected cube map correctly, or you can look at the shader graph source to do that
it's something idiosyncratic
@livid kraken otherwise i understand the appeal of authoring an uber shader but there are also lots of pre-existing ones, some free on github some on the asset store
that someone has already relentlessly optimized
and those typically have you slot in the reflection cube map directly
Thing is this shader was birthed from a joyrney of optimizing a scene for the Quest 2
It samples a globally set texture array for the atlas with the slise being baked into a exrtra component of the uv to minimize attribute data
and i think the quest 3 is massively delayed
I dont really want to create multiple materials for the env so that they can sample different cubemaps
i've seen these uber shaders usually have like 4 cubemap slots
I know Im sampling it correctly since I "yoinked" the sample from the lit urp shader
and like the 4 box centers of where they're supposed to influence
they like... loop unroll that whole thing
i think as soon as you add the cubemap slot you'll be fine
Its far from a uber shader. If anything its a very narrow specific shader for the environment of a specific quest 2 experience
I should mention it runs fine in the actuall scene
Frame time is 4 ms
Heyall is there any way I can make Unity allow me to create some objects on another thread other than it’s main? I’m building an editor utility that creates thousands of textures and other assets and it would be nice to have these tasks leveraging the full potential of my cpu
In my test scene with 4096 cubes is where the problem starts
there are a lot of variables here
have you looked at the shader that comes with the Steam lab demo scenes in unity?
some of the interesting stuff they did, which is as old as 2016, is implement dynamic resolution
and stuff like that
Fun fact the same dynamic resolution algo runs in Alyx as well
also you saw my note about ETC2_RGB not having alpha?
I recently installed a more aggressive linter and it's complaining about my use of public members in Unity. What's your convention/solution to the following?
public GameObject MyGameObject; // S1104 Make this field 'private' and encapsulate it in a 'public' property.
A: Disable this particular rule and live life to the fullest.
B: Use a manual property and give it an inspector name (or not):
public GameObject MyGameObject { get => _myGameObject; set => _myGameObject = value; }
[SerializeField, InspectorName("MyGameObject")] private GameObject _myGameObject;
C: Use the auto backing field with the field attribute:
[field: SerializeField]
public GameObject MyGameObject { get; set; }
D: ??
(My complaint about "B" which seems to be the convention is errors are cryptic because they put out generated field names like k__BackingField__001__GameObject)
I typically use B or C depending on if I need custom getter/setter implementations
or just [SerializeField] private GameObject x; because most of the time you don't need any access from outside the class
And if you don't? Like, for a display object that might have dozens of TextMeshProUGUI objects where you're 99.99% just setting .text or something insignificant? This would represent a pretty substantial addition of boilerplate
then this:
[SerializeField] private TMP_Text nameLabel;
Hm, that's probably the best approach. I think it jives best with limiting the public members anyway. Most of my objects on scripts "are" private (but I've just left them public to set them easily in the inspector). I could change them to private and serialized without any trouble. I can't remember why I didn't do that as convention in the first place..
on one hand, adopting a new analyzer/linting tool feels nice but on the other hand......
D: since you're using vs just uncheck the warnings and messages on the error list window and live on. that's what i do lol
Heh.. I generally try to TWOE though so.. I mean, especially if I'm going to be bringing on another dev in the next few months, I want to at least be able to say "here's our standard analyzer, use it, don't check in things that fail it"
I shouldn't really pick and choose which rules I live by if I'm gonna pay someone else to live by them 🙂
what does TWOE mean??
this linter doesn't work super well with Unity though unfortunately, I suppose I'll have to configure some stuff
treat warnings as errors
linter thinks all unity messages are unused :p
yeah that's annoying. i usually just stick with unity tools for vs, it works really good for me
I wish you could do something like a C #define
#define inspectable [SerializeField] private
I don't think that's possible in C# though
that's an interesting idea
i'd be leary of adding my own #define like that to a codebase though, but.. i like the idea lots
that would be practical, but hiding access modifiers under a macro is a little devious, imo
i mean, I think it's not really hiding it since he's making a new word inspectable
if it is well understood that inspectable IS an access modifier than its fine
but yeah, I can't really put my thumb on why I think it would be a scary addition, but... it feels scary 🙂
While we're sorta on the topic - anyone know how to configure various rules of a given analyzer? Do I just have to supress them ione by one in a project suppression file?
that's also what i feel and what i was trying to convey, it just doesn't feel right
It depends on the analyzer, for example with IntelliSense you can do it in a file as you said but you can also use #pragma to locally supress warnings and messages, as well as change their severity.
I actually was looking at that earlier today to try and supress some errors I was getting on IntelliSense in a .hlsl file even though it was all fine: it just didn't knew the unity macros. VS support for hlsl is really bad imo
Yeah I'm going to have to do this globally since my new analyzer is complaining about hundreds of Awake/Update/etc messages that are "unused". I always have to google up the syntax on these global suppression files
[assembly: SuppressMessage("Roslynator", "RCS1213:Remove unused member declaration.", Justification = "<Pending>", Scope = "module")]
I think this is correct and hits all the projects in the solution
(ie - scope = "module")
I've never done it before so I can't help. Also never heard of Roslynator, so yeah good luck
heard good things about it: https://github.com/JosefPihrt/Roslynator
almost no impact on my server-side solution aside from a few hundred whitespace complaints (like an extra space at the end of a line)
lol at that comment btw
I started coding on a very basic IDE (Codeblocks), so all this vs suff is still pretty new and overwhelming to me, that's why i usually just stick with intellisense.
Also i don't mind "bad" code, I usually just code by myself, so no one will criticise
I'm a VS fanboi. The only things that make me mad about VS is blazor/razor tooling issues and bug reporting/handling by MS
You should be as aggressive as time permits towards bad code since.. even if you're only doing it yourself, you'll come back to it later.. plus, having really robust but not overly clever code means A) lower incidence of bugs and B) bugs you do have are easy to find and fix
Well if its unreadable and you have to change something about it it sucks
(imho)
Yeah, since I changed over I was never able to go back, I also love it
I do be being a rider boy
You're completely right, it is me who's knowingly doing things wrong
hehe
well i also did qualify it with "time permitting"
I did a game jam recently where the code i produced was embarrassingly bad .. but.. you know, game jam things
i understand...
Does anyone here have a preference between
if (myObject != null)
{
// do something
}
versus implicitly casting to a boolean
if (myObject)
{
// do something
}
?
Assuming myObject derives from UnityEngine.Object. Of course, while there could be valid readability/design preferences here, I'm also trying to figure out in the Profiler if there is a performance difference between these two options. But I haven't been able to discern anything meaningful yet. Thanks in advance if you weigh in!
The performance difference in the above is insignificant.
If your object is implicitly a boolean (like, if it could be named isJumping or hasObject or doesAction) then it's fine from a readability perspective to if(isJumping), but it sounds like you're using game objects, so I would never use an object like that since you're likely to step in poo
(because UnityEngine.Object has overloaded operator== and it doesn't mean what you think it means, typically)
I know it doesnt have alpha. This is why Im perplexed by the fact that the preview in the editor is displaying a full white alpha.
Also, in general, build first then profile. The real hits to performance in your game are not going to be in trivia like this.. they're going to be situations where you FindObjectOfType in your update methods, or Instantiate() when you don't need to, or have deeply nested prefabs, etc. All that low level math stuff is like.. many, many orders of magnitude less significant.. like nanoseconds of difference, even for several thousand/million iterations
there's essentially no differece between these. See:
https://github.com/Unity-Technologies/UnityCsReference/blob/dcf29f6d96a9708d7a7350f92772bb75ca3befbf/Runtime/Export/Scripting/UnityEngineObject.bindings.cs#L392
and:
https://github.com/Unity-Technologies/UnityCsReference/blob/dcf29f6d96a9708d7a7350f92772bb75ca3befbf/Runtime/Export/Scripting/UnityEngineObject.bindings.cs#L98
I do prefer the != though because the other way feels a little too C/C++ "truthy vs non-truthy" values for my blood
Thank you both, super helpful
How does Canvas.targetDisplay behaves on a WorldSpace canvas that moves across displays?
"For Overlay mode, display index on which the UI canvas will appear."
so it has no effect for world space ui
I'm having problems with the sprite revolver
I can't "animate" the label hash
when I try to animate it, it animates the sprite key instead?
I just switched from 2020 to 2021
what can I do to confirm touch input simulation is working?
Is there any way to execute my code before unity engine initializes opengl/d3d device?
what is your objective?
To initialize Steam API
i think you can just do that as normal
you can use script execution order or runtimeinitializeonload to do that early in your game
Of course I can but if I do it after that, Steam overlay doesn't appear
And script execution order may doesn't work because the graphics API is initialized before executing MonoBehaviour
I don't think any steam API relies on you calling initialise at some insanely early point
the steam overlay appears for me
what exactly do you mean?
you don't even need steamworks installed for the overlay
If you're using Facepunch.Steamworks you have to make sure you're also calling Steamworks.SteamClient.RunCallbacks(); in Update
the graphics device initialization has nothing to do with the overlay
steam already has special handling for unity games, it is aware of them
I'm using it with FacepunchTransport and this script is doing it
I also thought like that but the document says it has relationship: https://partner.steamgames.com/doc/features/overlay
If I play the game launch from Steam, yes it does work but, when I launch the game by clicking exe directly, it doesn't work
obviously
yeah you have to launch it through steam
I hope so but during development, it is quite a hassle to upload the Steam every time that I want to test my client
You can replace the files in your steam directory, it'll just require you re-validating the files when you want to sync back to steam
you might want to just copy and paste your game into the steamapps directory
You may want to force-reopen it through steam for players in the final build
if (SteamClient.RestartAppIfNecessary(AppID))
{
Application.Quit();
return;
}```
jinx
if you add your exe as non-steam app, and run through steam you have overlay
is this helpful
Maybe I should make a new Steam build branch for testing
yeah i use a testing branch
One of the reasons I don't want to upload to Steam build to test is there can be corrupted builds uploaded during development
Anyway, thanks for your help @undone coral @austere jewel @deep peak
ok
What could be causing AddComponent to simply not work?
The code works fine except for the last line, it's simply being ignored
What’s the instantiate for?
it instantiates the new gameobject ...
no, just one. the first line declares the gameobject and creates a variable referencing it
the second line instantiates it in the scene
it's the same gameobject though
You are creating two game objects there
Calling a GO constructor already adds it to the scene.
You're doing it
Your first line does that
new GameObject()
Anybody familiar with this type of stacktrace?
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Module "System.Runtime.ExceptionServices.ExceptionDispatchInfo", in Throw
Module "System.Threading.SendOrPostCallback", in Invoke
Module "UnityEngine.UnitySynchronizationContext+WorkRequest", in Invoke
Module "UnityEngine.UnitySynchronizationContext", in Exec````
It doesnt help me at all to know which script or method is being thrown from
so far i understand an index was out of range , and the variable out of range was called index... but nowere i see where is the origin like i see in most stacktraces... why is this?
It looks a bit like there's no symbol information at all
More info required! Where are you seeing that stack trace?
are you using the job system?
no
I get it through sentry SDK
maybe it's their fault
No idea what that is ¯\_(ツ)_/¯
Are you accessing arrays or lists in the method you got the error from?
I usually get thos when, well, the index is bigger than the length of the array
the thing is im not 100% sure which method comes from due to the lack of information of the stacktrace but if it is the one I think this comes from inside of a Unitask, could that be the reason?
and yeah that method goes across lists using for, and one of them i use 'index' instead of i which i use normally
okay but now i got another exception is not inside a unitask and has the same structure
this must be the sdk's fault
System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.
Parameter name: value
Module "System.Runtime.ExceptionServices.ExceptionDispatchInfo", in Throw
Module "System.Threading.SendOrPostCallback", in Invoke
Module "UnityEngine.UnitySynchronizationContext+WorkRequest", in Invoke
Module "UnityEngine.UnitySynchronizationContext", in Exec```
If you are usin extensions, then i cant help you xD
yeah sorry, i didnt think it was the exception reporter
well... im still not sure but seems like
the sentry sdk probably has bugs on unity
yeah it would not be the first time
i just wanted to know if any of you felt that stacktrace familiar
you can try breaking on the exception and checking if it has an InnerException set
and it will show you what the real issue is
i don't think sentry can help you much in unity though, it can't instrument the code can it?
for example they claim "Line numbers for C# exceptions in IL2CPP builds." which is dubious
this doesnt work in Diagnostics neither
yeah thats a big shit
but they claim they will make it available for 2020, and 2021 while unity said just for 2022
the team of like 1 person who does't know how to make anything in unity at sentry isn't going to know how to do anything
i guess what i'm saying is that it's not reliable
i understand they SAY they will be an APM but it probably doesn't work a lot of the time
not just line numbers but in general
well youre right, sometimes stuff fails but they have a team of 2/3 people working on the Unity SDK constantly
It's quite useful compared to Crashlytics or Diagnostics, just saying
same with the tracing... it's a very odd thing to promise
the stacktraces i've been getting are totally fine most of the time
but yeah sometimes shit like this filters
but as I said... they work on it constantly and i have someone to complain for 😅
also the dashboard is amazing
they're just making promises there is no way they can keep
does anybody know how it works? I need to get camera depth texture but there's always nothing
why do you need the depth texture? what's your objective?
i know what box you have to check, but you're still probably doing something wrong
outline shader uses scene depth, but it doesn't work with 2 cameras, because the node always gets main camera's depth
You should share the code that changes this intensity setting
If you don't have code, then it's maybe automatic (depending on what's on the screen), in this case ask in #💥┃post-processing or #archived-urp or #archived-hdrp
code: https://gdl.space/esaritexil.cs here is code or i got u wrong?
So the two Lerp might conflict hence the back and forth movement of the intensity.
Check that both can't run at the same time
Maybe by using else if? Hard to say, depends on what affects the chromatic aberration
hmm not sure in URP
visually it looks alr. nothing is changing instantly
Hello, does anyone know how to make an automatic login with facebook? I manage to make the user log in but I don't know how to save the AccessToken
what is your objective
Make that when starting the game, the player does not have to log in again, that the game automatically logs in
how are you currently using facebook to "login" to your game?
what is your game? (in one sentence)
the access token can't be used to "login" to facebook, that's not what an access token is
or what login is
are you trying to say
"i want users to be able to 'login with facebook' in a colloquial sense, and thereafter whenever they reopen the game, they are not prompted to login anymore" ?
Yes, I have done the login function
okay, well i think you're at the start of a long journey
you should probably use PlayFab, GameSparks or something similar for user accounts
you can use firebase for unity if you need a comprehensive solution for backends
And there is no other way to make the user not have to login again?
I already have a server in which I store player data (score, coins, name), but I use the id of his facebook account to be able to identify the user and that there are no errors
The game is not multiplayer, the only thing you can see is the ranking of the other players and the profiles of the game
what exactly do users log into then? in 2022, you need a redirect URI for your facebook app
what did you put in there?
i understand what you are trying to do and that you are looking for a simple solution
if any meaningful number of people start playing facebook will boot you if you don't do things right
i assume you are still running in test mode
the token facebook gives you, you can later query through an API to see what ID is associated with it. they aren't signed, but as long as you use the API, it will only return the real ID associated with it. the token is just an identifier, it doesn't encode data
does that make sense?
The facebook apk opens the app/web to be able to log in.
I can see its id and with it make Get requests to facebook to request the name and information that the user has accepted when logging in.I can see its id and with it make Get requests to facebook to request the name and information that the user has accepted when logging in.
okay, so what is your issue?
show them the login option if the token is invalid
you can store that token
That when closing the application, the user has to log in again
The token when closing the application is deleted, I try to save the token in a scriptable object but it is also deleted
okay
well there's your problem
you can try saving the token into PlayerPrefs
this was a #💻┃code-beginner issue, and in quintessential XYProblem form, your X problem was actually "how do i save things between app loads"
I will try to save in playerprefs, to see if it works for me, thanks
Hello! I am trying to do a map builder (imagine trackmania map builder), and I was wondering if some of you had some kind of link to tutorials or techniques to save the data, like position/rotation/extra data efficiently. Thanks!
You want to save data?
Well you can use json files...
I would suggest using Newton Soft if you choose this path. It's typically better than unity's JsonUtility
how does this code work? never seen it before
oh is it just if (weightedInput > 0) return 1, else 0
Ow that's some dense code lol
Looks pretty useful
Otherwise it uses the second value
that's very cool
Yes, like saving a map data and being able to load it back. If JSON is the solution then JSON it is, thanks !
bingo
how do i add weight to my randomization in unity?
i'm randomly spawning fruits out 10 options, but i want to be able to modify it so fruits later on in the list spawn more
Maybe more complex ways to do this, but create a new list with different amounts of the elements from the original list.
Easy
And of course would be more performant to not create the second with the original objects, but with some type of lightweight key that points to the original object.
Perhaps you could store the original fruits in a dictionary
And then use their keys to populate the weighted list
oh i might have come up with something else, maybe make a curve and then use the initial random number to get the point on that animation curve, then you can change the curve to have any weight you want??
i need to specifically be able to control it semi easily, and i feel like that might work
I realized that I made a better version, because the sorted requirement was annoying me
public int WeighedRandom(List<float> weights)
{
// modifies the collection
float total = weights.Sum();
if (total == 0) return -1;
else
{
float weight = 0;
for (int i = 0; i < weights.Count; i++)
{
float probability = weights[i];
if (weight == 0 && probability != 0) weight = float.Epsilon;
weight += probability;
weights[i] = weight;
}
float rngWeight = rng.NextFloat(float.Epsilon, total + float.Epsilon); // dodging zeros in the beginning
return weights.FindIndex(p => p >= rngWeight);
}
}```
hello guys I have blender scripts but I need want unity engine so I need my special binary files import export unity but how I need learn can anyone show me some example so i can look it up https://cdn.discordapp.com/attachments/497874004401586176/1008052746949251122/Adsz.png
how do you actually connect a random seed with procedurally generating objects?
in this tutorial they don't seem to connect the two:
In this unity3d tutorial i will teach you how we can easily create a simple seed based island generation system. We did something similar to this with our "Survival" tutorial series how ever we never made it seed based, This tutorial will show you the basics of seeded generation.
Join our discord server to submit your challenge entry!
Discord: ...
Sorry if this isn't advanced enough for this channel...Is there any way to hijack/override a method from another method for the sake of keeping code clean? Usecase: Text game. I'm adding "aspects" which change the way things in the game works. If I had, say a "darkness" aspect, that I wanted to hijack the room description generation method to change it to "it's dark in here" from within the aspect's code instead of the room's code. The reason is so that when I add the other [x] number of methods, the code within Rooms, items, and NPCs isn't absolutely bloated with "aspect" if statements and instead those are just hijacked from within the aspect code
you can do this in a clean-ish way by using an event bus (also called a pub-sub or message bus) that all aspects subscribe to and use it to pass a DataObject through all other aspects whenever an action happens allowing them to modify, delete or block it
if you prefer a "raw" way you can have aspects publish some events or delegates that you can inject handlers into (from the outside) which then modify the behaviour of the aspect
Thanks, I don't know a ton about event busses but I will look into it because it seems like the best way to go about this.
Because this seems like what I'd want it to do. Let me see if I have it right. Say I make another aspect, "Poison". Using event busses I'd be able to make it so if a food is poisoned, it'd poison you. If a weapon is poisioned, it'd poision who you hit. All within the aspect itself. Wtihin the food command it'd be like: "Eat { do eating actions, also alert all aspects that we're eating":, and "Weapons {do fighting actions, also alert all aspects that we're fighting}" then within the poison aspect I could be like "ope, the eating alert just got passed, let me check quick to see if it has the poison aspect attached to it. If so, we'll modify it to take away health at the end."
is there a way to revert to the old way of working with a sprite resolver
now when I try to animate anything with a sprite library, it chooses the sprite from the category that I animated with, rather than setting it to the equivelant sprite hash within the preset category
which isn't really helpful to me since I started using it like that in 2020 because I can have the same animation with sprite swapping depending on the circumstances
you're at the start of a long journey
you can look at the xmage or spellsource source for an example of how to architect these kind of games
I wanted to hijack the room description generation method to change it to "it's dark in here" from within the aspect's code instead of the room's code.
this is hard to do
you can't just ad lib it
if you wanna avoid a spaghetti code mess like hearthstone
the super abbreviated version of this architecture is that your game rules executing looks as much like a conventional c# program as possible... with the magic that the code is also data and can modify itself
C# isn't a LISP, so that's hard
in spellsource, my card game, which has a poorly implemented version of half of common LISP
an effect like All draw card effects discard instead looks like
{"type": "ModifySpellSpell",
"target": "ALL_CARDS",
"spell1": {"type": "DrawCardSpell"},
"spell2": {"type": "DiscardCardSpell"}
}
the reason this works pretty simply is - every spell / effect, if it were a conventional C# function, would have the same exact function signature
it's up to the function to decide how to interpret the function arguments, including possibly using none of them
Whoever at Wizards of the Coast did the code architecture for Magic Arena (and MTGO) has my pity and respect.
lol
I'm pretty sure the card engine needs to be a turing complete system
@queen stirrup so there are many discoveries along the way that you have to make. think of this like a tech tree:
in the Architecture tree:
-
Execution
Your game stack looks like your C# stack -
Pre-emptibility
Your game execution can be stopped, serialized, deserialized and resumed at any time
...
19. Algorithmic Content
You express your game content, like card text, algorithmically
20. Homoiconic Implementation
Your content format is both code and data
...
40. Function Rewriting
You can instruct your game virtual machine to replace a function anywhere or everywhere
i think if i could do it all from scratch, i would write the game logic entirely within lua
and render from its state
with a clear, demarcated API between the card game and wherever it is hosted
definitely some language like that - or ruby which can rewrite itself at runtime is needed
i'm sure the hearthstone people wish they did things this way, although Snap just the same hearthstone approach of a C++ backend
roblox has fairly primitive replication, but it is greatly assisted by shipping diffs of lua runtime state as a black box
i have no idea how hearthstone works but the mechanics of hearthstone are much simpler than MTG
yeah i had the benefit of starting with a codebase that was "Learnings from Xmage for Hearthstone"
it stands on the shoulders of giants
i met the contractors who do MtG Arena, who were selected because they had experience porting a lot of very text-driven board games
like they did many avalon games' mobile ports
anyway when people say they want to do code rewriting
i don't know, i just imagine the alpha centauri tech tree
they want to rush to air power, which is only 5 techs away, but default rules are you get techs from a lane randomly so you can't just
go for it
the default rules are more realistic. you fumble around learning 15 techs you don't need for air power
Sorry Doc you've gone off on a tangent now 😛
lol
@sly grove https://i.imgur.com/IbzHn6A.jpg okay, as you can see, Doctrine Air Power only has 4 prerequisites techs so can be reached very quickly, however in this game you can't...
(40 minutes later)
I have a project, I want to break some of the systems into separate code libraries so I can use them in other games and more easily update and so on. How does that work in Unity? 🤔
Thought of this conversation when I saw this: https://i.redd.it/jtx4eqqafih91.jpg Good reason not to allow this stuff. 🙂
Lolll this reminds me of when I was working with high school students first learning to program and you tell them "you can make the variable anything you want" and they start picking their friends' names.
so I have these SearchTreeEntries cached in a ScriptableObject
and if I create the ScriptableObject, it works fine
but the moment I recompile, even though all the data is there
it doesn't work anymore
and throws an exception
missing reference for some reason
Scriptable asset cant refer to scene objects proly that was your issue
no, unity creates an xcode project which you must then compile to produce your ipa
i know so how do i make an ipa file in xcode?
im bulding using windows but compiling using mac
will i ran to issues?
no, that should be fine
i hope so thx for the info
Hi there, I'm looking at some decompiled code at the moment and I've noticed that in this condition, the compiler has automatically recasted all the floats into doubles.
My understanding is that casting is expensive, is there a reason the compiler would do this?
Sorry for this being a more C#-oriented question
Check the IL to see if it's actually casting
It might just be the decompiler making assumptins because it doesn't know for sure
Think you're right there, thank you!
I had a question that I am unsure if anyone can answer but I have gotten to a point where I think the best I can do is just get more eyes on it.
I am currently working on a dungeon generator that involves a far more tiny keep algorithm idea. Basically i spawn a bunch of rooms, then I am trying to A* to make all the hallways. Right now the formation of the hallways works, but what specifically has just not made sense. Right now my cost function for the A* algorithm has a lot of extra workings in it. But one thing that has stayed constant is it increases the cost more to go through a space in my grid if its nothing then vs if its a hallway. So despite everything, I am really confused why stuff like this happens (red squares are just my debug fill in for what the world sees as hallways) (green squares are fill in debug space for what the game sees as being the room)
Would anyone have any idea why this is forming when I am encouraging the A* to go through existing hallways?
I can also show any code anyone wishes to see
I'd help you but unfortunately I've got no clue what your question is nor what I'm supposed to see in that picture
My apologies I can elaborate
Basically, the way my system works right now for what matters, is that i form a graph of all my rooms to determine what hallways to create such that you can traverse all the rooms for the floor in the dungeon
that system for making the path of the hallway is an A* algorithm
the hallways in this case are made up of red tiles mainly to show for myself in debug what the code knows are hallways.
My confusion has become that part of the A* cost function (determining the cost of moving to a certain tile) makes it in a way where it should cost less for any hallway to move through a hallway that already exists
Yeah i dont understand why when the cost function should make it such that a hallway would always prefer moving through an existing one, you get something like the above picture where it just goes next to it instead
So you essentially want to recycle paths as much as possible
Or in other words, paths which are 2 tiles wide are wrong?
correct and correct
that is why actually if i blow that picture up
you see a lot of cross roads like this
because its supposed to try to reuse as much as possible
Okay can you elaborate what your cost function does?
sure
Because if I'd implement this I'd simply use Manhattan distance as heuristic and then increase the node weight of all cells which are empty (but I believe you said you did this)
the cost function takes in two nodes. Node a, and Node b. Node a represents the current node on the path. Node b represents the node that we are checking to see what its cost would be if we added it to the path. Because the goal of an A* algorithm is to get from the start to the finish with the cheapest cost
It first begins by setting the base cost of b to its distance to the end, then it will increase the cost of b by a myriad of factors I have set up
the distance cost beginning is heuristic
they line up particularly in this order:
if we are trying to attempt to perform what i call zig zags (basically go diagonal) increase the cost (this encourages straight lines which are easier and make more sense, also makes turning far less common)
if we are too close to a room increase the cost (this is to give ample space between rooms and hallways
we then increase the cost of the node based on what type of node it is with the highest cost being a room, second highest being empty, cheapest being hallway.
that is all
Hey all, I'm having an issue with the unity standard assets. I downloaded the entire third person asset and I loaded the demo scene. I cannot get the mobile controls to work
I'm building targeting android and I have the game showing in unity remote
but its not reading or reacting to any touch inputs
I might be wrong on this but you might be cluttering your cost function a bit (people might disagree with me here)
If you want to discourage A* from going near room, can't you simply increase the weight of nodes near the rooms?
that is basically what i am doing
its just wacky because technically the nodes are per path
so for each hallway the costs are all redone
because they have a different starting and ending context
what may cost 5 in one hallway may cost 20 in another
That sounds normal
Gcost is the travel cost to reach this tile from the starting point
So it's normal that it is not the value when you start from a different starting point
right but regardless of that reset
it should still prefer going through hallways
the only thing i can think of is maybe it doesn't know its a hallway for some reason
but that wouldn't make sense given the entire other context of 90% of the time it works
I think your best course of action is to reproduce this issue in a small scene and go over the code with an debugger
i agree
do someone know how can i make my game moddable by loading a mod .dll at runtime?
and how can i make a custom API for modders to use
Hey, anyone out there have any experience with the material array in a Skinned Mesh Renderer?
trying to figure out why it changes the sort order of my materials
keeps swapping the slots
is it based on vertice order?
how does it decide what order to list the materials in the array?
It won't change order on its own. You probably have a script doing it
I should clarify
so when I import a model, the skinned mesh renderer reorders the materials
so 01_mat is in the second slot, 02 in the first of the material array
no scripts
trying to find any info on how that sort order in the material array is decided
and if there's a way to override it, as I need my 01_mat to be in the 01 slot
in Unity Metal, does a CPU and GPU texture point to the same memory?
e.g. if i request the gpu texture and the cpu texture for a RenderTexture, i might get different pointers but are they backed by the same buffeR?
because it is unified?
Guys, I have been trying to do something but I just can't seem to figure it out
Say I have an object that collides with the object in the image above at the red dot
So the collision is at the red dot.
How do I find the angle of the green arrow? It should be perpendicular from that object in the image
It's the normal of the collision
which is generally provided in the collision object
Though doesn't the normal give the direction between the collision point (red dot) and the pivot of the object that collided?
No
Oh. Thank you
But shouldn't the "rocket" be bouncing on the same spot then?
Or is my code wrong
I also tried pushBackDirection = collision.contacts[0].point.normalized
https://docs.unity3d.com/ScriptReference/ContactPoint2D-normal.html is what you want
Not what you're doing
How do I use it, ContactPoint2D pops up, but I can't write ".normalize" or ".normal" after it... I'm sorry I probably shouldn't be in #archived-code-advanced
Ah... I got it...
nevermind....
How do i implement a complex combo system similar to platinum games or DMC games in 2d ?
i can only think of a tree structure, where player click one attack button and then he has a possible combo he can move forward to
hi guys, found some really good threads and info about having using json in this channel
i was wondering if anyone... has a good tutorial or example i can learn from to do this...
similar to a card game where you have a card that has spells... i want to do something the same/similar
read data from json, use it to populate actions/spells in game
Hey, I just figured it out. Thank you vertx and Navi, I'm not going to ping you guys but thank you
This https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0 or use newtonsoft.json
yeah ive read this and other docs like it a bit, im not sure how to get data in my custom type even after reading this
Watch some tutorial then
Fsms are something you might want to look into then
im having trouble with the EventTrigger, i have a list of buttons dinamically created and in order to know which button the user has clicked i use
myButton.onClick.AddListener(() => OnClick(buttonID));
but with the EventTrigger i can't pass parameters
(I want to use onPointerDown and OnPointerUp, in order to hold and push multiple times)
I dont see how can i do this if i can't pass he 'itemID'
What happens rn ?
This seems valid
yes this is valid but i want to replace the onClick by onMouseDown
you can do something like this
Action<T> someThing;
void Foo(T param){}
void Assign()
{ someThing = Foo;}
so the user can tap and hold
but the problem is the EventTrigger doesnt allow me to send the button's id
tbh, I don't see anything wrong with this
proly you should elaborate a little bit, bcos I see no reason why your sinppet won't work
my snipet works, but its an onclick event
so it triggers when you make a click which is tapdown and lift finger
but, i need to tapdown... detect how long has been holding down... and decrease
Exactly
now the problem with this is, how can I pass a parameter to tell which button has been pressed?
can i use the PointerEventData?
to send it there somehow '
?
well yeah 😄
i can use the PointerEventData? oh i didnt know thatr
ah great great, i didnt know i could set custom info there, i thought this just holded info about the click event
thanks a lot
goodluck
they are just read-only properties
So you can pull out the id of your gameObject of which the event belongs to, and check on your side if that id belongs to which button etc
oh i see... I guess it picks the instanceID then
that sucks a bit but well... better than nothing
It doesn't, it's just a pointer to your object which the event belongs to... Whether you want to get the InstanceId or not it's up to you
I mean, you said they're dynamically generated which I assume they're instantiated... so InstanceID makes a lot of sense here
Unless you have your own id system, then use just that yeah
Hey idk if this question belongs here, but i'm somewhat new at programming and currently working on a game with unity. I was working on it just fine yesterday, mainly messed around with the level design, but when I opened it up today some of my scripts were encoded like this and I have no idea what caused it or how to fix it. Could someone help me out?
yeah i have my id system but you said these properties are read only so i cant use them correct?
you can get the reference to the object for sure, like anything else with UnityObject 😆
just read the doc that was linked
I should've worded it better, most of them are read-only.. so not all
goodluck
now that I think about it, you're too overthinking your simple issue 😆 but that's totally fine
how would you do it?
make a list somewhere to pool your buttons, static or not it's your choice. Add a listener that will execute a method with the id of the button for as it's param
the go from there, like you can do filtering and whatnot it's up to you
so when you're checking things, just check what's in the list
so.... Friday everything builds fine. Today I get to the pc, install a mandatory windows update and suddenly I can no longer build for android, getting this error : https://hastepaste.com/view/ZMRTj
What have I tried so far, Installing the android module again, complete fresh install of unity with the module, deleting gradle cache, making sure I have the correct keystore( its a debug key), updating java, deleting project library folder, doing a clean build
there are nasty bugs in 2021.3.3 - 5 for android builds, I believe they fixed this in 2021.3.6, what version you're using?
2020.3.37f1 LTS
should check issue trackers for whatever is in the build pipe
if there is a panic over that update youll just have to wait
well well well, the mystery deepens a fresh project on the same version does build
maybe library nuke?
Are you using the standard Unity android sdk, ndk and java sdk?
Yes
do you have Android Studio installed?
No
Try installing that and then use the SDK from there
But it was building fine last Friday I shoudnt need Android studio because windows updated
True, this error seems to come from a duplicate library somewhere, did your Java SDK update with the windows update?
Clutching at straws here but you are not the only one with this exact error
I had a pending jvm update that I did but after the build started failing
I can try and remove java, and all android modules from other unity versions on the machine
See if that magically fixes it
thats why I was thinking Android Studio, to take the whole process out of Unity
Ive done that in the past. Build a android studio project from unity and build out apk from the studio itself
Idk Im really frustrated atm and have a doctors apointment so I cant keep poking this problem
@livid kraken maybe it fucked up environment vars
I dont think so since the sanity check of building with a fresh project passed
so something somewhere is cached
Yeah but where🤣 I cleared all caches I can think of
and nothing in source control?
potential places, EditorPrefs (?), ProjectSettings, package manifests or something
Nope git is clean
Well was clean, after the lib nuke not so much
Anyways Im at the doctors now so wont be working on this anymore at least for today
Maybe I will come back and it will work🤣
i am implementing one for the game, but still havent an idea how to do combo systems
i use the bundled jdk because of issues like thiese - it's kind of tricky
okay based on this error
it's possible that installing a windows update "cleaned up" your system environment variables, where there was previous an issue with them there is no longer such an issue
and consequently you now have a lot more of e.g. your JAVA_HOME or PATH correctly working
and it's finding your other android sdk path there (or something)
the windows update might also be a red herring, you may have just not restarted in a while and something else you installed or updated modified your PATH / JAVA_HOME / ANDROID_SDK_PATH or whatever that path is
how can i load a dll at runtime and run it's main script?
What's the goal here? Mod support? This is extremely dangerous.
you're at the start of a very, very long journey
yes, mod support
you can look at the XMage or Spellsource source code to see how to represent something like a card game card in json
how can i run it's main script?
thx
use reflection to find some method you want to run and run it
Nope
😛
that's why this is so dangerous
there's no way to know what the Assembly it going to do
then i'll make a system to review it before you can use it XD
It's a lot safer to provide mod support in the form of some kind of sandboxed scripting environment
like a custom program?
that's why a lot of mod support uses languages like LUA which can be plugged into your game and limited on what parts of the application it has access to
have an example on how i can use LUA?
I've used MoonSharp in the past https://www.moonsharp.org/
it's a LUA engine for C#. Basically you can create lua functions that call back to C# functions you write
letting you define your mod api into your game
so the modder would write LUA, which only allows them to call C# functions that you have predefined basically
you would have provide some C# code that can load an external model for example and provide a LUA function to plug into that
k, will it work with prefabs too?
wdym
if someone wants to add a prefab
you'd have to provide support for that somehow
k
e.g. via AssetBundles
i'll invent something
trilib is a good asset for importing stuff like FBXes at runtime, if it's important that the players do not touch unity editor at all
thx for the help guys
I'm getting an InvalidOperationException when I call SetResult() on a TaskCompletionSource. I've verified that that both the TCS and the argument are instanced and of the appropriate type. I'm kind of at a loss on how to troubleshoot this.
I'm also not calling SetResult from anywhere else - 1 shot.
show code and error message/line?
i broke something else while trying something - hold on 😛
Please see #854851968446365696 for instructions on how to ask a proper question and how to share code.
You need to say what's broken, show the debugging steps you made and its results.
Use a paste website to post code as Discord embeds can fail and aren't visible on mobile.
so I tried to put debug logs, and its not even showing that hes put into the attack mode. seems like hes stuck on idle
a powerful website for storing and sharing text and code snippets. completely free and open source.
I got the nav mesh stuff already setup
where did you put logs? Looks like it needs to be in chase state before it can go into the attack state
i put them in jusst about every if statement i could that said somthing about attack
I don't see any in the code you shared
oh cuz i deleted logs before share sry
you'll want to put them where the state transitions are supposed to happen
you want to figure out if it's never geteting into that state, or maybe it's getting into that state and quickly exiting for example
and then figure out why
can u help me figure that out, show me where to put them?
@brave solstice one way to make things more organized is things like
state = InitStateAttacking()
public AIState InitStateAttacking
{
anim.SetBool("IsAttacking", true);
return AIState.Attacking;
}
and then your if statements can be like
if(EventAttacking()){}
instead of
if(distanceToPlayer <= attackRange)
for example.
your AI state machine is just ultra simple logic based on distance so it should be easy enough for you to figure out just looking over the code.
for me I found it extremely helpful to print the state every time it changes, so you have a better idea of what is going on
organizing it like it said is really helpful because you may have to paste things in multiple locations otherwise, and then make a change on one and forget the other
im so confused, trying to read
are there any lines that you don't know what the command is doing specifically?
i mean it looks like attacks/state switches based on distance, but so confused why enemy wont attack/move if no errors
check the inspector for the state of the AI when it won't move and ill take a look
does PlayerPos return transform.position
got it working now
great
np
somtimes i want to throw my keyboard 😅
yea same. I find the best way to solve my problems is to calm down or rest up
How would I go about getting the class that called a function? I'm trying to make a custom logger, and I'm calling it from a class called TestErrorCaller,
however, running this code:
Debug.Log((new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().DeclaringType.Name);
returns <>c__DisplayClass10_0, and not TestErrorCaller
https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=net-6.0 does this work?
you're getting the name of the declaring type
so it's printing the name of the type
why not print the name of the method itself?
Oh call, not sure that is possible easily
Creating a new stack trace is probably very slow
oh sorry I misread
Method name works, trying to get the class from which that method is called
but it's returning something weird and not the class which it is called from
if it's not possible it's fine I can probably pass the type as an argument
just trying to do this from a code cleanliness perspective
well where did you put this code?
looks better to call Error("blah") instead of ErrorFromClass<TestErrorCaller>("blah")
Inside of Error, a method of Logger
can you show the code?
Is it inside a lambda or something
yeah that's the name of the lambda class
that was created automatically by the compiler
How would I go about getting the class that called a function?
Logger.Log("Message", className=nameof(MyClass))
a logger shouldn't do reflection
you will get an exception
in your logging code
and pull your hair out in anger
usually the simplest thing is
class MyMono : MonoBehaviour {
private static readonly Logger logger =
LoggerFactory.GetLogger(nameof(MyMono));
}
@frozen prawn
but you shuld just use microsoft.logging
Yeah i might need to do this
Help
this is the error
its an unity script not mine
and the code... without errors?
are you sure you didn't edit this?
yhea
because that code is clearly broken
its the psdImporter
the green line in your code editor show that you changed it
i was testing put } or ;
because that is what the description says
but nothing more
you should not be changing any of the code
uninstall/reinstall the package
and/or uprade it to the latest version
is this the way to call my input func to attack?
this is in my animcontroller.cs ``` public void Attack()
{
anim.SetTrigger(AnimationKeys.Attack);
}
public bool Attacking()
{
return anim.GetCurrentAnimatorStateInfo(0).IsName("SwordAttack");
}```
so im trying to access that by using my input on the attack script
to trigger my animation attack layed out in my other script
Have you tried putting that code in place, what happened?
so i tried making a whole new script
getting this error now
still spitting error after i put animator = GetComponent<Animator>(); in awake
Do you mean GetCurrentAnimatorStateInfo ?
LOL maybe lemme try
so it lets me run the game but still wont work for the attack
@mint python so this correct?
What happens when you run it?
wont do the attack
where can i put a debug log?
if(!isAttacking)
{
animator.SetTrigger("Attack");
Debug.Log("Attacking pen!");
StartCoroutine(InitilizeAttack());
}```
here?
Are you sure this is an advanced topic
@mint python this is my input
hey guys, so Im having this error for no reason, I just imported taro dev's .unitypackage:
https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
and its giving me this error:
Assets\Tarodev 2D Controller_Scripts\PlayerExtras.cs(14,24): error CS0106: The modifier 'public' is not valid for this item
(basically for every thing that has public in the script)
here is the script:
https://gdl.space/ejogihadik.cs
yeah interface members shouldn't have public or any access modifier in front of them
how can I fix that?
errors in other scripts pops up because they need them to be public
they are public
automatically
that's how interfaces work
I'm talking only about lines 14-19 and 23-24 in that script
nothing else needs to change
both interfaces, but is there another interface other than IPlayerController ?
I have a project, I want to break some of the systems into separate code libraries so I can use them in other games and more easily update and so on. How does that work in Unity? 🤔
I remember seeing some file extension I can't recall now when looking at a code asset from the store 🤔
make UPM packages
Models, Textures, animation and audio clips
, and other assets.
Does that include prefabs? 😮
Oh these are probably the same format asset store stuff uses huh
Are there any strange performance concerns with using interfaces on monobehaviors? 🤔
no
Cool 
they are just often useless without custom tooling/inspectors because unity can't deal with them in serialization and the inspectors
🤔 Can't you assign components to interface fields in the inspector?
Could swear I've done that
nope
unity needs a concrete type for everything it is supposed to serialize (i.e. all serialized fields that you assign in inspectors)
yes
you can use the [SerializeReference] attribute to get some sort of interface serialization but you should be very careful when you use that, its not a general solution
So what is the solution for loosely coupling two packages? 🤔
loose coupling is not achieved by just using interfaces
That much is now clear :p
What are the alternatives, so far my experience with Unity has been there's usually some workaround to the quirks lol
you could just use a regular base class to define the interface
True, that bypasses the issues?
you can also still use interfaces, just not for the automatic inspector fields
the whole UI EventSystem is built on top of inetrfaces and base classes
you could look at that for some ideas
Oh well the base class thing means... hmm it's still fine, but you have to have an extra component involved
Instead of just slapping the interface on the component that is interacted with
But that's nbd
in most games full decoupling of systems is frequently impossible
or at least impractical
it just adds a lot of code that does nothing and that is rather difficult to make efficient or makes debugging quite tedious
I mean, code assets existing disagrees with that a bit
I'm just trying to break up, for example, an inventory system from a FPS character controller from a stat-buff system
yes, but why do you need interfaces for that?
I don't, base classes sounds fine
I mean, sure, I might end up not needing it at all, just establishing my options before I even start thinking about how to separate it
the realization is usually that only very few of these assets are actually helpful, precisely because the asset generally fails to integrate nicely with the rest of the game
and assets like UniTask or DOTween or Mirror are anything but decoupled
Nah I'm talking stuff like a dialogue system
thats also not decoupled at all
From what? 
you will not be able to replace dialogue system X with system Y
you will design your game to suit the dialogue system asset, that is not decoupling
🤔 I am not referring to coupling with the game, but with the other packages
Obviously at some final level things gotta have glue 😛
what good is a dialogue system that does not cooperate with your UI juice or Behaviour Tree asset?
Optional cooperation is the goal. Keyword being optional
good luck with that dream
I'm pretty sure you're just misunderstanding what I'm talking about 🤔
I'm not expecting to be able to just hotswap them or something
I just don't want them to require each other explicitly
That's not that complicated 🤔
Code assets optionally work with other code assets fairly often
Without requiring them
you'll see how pointless these assets often are, precisely because they each do their own thing and don't integrate holistically
Using... existing code... is pointless... got it lol
If you can't write the code needed to glue stuff together then sure
But using existing code libraries is like 99% of programming
Pretty much just when you are learning do you write software that uses 0 existing libraries
Thank you!
Anyone here have expert certs? I'm interested in knowing how hard the test is.
i'm trying to lerp from quat1 to quat2 but it gets flipped, i tried both euler and quaternion but result is same
// Extra points
for (int i = 0; i < genPts.Count; i++)
{
float blendValue = ConvertRange(0, genPts.Count, 0.0f, 1.0f, i);
var rotationFrom = start.localRotation;
var rotationTo = end.localRotation;
var localRotationBlend = Quaternion.LerpUnclamped(rotationFrom, rotationTo, blendValue);
var base_left_angle = localRotationBlend * Vector3.right;
var base_right_angle = localRotationBlend * Vector3.right;
var leftPos = genPts[i] + -base_left_angle.normalized * length;
var rightPos = genPts[i] + base_right_angle.normalized * length;
genExtraPts.Add(leftPos);
genExtraPts.Add(rightPos);
}
more details and a minimal github repo is presented here https://gamedev.stackexchange.com/questions/202180/how-to-lerp-correctly-between-two-unlimited-rotations
result :
That probably wouldn't ever work with quaternions since they're normalized. Try defining the start/end rotations as angles and convert the lerped angle to a quaternion rotation.
how can i convert local rotation to angle? there's a angle float on them is that the value i need?
Ah, I see now. local rotation is probably normalized as well. You'd need a custom Vector3/float field to hold the start/end angle.
From my understanding you're relying on the angle values in the transform inspector, right?
all i care is to compute blending points based on local rotation of start/end, i don't want a world space rotation and result is only a vector3 position for generated points
Well, anyways, the point is that you shouldn't rely on the values in transform. Especially if you're using values above 360(possibly 180). It gets converted to a quaternion and clamped back to the above-mentioned values. Thus, you'd need to define your rotation separately. If you need to include the current local rotation offset you could get it from the local rotation Euler angles and add to whatever value you want to be above 180/360.
Say I have a white floor, with a character that can move left and right. How do I make it so the colour of the floor is yellow on the sides of the screen, and then gradients into white at the center of the screen?
The player can move left and right, but the floor will still follow this colour pattern?
you say i need to make my own quaternion system?
Like.. screenspace shader?
No. You don't need your own quaternion system. Even if you did it would likely have the same issue. What you need is to slightly change your current approach.
well this isn't what i'm doing here ?
https://github.com/CycloneRing/UnityRotationLerp/blob/12ecfe2bef1c466ac998210999fa998235f3547c/Assets/Generator.cs#L38
i'm confused, using local rotation euler comes with same result
Take a screenshot of the inspector. What values are you working with?
Not very familiar with that. I’m sorry I’m kind of new to unity and didn’t even know there were shaders lol. Do you think it would fulfill my purpose? And does it work in 2D?
i don't set any value in inspector all is coded, which object you would to see inspector of?
i got a solution in my mind to create a temporary game object set the position and apply the rotation using transform.Rotate and set it back to points but it will be a performance killer no?
The one that you use rotation of.
Shader can definitely work on 2D. But how to write it is depends on your rendering pipeline. So your ‘floor’ can change shape but has same gradient independent of your character position?
In your code it's the start and end transforms.
That wouldn't help as you'll still be relying on transform rotation.🤷♂️
it's a simple spinner script
public class Spinner : MonoBehaviour
{
public float speed = 0.0f;
void Update()
{
transform.Rotate(transform.up, speed);
}
}
spins the start/end points
Okay. Well, instead of rotating the transform, just accumulate the value as a float and use that in your other script. If you do need to rotate the "spinner" object as well, you could feed the accumulated rotation into it as well.
The point is to keep your angles rotation stored as an angle and not as a quaternion
Float can be swapped with a Vector3 if you need to rotate around more than 1 axis.
float speed;
float currentAngle;
Update()
{
currentAngle += speed * Time.deltaTime;
}
https://www.ronja-tutorials.com/post/039-screenspace-texture/
Something like this but in your case texture would be simple gradient
There are many techniques how to generate texture coordinates. Previous tutorials explain how to use UV coordinates and how to generate coordinates based on planar and triplanar mapping. In this one we’ll use the position of the pixel on the screen as the coordinate.
On it’s own the effect just looks kind of weird, which can also be used as a ae...
sorry i'm confused what is this has to do with rotation lerp calculation, still it give same result it's not how i rotate it, problem is how can i lerp the generated points correctly between these two points
You lerp the float angle
Mathf.Lerp(currentAngle, targetAngle, t)
Then use the result to construct a quaternion from Euler angles and use that as the new rotation.
Perhaps that's not the only issue with your current implementation. But it's definitely on of the issues.
feel free to check the minimal project i provided
Can't do it from phone, but will have a look in the evening. If I'll still remember it.
Thanks!
I apologize if this more so belongs in #💻┃code-beginner but I feel like it might be a fairly complicated thing im trying to achieve. Currently, I have a 3D FPS game that im working on. I'd like to incorporate a funny gun, where if you shoot another player with it, you and them must battle to the death in a game of PONG. I'm trying to think of the best way to achieve something like this and I'm not sure what's possible. My plan is to set the current camera of the players to a camera somewhere far away and have a 3d pong game playing there? Is there maybe some sort of canvas or UI I should use instead? Sorry its a very general idea, but any advice would be helpful!
What happen if multiple user use that pong gun at the same time?
So i had several thoughts around this. I might take the easy way out and make it so that there is only one PONG gun in the game at a time. Another idea was maybe to have set "arenas" where multiple PONGs could exist at once. idk its a cool idea, but it may be too complicated to make work 😦
I mean anything is possible if you can manage it properly..
perhaps too complicated for a newbie like me lol
But the basic idea of setting camera somewhere far is probably right. You could do it with layer but it will be complicated.
Thank you!
No problem!
Hello there;
I noticed there is this OnCanvasGroupChanged() function under the UIBehaviour class
Is there a fast way to obtain the CanvasGroup that invoke this method?
Oh.... there is implementation available in the Selectable class
Singletons make a lot of things a lot easier in exchange for some mess if yuo want to do some more complicated things
Like threading
If you never run into those problems then they can make code a lot cleaner because well, you don't have to architecture systems that solve those problems and have less perceived complexity
Take Code Monkeys claims with a pinch of salt, imo his code is generally neither good nor clean.
That said the singleton pattern is very useful because it can cut down on a lot of .Find and .GetComponent calls which can hurt performance
GetComponent is not as slow as you'd imagine, as a matter of fact it still extremely fast... One awesome folk at c# discord server did a benchmark between IL2CPP vs Mono GetComponent
lemme screencap and drop it here
it's faster than Dictionary lookup
I do not believe that, I think his benchmark code is missing something
Yeah I remember that convo
Seemed not trustworthy
Also cached getcomponent vs uncached is very different
It might, but the dude who wrote that seems trustworthy enough at least to me 👀
Making reliable benchmarks is very hard. Any number of things can invalidate the results.
Thats because there is no data nor software design in the stuff. It's programming by stream of conscience which is always a bad thing
But I like going in programming hyperspace where the one who sees all tells me the whole program structure. That transe is the fun part
Thank you, I'm glad that at least one person understands the correct way to make software
That is a talent which, unfortunately, cannot be learned, you either have it or you do not
It ends up as a pile of garbage, though the process is fun
That's the stupid way of learning programming
seeing the design problems AFTER you're 50 hours into a project and have to scrap it
Think about your data structures, how are they going to be used, where are they going to be used, run the potential code in your head, the rest is just typing it out
Yes, the worst kind, thinking they know everything when, in fact, they know nothing
That is also very true, but usually practiced by people who shouldn't be in the industry in the first place
The worst trap of all is not knowing the technical requirements of the system you are making. You cannot write Application code like you would Game code and, conversly, you cannot write Game code as you would Application code
That is the problem, 'It kinda works', so they do not learn nor do they try to do it better
Happen to have a link to an intro on hexagonal architecture? Looks interesting
you are missing the point, in game software we have the FPS monkey sitting on our backs, in most other applications that is not so. If you really want to see optimal data/software design you need to look at the financial world where nano seconds in software count
can someone tell me whats wrong with this gameloop i implemented ?
private void MainLoop()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
long stepTime = stopwatch.ElapsedMilliseconds;
while (!_quit)
{
_deltaTime = (stopwatch.ElapsedMilliseconds - stepTime) * 0.001f;
stepTime = stopwatch.ElapsedMilliseconds;
_frame++;
if (!_paused)
{
Update(_deltaTime);
}
var dt = (stopwatch.ElapsedMilliseconds - stepTime);
if (dt < frameMilliseconds)
{
Thread.Sleep((int)(frameMilliseconds - dt));
}
}
}
when i set the frameMilliseconds to 1000/300 (300fps)
the fps jumps from 333 to 250 abnormally. why ?
My two cents is, Games also tend to be very object oriented by nature, everything exists by itself, whereas when I design other software, it's mostly centralized, with less parts. So I need to think more about the design pattern for the game so that the objects interdependency is scalable and workable.
Thread.Sleep is not going to give you an exact sleep time. It will sleep for at least that amount of time but probably a good deal longer.
yeah but i dont think thats the problem
You do realize this is a Unity server and not a game engine development server?
Thread.Sleep((int)(frameMilliseconds - dt));
casting that to int cannot be good
why not
i dont know where to ask
If I have to tell you the difference between int and float you should not be writing code like this
frameMilliseconds and dt are not floats, they are long
Stopwatches are also not that precise depending on the platform
Because they're backed by different things
i dont think a jump from 250 to 333 consistently is caused by that
there's a bug somewhere
well, if it's never hitting your target FPS then your precision is likely wrong
Caused by stopwatch, thread.sleep and possibly other things
but you are using a float for _deltatime and trying to achieve the same with an int
And that
achieve what ? _deltatime is never used in the loop, its just a conversion from ms to s
What happens if you use a busy loop instead of Thread.sleep? Does the same behavior persist?
jumps from 1000 to infinity. also my pc broke cuz i ran it without debugger :(
var dt = (stopwatch.ElapsedMilliseconds - stepTime);
you have alread updated stepTime
so dt == 0
A TimeSpan expresses a time period in 100 ns ticks. Research what methods can return a time span may yield some ideas
wym?
look at your code
stepTime = stopwatch.ElapsedMilliseconds;
So you are basically implementing a fixedDeltaTime
Thread.Sleep((int)(frameMilliseconds - dt)); where frameMilliseconds is fixed FPS and dt - time Update took to process but you also need to subtract the actual time taken represented by _deltaTime
wym subtract actual time?
fps is not linear, a single number calculation may affect it a lot on high ratio fps and a heavy calculation may only make 1 to 2 fps changes, you need to check frame time instead.
also what do you try to achieve? limiting fps?
yeah limiting fps. wym high ratio fos
didnt understand that part
say you want a fixed delta of 200. the time from the last frame is 0.9, the update takes 0.1 so your sleep period is (fixedDelta - (actualDelta + updatetime)
- use vsync
- use
Application.targetFrameRate = 120;to put a limit on game frame rate
He's not doing unity so your suggestions don't make sense
wait a minute, this channel is not about unity?
The whole server doesn't make sense if they're not using Unity
This channel is about Unity
That guy is just off topic
bruh
moment
what is actualDelta? isnt it updateTime?
high ratio fps is like rendering a empty scene which gives 2000fps
now add a single triangle and it drops to 1000fps
so we get 1000FPS drop but it doesn't mean if you add another triangle it drops 1000fps
FPS is not linear
yeah sorry guys didnt have any other server to ask my bad
GDL is the best search it up
no, it is the time after the previous sleep and coming back again as per your code. As I said if you do not understand this you should not be writing it
he means understand the theory first I think
im doing that rn by asking 🤷
Drawing a circle wrongly a thousand times will not make you a master of drawing perfect circle, you need to learn the logic before you start coding,
I usally bring everything down on paper before start coding
- Go native
- Find high precision timing structures for your target hardware platforms
- Write your own scheduler
- Have fun
i mean its more of a bug than not understanding, you know it exist but u dont know where
Get a piece of paper and a pen (if you cannot do it in your head), run through your code twice and write down the values of each variable, then you may understand
it is not a bug, it is a lack of understanding
you can also use notepad instead of paper
hey, I'm old school
does anyone have a library or at least a console app in mind that would describe a unity project (all asmdefs and all dependencies), or generate the project and the solution files for each project, outside the unity editor?
The least I need to generate the project files without starting up the editor and clicking a bunch of buttons
you can look at the sources of the visual studio package
it is what is generating the project afaik
so in theory you can copy it and modify
you mean calling methods by name?
thing is, the package may not exist in the cache
that works in the editor
I realize that generating the project files without restoring the library folder with the package files is a tall order
it would effectively mean reimplementing their pipeline
hello. Im trying to create an optimization system, its quite simple.
atleast thats what i hope
what kind of optimization are we doing?
generate the project and the solution files for each project
what's your objective? this doesn't exist, but if this is really important to you, check in the solution and project files.
Hey, I had a look at your project. In addition to what I mentioned, there was an issue with Mathf.LerpAngle. Didn't think too deep about why that happens, but using Mathf.Lerp instead seems to fix it. If you want, I can upload the changes to a cloned repository.
I tried Lerp but it still happens, but in higher degree like 360, I will be thankful if you upload your changes
Yes, as I mentioned, one of the problems was you relying on transform.localRotation quaternion instead of keeping track of the angle yourself.
I'm trying to upload it now.
Damn. Had some issues with Source Tree, so it took some time. Here's the forked repository:
https://github.com/Mdlich/UnityRotationLerp
SourceTree was cool back ago. Now Fork is the best git gui imo
thank you dlich, this is amazing! changes you made twist the points perfectly! it becomes so cool by playing with speeds...
however this is not like the reference i need, it shouldn't twist it just have to comeback to same state it started rotation.
this is the reference i need to implement https://i.stack.imgur.com/DQZv6.gif
Which is more optimal for firing a delayed method: Invoke(nameof(methodName), someFloat) or a coroutine with yield return WaitForSeconds?
coroutines
Ok, cool. THanks
Here's a fun one. I am trying to make a dictionary with two variables as a key. Unsure how to do it. Essentially:
A, B | AB
B, A | AB
A, C| AC
C, A| AC
B, C| BC
C, B| BC```
Is there a better way to do this?
Use a ValueTuple
Yep jsut make a struct that defines equals/hashcode in a way that ignores the order of the two values
ValueTuple is not order agnostic so it won't work
ew - wasteful
On second thought, I might not need it to be order agnostic. Here's the sitch:
I have a variable defined that is an object's 'material'. Not Material, but a generalized one (stone, wood, etc.) When two objects collide, I want to take both objects 'material', and check it against a dictionary of sounds to play the right collision sound. But it occurs to me that dropping a rock onto a metal table sounds different than dropping a spoon onto a stone table
So I assume that makes it a bit easier. In which case, maybe valuetuple is the place to be
(int, int) tuples are compiled as ValueTuple anyway, no reason to use ValueTuple directly.
I wouldn't want to allocate for dict lookup
tuples are structs
you have to jump through hoops to get that
(int, int) x = (5, 3);
is not a Tuple.Create
That is, ValueTuple you just created
The tuple language feature in C# translates to ValueTuple now. It used to be System.Tuple.
fair enough
does "now" also apply in Unity?
I don't recall tuple syntax ever being System.Tuple.
Yes. And I think I'm wrong that it used to be System.Tuple. System.Tuple was available, but didn't have the (int, int) syntax until ValueTuple
It introduced in C# 7.0 and it was ValueTuple ever since
.NET is very strict for backward compatibility as well
Only "breaking" syntax change I know is capturing loop variable into closure
yes, in this case declare
var dict = new Dictionary<(PhysicalMaterial, PhysicalMaterial), Sound>();
however i think you prboably want to create a
class SoundProperties {
...
}
I want to make my own custom render engine that shoots out raycasts at each pixel and detect if it hits a certan object. allowing the rays to bounce on geomitry. How can i get a world raycast for a given pixel on the camera?
This is fairly simple so i dont want to make my own shader for this
And how can i set a pixel on the camera to whatever I need?