#archived-code-advanced
1 messages ¡ Page 178 of 1
Oh I've watched all the stuff with SC2, was very revealing about how these NNs are working
that the bot can exploit lmao
and training
yeah it's scientifically very interesting
but there's a really good reason it's starcraft and not hearthstone
But I think they've got a pretty robust SC2 ai at that point?
same with DOTA 2
it just takes like milliions of training hours
i think they ran a trial of the bot playing against real humans in SC2 matchmaking
on the public matchmaking
but there were too many flaws with that? i don't remember what happened
DOTA 2 they let people play against the bot and normals defeated it in like 30m
yeah well there's a reason people kind of stopped playing starcraft
as a competitive experience
Dota is actually much more complex
DOTA has the same mechanics where a little bit of excess dexterity at the right time wins the whole game
like i said, why not a hearthstone bot?
the path to victory in a MOBA is much more complicated than the path to victory in Starcraft
dexterity has no role in the game, is the answer
Vastly different hehe
even the poker bot that the CMU team made... the experts felt the bot fatigued them out
because it played cautious? I haven't seen anything about that one
you can read about the circumstances of that experiment, and the bot started to rack up its biggest wins after an unrealistically long amount of multiple-hands play
it doesn't get tired
12ms to go 4 deep on a 5x5
5x5 is too short though, way to easy to lose with an unlucky run of blocks
even w/ a very short queue
well the idea is that a queue of x length must contain a breaker-block of each color
so a shorter queue is a "lucky"er queue
the essential ingredient of alphago/alphazero is that a chain of many transitions in go corresponded to something that could be learned by a deep network
because Go looks like convolutions on matrices
https://www.deepmind.com/blog/alphago-zero-starting-from-scratch this also reduced its resource usage, according to them
how true that is i don't know
It decimated almost everyone and they had to nerf it
Even after the nerf it could go toe to toe with the best players
but also that game had fewer than 30k online players, even then
Well they say it plays on bnet at grandmaster level in open play
Don't understand what that has to do with anything, but I only skimmed the convo
i suppose an FPS bot that aimed perrectly would also destroy players
ol
i'm trying to emphasize that the starcraft bot had a dexterity problem hidden inside of it
i mean, i don't know how it was so hidden, it is obvious to everyone
What kind of dexterity problem?
It had unlimited actions per minute, inhuman, you mean that? They nerfed that to be more human
and they managed to convince the public that limiting APM was sufficient to limit the impact of the dexterity problem, and i'm saying it did not at all
the apm doesn't matter
it just needed excess dexterity compared to its opponent for a very short period of time
you're part of that public
Oh you mean like, individual unit selection and stuff?
Yeah that was way over the top
if you watch the real games, it only needed to portal 1 extra stalker
which a human could certainly do too, but the computer always correctly portals the stalkers
starcraft is, a big battle that determines who won
which is cool, that's a good setup for a game
the dexterity in that battle plays the biggest role in determining the winner
One thing it used to be able to do, still can to an extent, is superhuman micro. It doesn't make mistakes like you mentioned, so selecting a single zergling in a swarm is no big deal. It can micro a swarm of them to have single zerglings take tank hits
since the units with the greatest value have that value tied up in dexterity
right
exactly
The difference being that no only does the AI execute dexterous tasks to perfection, but it ALSO doesn't waste any actions
is # of lines of code a useful metric in any sense?
Not usually
like saying "game X is Y amount of lines of code yada yada"
Only as a sort of general approximation of the time commitment, maybe
i don't play competitive starcraft though, i will say stuff that doesn't make sense to a competitive player
I definitely don't think dexterity plays the largest role in Starcraft
but because of different language, not because we disagree
Depends on who wrote those lines. A noob can make something 10k lines easily. Someone who knows what they're doing can reduce that massively
A dumb AI with crazy micro will not win. It actually executes proper scouting, builds, and timings in addition to the good micro
it is the proximate reason games are won or lost at the highest level
thats fair. my comparison was hearing that dwarf fortress was 700 000 lines of code (as of a few years ago, maybe its diff now) and that seemed like... alot lol
Largest, no. But it's a part of micro, so I get that it's kinda big
It is and DF is kinda huge, Toady knows what he's doing I figure
which if you think about what a deep neural network does, it's going to find the shortest path to the biggest reward and optimize the shit out of it
agreed, hes harvard trained to which is pretty intense. not that their particularly known for CS but still.
It's a lot but like i said, that represents a HUGE, MASSIVE, almost INHUMAN amount of time on the dev's parts. They've been working on it for decades(?) at this point
the APM constraint was window dressing to sell the project
I've been playing it since like 2006 and it had been around a while before
Ya I remember reading about it in the early aughts
i've been playing it since 2013 or 2012, its crazy how much has changed since then even
boat murdered lol (early community fort)
They haven't posted anything new on alphastar since 2019 đŚ
I guess if its beating everyone what's left to say
i wish toady would go into more depth on his algorithms and stuff like how he implemented a* with mulitple z levels.
but he does his best in the future of the fortress posts
Depends. I have watched many, many professional games of Starcraft and I feel like it is smaller trends unrelated to micro. You hardly ever see the top players mess up their micro. It's more like, a Zerg player made the decision to spend tons of resources on repeatedly attacking, but they keep attacking into an entrenched position, and now they are down many thousands of minerals in gas on their side of the map. The game gets long, and they run out of resources. Or, a Terran might choose to take air superiority but then get overrun by repeated Zergling runbys and have a difficult time tech switching with the constant harass. A protoss might fail a cheese because they got randomly scouted and eventually lose the game because they are behind
I don't think their AI could actually beat the TOP top players
It's less about the micro, and more about mindgames and army composition at the highest level
I think I will give unity ml-agents a crack and if it proves deficient I could rewrite things in pure c#.
if the human player had excess dexterity at the right time, they'd win regardless of the strategic mistakes
this is true in DOTA and League of Legends too
i personally don't like these games
i find them stressful and not fun, and everyone i know who plays league is permanently soured against all other PvP games
I don't think this is true of either of the other two games you mentioned either
A functional team aiming to win would beat dexterous players
there are hardly any bots of strategy games.
the best evidence for how important dexterity is in starcraft is the fact that some people somewhere figured out how to get a spam* detection technology to play it well
Yea I think it's very deceptive to think that human dexterity is in any way similar to AI dexterity
this is coming from the perspective of someone who has written these bots
There is a gulf between human dexterity and perfect execution
and @soft hawk now has the perspective of having written a heuristic bot - what is the "game" hiding inside there, so to speak
it sounds like in puzzle fighter it's about setting yourself up to use the queue best
which maybe cheating (knowing the queue) has an outsize impact on that
it's not impossible to write a heuristic bot that handles not knowing the queue
Setting up combos is the key to high level play, yes. That's why my bot has to cheat. I didn't really see another way to do it
it's hard though
Yea and I'm not sure how good it could be. It's very good right now even limited to 100ms, it can play indefinitely
But 100ms on this pc and 100ms on my phone are very different things đ
Serral ended up winning I think after a few attempts
Considered the GOAT, except maybe Maru
Serral has improved quite a bit in the last 2 years, I didn't know they had actually done runs of these matchups though. I'm late to the party
Yea I think the last iteration of AlphaStar was very capable
He went 0-3 against the toss agent lol
if im spending full time developing something should i care about optimization off the bat, and if i don't, am i just adding technical debt (ie more time down the line fixing quick n dirty code) lol?
you're probably going to rewrite large portions of your code multiple times as you figure out how it should be structured. And you don't know what parts of your code are going to be important to optimize from the beginning. Focus on optimization once stuff has settled into place, otherwise you'll just be wasting your time.
Some people make prototypes in a totally different language/engine than their final game will be to force themselves to throw everything away at some point once they have the design figured out.
I've rewritten this puzzle fighter clone 3 times at this point, the first iteration was a mess
But also, don't do stupid things. If you can choose an approach that is more optimized for 10% more effort, go for that. But don't do 100% more effort to optimize it until you're confident that effort will pay off.
resizing the game window in WebGL is something that needs to be done on the Javascript/HTML/website side, it's not really under Unity's control.
does the bot mass stalkers?
Regardig the docs:
https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html
the parameter halfExtents is a vector3 with HALF the size of the boxcast in each dimension...
And the example says:
m_HitDetect = Physics.BoxCast(center, transform.localScale, transform.forward, out m_Hit, transform.rotation, m_MaxDistance);```
But in the draw gizmo example we see in the same page they do:
```c
Gizmos.DrawWireCube(transform.position + transform.forward * dist, transform.localScale);```
So my question... isn't the boxCast or the Gizmo draw missing a division by 2?
the boxcast expects half of the size... but then the Gizmo is drawing the full size
does it make sense?
is the example not accurate?
to my understanding the Gizmo would be drawing a box twice as big as the BoxCast actually is casting
I don't think it massed them, but its stalker micro was insane
what would a more strategic starcraft look like? Civ V is probably a good candidate
it's not balanced for multiplayer though
really hard to say what turn based games people play besides CCGs
with interesting multiplayer
what about crusader kings 3?
that game is hella strategic in terms of political decisions
theres gotta be a bot meta
and its current AI sucks ass ngl, could use work (its a terrible ally in wars, for instance)
that's a good one
My enemy game object has a child game object which is a trigger collider for an attackbox. This child game object also has a script that propagates the OnTriggerEnter2d call to the parent object. I want my enemy to have two kinds of attacks, a light attack and a heavy attack.
I am currently using the trigger attackbox for the light attack. In the light attack animation i am turning the trigger collider on and off.
Now for the second attack i can easily create another child object with another trigger collider and script.
But let's say i want to use the same child object for the two kinds of attack. Even though the two kinds of attack has different animation and different attackbox sizes, i can easily use the animation record option to change the attackbox size and position.
But inside the code where i call the TakeDamage(parameters) function of the player game object, how do the enemy know whether it should send the light attack parameter or the heavy attack parameter
Even a "simple" game like civ has terrible bots
It would take A LOT of processor time to train a decent bot on 4X games
So if my GameState is this:
public struct BlockParams
{
public BlockType BlockType;
public int ColorIndex;
}
public enum BlockType
{
Empty,
Basic,
Execute,
MegaBlock
}``` Can I just pass GameState directly to ml-agents CollectObservations() or is there an additional step I need to do for the BlockType enum?
hmm it doesn't like multidimensional array
Don't cross post
Okay, so i am importing a more efficient matric multiplication library and it gave me a Unity Error as soon as I imported to library. It told me to turn off 'Use Deterministic Compilation' in Player settings
I did, and everything works fine, but I dont even know what deterministic compilation is, much less know if its bad or not for this to run.
Unity 2020.2 offers a â-deterministicâ compilation option when compiling C# scripts. This option lets you avoid unnecessary recompiling of assembly definition (.asmdef) references if the public metadata for the assembly does not change when compiling scripts for the Editor.
I think basically it only recompiles assemblies that actually changed. Not sure why that'd cause an error
This is the matrix library https://www.codeproject.com/Articles/5835/DotNetMatrix-Simple-Matrix-Library-for-NET
and the error code it gave is attached, here is the code that is erroring.
https://hastepaste.com/view/SsKgl7
As well, The files have csProj files. Attached is a screenshot.
Ahh, this project uses another assembly file inside of it. Will that cause issues?
Ima just try it, lmao
remove assemblyinfo.cs
and create an asmdef file
change the framework to netstandard2.0 and retrieve the project's referenced DLLs using dotnet publish
i should write a tutorial on this
So, I'm using the new input system, and storing the left stick's x and y position to variables:
currentUp = gamepad.leftStick.ReadValue().y;
currentRight = gamepad.leftStick.ReadValue().x;
And when I push the stick up, not to either side ...
What's going on here?
I'd think Current Right should be 0 or at least close.
guess I'll make a check that if it's under, maybe 0.001 or something, it'll go to 0. My game doesn't need that precise analog input anyway.
That might be the deadzone or something?
Joysticks often don't output zero, so there's a deadzone, or a "close enough" value that it sets it to zero when it gets there iirc
Might be able to change/increase that in input settings
yeah, cuz right now down is being treated as also holding right, and that's not what we want XP
this is what I see
Deadzone seems ok to me, not sure
When are you running this
basically at the beginning of Update.
that is close to 0
Fixed it by adding additional code that functions as a pseudo-deadzone, avoiding floats in a range of (currently) 0.00002, changeable if needed
the code considered anything above 0 for that axis to be "holding right". Like I said tho, I added my own deadzone code to fix that.
if (currentUp < deadzone && currentUp > 0 || currentUp > -deadzone && currentUp < 0)
{
currentUp = 0f;
}
if (currentRight < deadzone && currentRight > 0 || currentRight > -deadzone && currentRight < 0)
{
currentRight = 0f;
}```
tho if there's a way to shorten the lines I'd like to know
i would change the other code so that it works in a way that effectively 0 doesn't break everything
it's technically not needed with this fix, but I might end up reworking it anyway if I decide to make variable movement speeds based on stick tilt
which I'm honestly tempted to do.
it sounds like you have shit movement code tbh. you haven't actually shown it, but it sounds like you are changing bools which determine what direction you are moving rather than something sane like normalizing the input vector and just using that directly
I don't know about "normalizing the input vector" (or if I do then I don't realize that's the term for it), but the reason I save it to a variable is because that code is in an input script, and passes the input variables to the controller script. I do it this way to account for stick taps and macros, like Tap Jump, without needing to clutter up the controller script.
that, and the input script is so the player can control the character, and would be replaced with an AI that uses the same inputs when the character is controlled by a CPU. (yes this is a fighting game)
sounds like #archived-code-advanced may not be the place for you then. But you have a vector returned by gamepad.leftStick.ReadValue() you can store that, normalize it so that it has a length of 1 and it will be a direction which you can use to determine the direction of movement
ahhhh
well, I already do use a current speed that is always positive relative to the direction the player is facing (left or right) and negative in the opposite direction. So I did account for that already. This isn't my first rodeo with 2D, after all.
you will only need a single speed variable that you multiply your direction by, the direction handles positive/negative so you don't have to
@thin mesa Here's a very stripped-down version of my movement code in the controller:
... let me get pastebin up
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
That code only focuses on the horizontal movement, not the vertical or anything else
that's horrifying
It works, but if it can be shortened that would help
you're not even moving it in a physics friendly way either so if you expect colliders to work correctly you're gonna have to change how you move anyway
I'm not using Unity's physics for this project
okay then how are you restricting movement so that the object does not pass through objects it shouldn't? there doesn't seem to be any indication you are doing so in the code you showed
ground doesn't need collision for my purposes since there's no other level geometry, so I just have a value for what y float should be considered "ground"
and since it's a fighting game, I just set a hard limit on how far the players can move from the center of the arena. That's done with a Mathf.clamp that was removed in the pastebin for length's sake
the only thing I'll really need to figure out in terms of "solid" collisions is pushing players away from each other if they're too close, but that can be done with raycasts apparently.
Since I don't need to worry about level geometry for this game, I can just hard clamp the player's position so they don't go under the ground or outside the "walls".
private IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(300);
// do something
StartCoroutine(MyCoroutine());
}
private IEnumerator MyLoop()
{
while(true)
{
yield return new WaitForSeconds(300);
// do something
}
}
What's a better solution?
rather then waiting for 5 minutes with a coroutine? hmm one coroutine over 5 mins isn't so bad tbh
or two or w/e
What?
@frank peak no no, I just want a piece of code to run every once every 5 minutes. Is it better to have the co-routine run in a while loop for that or start another coroutine after the first 5 mins are up?
oh derp
maybe start another couroutine, cuz the while loop is gonna call continously
as fast as possible basically lol
Yes but I read somewhere that's not how it works
huh interesting
because WaitForSeconds() doesn't let anything happen for that period of time, even if in a while loop
Can anyone help the badguys in my game attack me. (Im not good at coding so Ill need alot of help)
The bottom one
if you want to run something every five minutes, start a coroutine of the form
IEnumerator MyRepeatingAction() {
while (true) {
yield return new WaitForSeconds(5 * 60f);
// do actions
}
}
note you can cancel a coroutine gracefully using StopCoroutine() but disabling the script it is declared in does not stop it
if the coroutine is cancelled (by using StopCoroutine or destroying/deactivating the game object containing the coroutine) while waiting, it will not perform the action. if the coroutine is cancelled at any other time, it will have finished executing the action that frame or nothing will happen.
i do not believe it is possible to cancel a coroutine using StopCoroutine and then still observe it execute code after a yield
i would add an extra if check after the yield return
what you would check depends on your game, but generally only if that condition is met, then you actually do the actions
although i might not be understanding exactly what you are trying to achieve
Comparing against System.DateTime.UtcNow is how I go about it. I have enough times things tho that I have a scheduler and it knows the ânext timerâ to care about. Polling for one time is no big deal. Polling for 100 is.
Personally Iâve been burned too many times by coroutines
I have a weird setup where my unity project is a little widget that sits on my computer, and I tab in and out of it with hotkeys to send it inputs. This all works fine, except I have to stay tabbed into it for a little bit to make sure it registers the sent inputs properly. This becomes a problem if I need to send inputs repeatidly, since I can't just repeat the press without it overlapping the last one and going funny. How can I make it poll inputs quicker? I've seen mentioned that you could use DLL's to check the input buffer but I have no idea how you'd go about that.
Is it possible to build Unity from source at all?
ok so I have a problem where I need to dynamically downcast an object variable-
it returns an error
Man that's unlucky
I could use a switch statement but that would mean having to do it for the hundreds of nodes I will create
Care to mention what error?
I fixed it it's fine
I had to convet object to a variant of another abstract script
I just saved the type as a string and then got it that way
it sounds like your FPS is low, or you're checking inputs in a fixed update
Neither of them. Unity just does not play nice with tabbing out so I have to really make sure to give it it's time first.
hmm
there is a checkbox for Input System that allows you to listen to all events even when backgrounded
maybe you need that
it's in the project settings
it's something about focus, and something about background
it's two dropdowns
in my experience applications configured this way respond to events correctly with the most generous settings in those dropdowns
I do have it set to run in background, but not listening to input. I could maybe do that, if I put the keys used to something I'd never press otherwise like F13 through to F24. Not ideal though.
you can always check if the application is focused
it's really odd you should "lose" some events in the beginning
something else is going on
This is the kind of thing I have absolutey no idea how to debug, if I can at all. It'd be great if I could so I didn't have to do things like wait for the splash screen to finish before tabbing out to not break all callbacks (awake, update, etc).
splash screen?
The Made with Unity thing before everything runs.
so wait what is your exact issue
you alt tab into something
and it doesn't respond to events
have it respond while in the background
change that and just see what happens
I alt tab in, press a key, alt tab out, and it doesn't register the key press unless I wait to tab out. I'm doing this via autohotkey so this happens very quickly.
It's software to make your own hotkeys to do extra things with your keyboard and PC applications. So for example, I've bound Alt + Ctrl + Shift + J to directly activate the unity window (what alt tabbing does but directly telling windows the one to activate), send it the Delete key, then tab back out to whatever the last active window was.
what does your* application do?
what is its idea?
Oh. It's a productivity clock. So it tracks my time utilised and wasted, averages them, and shows me if I've been getting better or worse at utilising time for work.
got it
i think you should listen for all events
even in the background
for debugging purposes, draw a rectangle every frame if and only if the game is in focus
and see what that is telling you
also, if this is windows, try switching your graphics engine between opengl core, directx11, directx12 and vulkan...
there is sometimes a subtle thing going on with rendering the thumbnail in the alt tab window
directx has a dedicated approach to doing that
disabling it by switching away from (or enabling it by switching to) directx as your graphics may resolve it
I wouldn't have thought of that. I'll try that when I get the chance, thanks. If not, I might do the background keypresses with some obscure keys so there's no conflicts.
you can check if ithe application is in focus in an input processor
or whatever
start just for the diagnoses
Oh ye, right. Also worth mentioning, I'm currently just using the old input system. Since this was meant to be a simple prototype thing I didn't bother and I didn't think these bugs were related, but that's something I could try too.
hmm... use input system
Input is 
Input is #archived-code-general or lower
attackoutrotation = Quaternion.Euler(new Vector3(0f, transform.rotation.eulerAngles.y + Random.Range(125f, 235f), 0f));
close = true;
Debug.Log(attackoutrotation.eulerAngles.y);
Debug.Log(transform.eulerAngles.y);
Debug.Log(Vector2.Angle(new Vector2(0, attackoutrotation.eulerAngles.y), new Vector2(transform.eulerAngles.x, transform.eulerAngles.y + 1)));
Debug.Log(Vector2.Angle(new Vector2(0, attackoutrotation.eulerAngles.y), new Vector2(transform.eulerAngles.x, transform.eulerAngles.y - 1)));
if (Vector3.Angle(new Vector3(0, attackoutrotation.eulerAngles.y, 0), new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + 1, transform.eulerAngles.z)) < Vector3.Angle(new Vector3(0, attackoutrotation.eulerAngles.y, 0), new Vector3(transform.eulerAngles.x, transform.eulerAngles.y - 1, transform.eulerAngles.z)))
{
TurningRight = false;
TurningLeft = true;
}
if (Vector3.Angle(new Vector3(0, attackoutrotation.eulerAngles.y, 0), new Vector3(transform.eulerAngles.x, transform.eulerAngles.y - 1, transform.eulerAngles.z)) < Vector3.Angle(new Vector3(0, attackoutrotation.eulerAngles.y, 0), new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + 1, transform.eulerAngles.z)))
{
TurningRight = true;
TurningLeft = false;
}```
it should be around 153
why is it 0
@regal olive Don't cross-post
Not really unity specific, but does anyone know how to make the nuget package manager in Visual Studio run faster? Using nuget packages with unity is awful because of how slow the manager is.
use the dotnet cli for package management
Is it possible to move a package (TextMesh Pro, in this case) out of the Packages folder into the Assets folder so I can directly modify the scripts? For context, I'm not trying to get clever and mod any packages, just want to add some log messages to debug an issue.
copy the package's directory from Library/PackageCache to your Packages/ directory
Thanks, that worked great
A TextMeshPro NullReferenceException is freezing my game on multiple Android devices. Naturally, it runs fine in the Editor. I'm not doing anything particularly unique with TMP, just using it in my UI.
Here's the error log: https://pastebin.com/zDqCELuS
The line it's failing on is a method inside a C++ file: TMPro.TMP_Settings.get_defaultStyleSheet
I've double checked my TMP_Settings asset -- a valid TMP_StyleSheet asset is assigned to the Default Style Sheet field.
I've tested this in TextMeshPro v3.0.6 as well as the preview versions available.
Has anyone run into this before?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can you reproduce this
my instinct is that this is a red herring
I wish it was a fluke, but I'm able to reproduce across multiple devices on BrowserStack. Other folks on my team are able to reproduce on their physical devices as well. Oddly enough, my one physical testing device doesn't experience the error, a moto g power.
The same project built to iOS and WebGL doesn't experience this error.
If I can't figure out a solution, I'm hoping I can recreate this in a small project to submit to Unity QA.
That asset comes from Resources right?
The stylesheet, i think by default tmpro makes it in a Resources folder
I believe you are correct. I realized there were other folders in our Asset directory also named Resources, so I renamed them, leaving Assets/TextMesh Pro/Resources as the sole folder with that name. Sadly, this did not alleviate the problem.
I for unrelated reasons copied over the tmpro package into our project, to use it and modify the source. Perhaps that could help you
When I imported TextMeshPro into a brand new project for reference, the TMP_Settings asset is created with some interesting values. For instance, the asset path fields. Default Font Asset Path is set to Fonts & Materials/, Default Sprite Asset Path is set to Sprite Assets/ and Color Gradient Presets Path is set to Color Gradient Presets/. This seems to indicate a pattern -- those are all sub-folders of Resources. However Default Stye Sheet Path is set to an empty string. I tried setting it to a path like the others (Style Sheets/), but to no avail.
I should definitely try this -- thank you.
Just as a follow-up in case anyone comes across this and is looking for a solution -- I'm almost certain this error wasn't responsible for the freeze. I moved the TextMeshPro folder from Library/PackageCache/com.unity.textmeshpro@3.0.6 to Packages/com.unity.textmeshpro@3.0.6 so I could edit the scripts. I then modified the TMP_Text.GetStyle method so it immediately returns TMP_Style.NormalStyle, a static style with default values, since I don't currently use style sheets in our project anyways. That stopped the error from happening, but the freeze still occurs.
yeah it's a red herring
try modifying your texture compression settings
especially the font atlas texture
Oh good idea.
can you target android vulkan?
or vice versa - try to targe openglcore?
So, when you create and open a script in Unity with Visual Studio, you get auto-complete suggestions for "Awake", "Start", etc.
However I'm using Visual Studio outside of Unity and essentially only supply Unity with the built DLLs.
Can I somehow replicate that auto-complete behaviour in a detached Visual Studio instance?
I know how to get general auto-complete and have that going, I just want to have the auto-suggestions for the Unity Messages as well.
I figured I might have to enable Visual Studio Tools for Unity seperately somewhere, but I can't seem to find where
There's a section on this page about debugging DLLs on this page: https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/using-visual-studio-tools-for-unity?pivots=windows
Maybe setting the target framework for the DLL to Unity?
Those Unity frameworks apparently only exist for legacy editions, I'm using 2021.2 "unfortunately"
huh?
it should just work
if it doesn't try reinstalling things
in Rider it Just Works
Everything works fine if I open VS through Unity, but I don't want that for... reasons.
(edit) I figured it out.
If anyone is interested, i had to add the generated Assembly-CSharp.csproj from Unity to my custom solution and set that as the startup project. That's it.
I guess this code didn't belong in #đťâcode-beginner but does anyone know what is wrong here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platform : MonoBehaviour {
float dirX, moveSpeed = 3f;
bool moveRight = true;
void Update () {
if (transform.position.x > 4f)
moveRight = false;
if (transform.position.x < -4f)
moveRight = true;
if (moveRight)
transform.position = new Vector2(transform.position.x + moveSpeed * Time.deltaTime, transform.position.y);
else
transform.position = new Vector2(transform.position.x - moveSpeed * Time.deltaTime, transform.position.y);
}
}
I got this error message
go to the Platform game object in the scene hierarchy, double click it, find the script thats missing, right click, remove component and re-add it if it was needed
Thank you!
cheers
I am using Strapi as a backend. Does anyone know how to 'Redirect URL to your frontend app' for a unity mobile application?
Any help would be nice.
is anyone down to call and me screen share and help me add my sound effect in my game?
Stop cross posting. Nobody is
Hey unity devs, has anyone integrated socket.io into their unity project ( versions around 2020.3.5f1 ) and what resources they used for reference?
I am trying to implement a socket communication with a server my company has and we're implementing it into our app
seeing some performance spikes with Mono.JIT in the profiler, is there anything i can do to make sure these happen e.g. during the loading screen? like other than just calling whatever's causing them also during loading even if there's no actual reason to
like some explicit call i can make
I removed the vulkan api in player settings a while ago -- doing so stopped it from crashing immediately on my test device. But I'll play around with adding it back in.
Right now we only have OpenGLES3 under graphics APIs
I'm using vs code with omnisharp, however omnisharp takes up approx. 800MB of RAM, which seems excessive to me and bloats my RAM thus making reloading script assemblies slow. Is there some better setup?
You will have to run through the relevant code at least once. Note that Mono.JIT will not appear in IL2CPP builds.
Hi, do you guys know if it is possible to have a SerializedField that wants a ScriptableObject but Automaticly creates a new instance of it an exposes the parameters of the Scriptable Object to the inspector? (Maybe with editor scripting?)
pretty sure thats possible
Yes thats possible.
ok thanks, i'd like to stay on mono if possible so is there any info or rule of thumb for what exactly gets postponed for JIT? knowing what's gonna cause it would help a lot, rather than having to look for every instance of it in the profiler ...
Any examples on that our resources to look at? Especially the new Instance creation part. I want it to be very easy to use, and same as if I would use a normal ScriptableObject Reference
You'll get a Mono.JIT whenever a method is run for the first time or a type is used for the first time.
oh duh that makes sense, i guess i was only noticing the ones causing notable spikes and GC
How do I code something that will trigger a crash plus error message
I saw something on the site with the Abort() function but it doesn't actually show the code
i've tried looking this up a few times but i keep getting massive Physics.Processing spikes for no reason, the profiler on deep mode says it's all self time and they happen when running the game on "idle", i.e. they aren't correlated with anything specific in the game
oh wait argh i did "solve" this before, it was having my web browser running (not running the game or anything, just in the background completely unrelated)
just the profiler getting confused i guess as the browser ... hogs some gpu resources or something??
it showing up in Physics.Processing is pretty confusing, lol
it does make me worry about users running into the same thing, though hopefully it's just some kind of rare interaction with specific browsers/sites/whatever
If there is ever a lag spike for whatever reason, there will be more physics updates next frame to compensate for the lost time.
oh right the whole fixed time thing, makes sense though i wish the method was more descriptively named
like i guess you can't just change something this fundamental easily but it'd help if it was somehow readable in the profiler that "oh that was actually like 20 fixedupdates all at once" or something
Seems like rotating around x
there is no rotation issues in the scene
it'S literally just the scene view
that is on an angle
most of my items have no rotation applied to them
(same with the parents)
if there was a ingame rotation my character's gravity would react to it
If you don't have editor scripts that modify the scene view active, ask in #đťâunity-talk instead
.
just press on the scene view rotation gizmo
i dont know if this is an advanced thing, does someone know how to make one way 3d platforms? for the 2d side there is a component but for the 3d there is nothing
What exactly happen in the process of Graphics.Blit() call?
or better yet, when I call RenderTexture.GetTemporary, does it ever recycle any old RenderTexture? Or does it get override on the next Graphics.Blit call?
Apparently GetTemporary keeps recycling old materials and mix in with some other materials I didn't want to mix with...
Blit is drawing a full-screen quad to the dest texture with a material where src is set as _MainTex.
The default material when none is specified just outputs the src texture directly, so it's like copying src to dst
You have to call RenderTexture.ReleaseTemporary when you're done with it
Right, I had problem when loading rendertexture from temporary. It had garbage data in it, mix with new opacity texture on top of it.
I did that
It will auto release after like 4 frames, but you shouldn't rely on that.
the problem is, next call stack recycle that.
I had to call GL.Clear() before calling Graphic.Blit to remove the "dirty" texture I got from the temp.
I have a design problem that I am going to try to explain.
I am making a system for having a hierarchy of tags.
Animal
> Mammal
> Dog
> Reptile
Building
> House
(each one is their own tag, but with relations to their children and parent tags)
Tags have an ID and a string name and are stored in a central 'database' file.
Tags can be compared either by checking if they are exactly the same, or if one is an ancestor of another.
Now to actually use the tags, you reference their ID. There is also a collection class that holds references to tags for doing more advanced comparisons/group comparisons.
This is where things get complicated and I have my question. If I want to check if one tag is the parent of another I would need to use the ID of the tag and do a dictionary lookup every time. Which of course doesn't make sense to do, so it seems caching the parents would be the way to go.
The problem here though is that if the hierarchy changes, the cache becomes out of date.
My only two thoughts are either to simply do a dictionary lookup every time, or to use ScriptableObjects for the tags, so they could be referenced that way and the parents could be checked directly without the need for a lookup
Just a thought before going to bed, don't know if that'll give you ideas: did you consider hashing the whole hierarchy in the ID. Something like Animal/Mammal/Dog. Checking relationship is then a matter of String parsing, dunno if that's more suitable for your case (could easily make things worse).
Also,
if the hierarchy changes, the cache becomes out of date.
I don't see dogs becoming buildings all of a sudden, but maybe that was just a dummy example ^^ Anyway you can still rebuild your cache everytime your relations become dirty
That was my 2 cents, going to bed now, have fun
Is there a way to check if Visual Scripting is installed in Unity Project? Using scripting?
https://docs.unity3d.com/ScriptReference/PackageManager.Client.Search.html A quick search found this
you need to use a tree data structure
Right, but I guess the struggle is referencing the nodes of the tree
depends on how you implement the datastructure
i'd say its an ideal problem for to be solved by a custom datastructure
The references need to be serializable, so that makes me think an GUID. Then have a dictionary with a GUID as the key and a node as the value.
you dont need to serialize references in any complicated way if its a properly designed structure
the backing data could be a flat array
containing structs, with a parent field that points to another index in the array
Oh, then references could just be the index of the tag
yes
for efficient traversal you may want to keep a list of child indexes aswell
but you can always generate that from the parent-data, no need to serialize
Hmm, that would make it very cheap to get tags, no need for caching the parents per-reference I would think as it would be cheep enough to traverse
Something like tags[tags[tagIndex].parentIndex] to get the parent of a tag
Unless I am wrong I would also need to keep a list of 'empty' indices, for indices of tags that were removed.
your datastrcture should perform compacting when you remove items
it should always be sparse (no null)
That would mess up all current references though
you would have to update them all
thats the price you pay if you dont use a linked approach
linked = each node is an object somewhere on the heap
Hmmm... I'm not sure if that would be possible....
Not in Unity đ
My thinking is that you would have a public TagReference _someTag; field. And assign it to a tag in editor
public struct TagReference { public int tagIndex; }
So, it wouldn't really be feasible to edit the index of every TagReference in the project
when you say tags, do you mean unity Tags?
I do not. I mean my own tag
what is your objective?
what problem is this trying to solve
i see.
I guess it would be efficiently reference a node in a tree, and efficiently check what it's parents are.
i meant the real problem lol
like what is the gameplay or
application thing going on here
Oh oh, I am making a tag system for my game so that I can more easily check data and status in a generic way. I can check if a GO has a Status/Fire tag instead of having to check if it has a Status component and if that component has the enum Effect.Fire
you can make a tree with nodes of the form
class Node {
string name;
Node parent;
Node[] children;
}
and you can test if name IsAnAncestorOf node using
boolean NodeIsOrIsAnAncestorOfName(Node node, string name) {
while (node != null) {
if (node.name == name) {
return true;
}
node = node.parent;
}
return false;
}
okay... i wouldn't say what you are going for helps you solve that
if you want to check if a game object is on fire... get the component, etc. etc.
Right but the issue is referencing a node in a serializable and efficient way
referencing what though?
the right way to do this is
if (gameObject.GetComponent<Status>()?.IsOnFire) {
...
}
that's fine
you could do a million of these statements
The node
public class SomeComponent : MonoBehaviour {
public SomeNodeReference _node;
}
nah
why not just add a reference to Status at that point?
doesn't make sense
i don't know what is inefficient here
there's no nodes
nodes and trees have nothing to do with your problem
your problem is reading a variable, for which there are many facilities
don't create a new way to read and store variables
it will be inferior to reading a variable
you could have a component with a list of all stati that the object has
What I gave was a simple example, there are many other scenarios where it would be helpful. One would be using it as a param for an event for triggering particles. Or checking as a way to group ScriptableObjects, like if you have an Item SO with a tag field. You could have a slot that only accepts items with a certain tag.
It also acts as a way to abstract the systems from each other.
if you want to make a group of scriptable objects
MyScriptableObject[] group;
// check group membership
group.Contains(target);
if you want to trigger particles...
...
i think you get it
I know there are other ways to do this. It isn't like using tags like these are the only way by any means
there is one best way to do "variables" đ
just... do the thing
i cannot wrap my mind around
public class SomeComponent : MonoBehaviour {
public SomeNodeReference _node;
}
being superior in any example
just being real
That was just an example of what I meant when I said reference a node.
maybe specify the problem again, with all its requirements, maybe this discussion has gone off the rails
focus on the
concrete problem
not the subproblem of the nonproblem of creating a new way of storing variables in tree form
the concrete problem is to make a generic thing
nah...
you are misinterpreting what the profiler is telling you
I am trying to find a way to serialize and keep a reference to a node in a tree that is stored in a central database(SO, jsons file, whatever).
And then at any point efficiently check the ancestors of the referenced node.
this is a red herring.
the profiler is telling you what is slow
seems like all you need for that has already been discussed
you can use my predecessor check code to "efficiently" check the ancestors of a tree
just based on what I've read I can't see why you need tags like this at all
you can use a custom property drawer to interact with an "x" in a datastructure "y"
it can be as simple as
[Serializable]
public class InspectableNode {
public int nodeId;
}
[CustomPropertyDrawer(typeof(InspectableNode))] {
// logic which interacts with whatever to populate your editor
}
Yeah, I was going to ask you is it really that bad to not compact the list and instead keep a second list of 'empty' indices? (genuinely asking as I don't have much experience in this area. Is it considered pretty ugly?)
The only other option I can think of is using an SO for each tag as those keep references across scenes.
none of what you discussed resulted in efficiency gains
i will guarantee you my while loop will outperform 100% of alternatives to "efficiently" encode ancestors
Maybe a more concrete example would be I have a area in my game where you can place things. Anything from plants to lights to decorations. If they each have tags, I can easily keep track of the different types of objects that are in that area.
it introduced a lot of potential bugs on top of making things slower
if you want to see what objects are in an area... enumerate them
if you want to see where you can place things... create a list (or if it's large, a set) that says what you can place, and check membership in it
Yes, but again I need to serialize a reference to the node so I can get its parents.
(gtg for a bit, feel free to continue as I will come back and read up on what I miss)
for small groups, an array will outperform a hashset
you don't need to serialize a reference to the node
you need something that is weird that you happen to want to use the unity editor's inspector to interact with
which will be impossible to do without a custom property drawer
that should be signaling to you that what you want is a bad idea
or can already be achieved by something else
impossible? people use ScriptableObjects as tags all the time which already has pog editor support
the user doesn't want a tag
i don't really know what the user wants
it sounds like a reinvention of "variables"
the idea of having "variables"
you already have variables
variables, but also, classes..
it's tough to say!
sometimes classes, but also sometimes, just group membership
I might be making connections that aren't there, but it sounds like they're trying to do ECS, or at least part of it
The way they talk about tags sounds a lot like ECS components to me
based on this it just sounds like they want tags, so you can just create a "Tag" SO and name it whatever your tag is
I think you're over complicating it
anyone familiar with game objects being stored in lists?
yeah actually I agree with this
Unity ECS would automagically give you a "tag hierarchy" thing where you can get every object with House + Fire or Plant
and do it in a super performant way with archetypes and chunk management
Ok so I am storing a game object with a script in a list. The Game Object is called TTScore. The Script is called DefaultScores.cs, and it has variables in it "Initials, Score, Deaths and Level.
What is the proper syntax to get the variables for the objects in the list?
is this the proper syntax:
Debug.Log("This is for index 10. Initials: " + theDirtyDozen[10].GetComponent<DefaultScores>().initials```
?
assuming you spelled everything right
yes
Ok so the NAME of the Object doesn't matter at all then
ok
đ
I was trying to call the object by name.
That comparison is not entry inaccurate. I guess I would put it like this, it is just like how you would use Unity's Tag system, but with a hierarchy and more data oriented (at least in my use)
But @smoky maple is right, it is basically just SO tags. I have several reason why I don't want to just use SOs though, they feel more cumbersome than what is needed., the API is messy(for this use case) and they clutter the project browser.
I might still end up using them though as they allow for being referenced across scenes and assets easily. And I can have them as sub-assets of a main one.
I do want tags. Perhaps some of the examples muddied the waters so I apologize. Its just a unique identifier which can be used for comparisons.
(And has hierarchical information)
@undone coral You were not kidding! 10k steps takes ~60 seconds with my CPU maxed and gpu @ 60%
I am running 7 headless envs
Reward is still trending downward but episode length is trending up pretty sharply so I think there is hope
This is so exciting! Training my first ML agent đ
(excluding the hummingbird tutorial)
How do I assign an alembic to a timeline track using script
Ok, no one can help me in #đťâcode-beginner so I hope someone here can.
My atrocious code: http://pastie.org/p/5AhlwthDvcxC38FsXBdy76
So, what I'm doing at the moment is my 2d gameobject table occupies a 4x4 tile when I place this table on my tilemap during runtime I keep track of all 4 sprite because my table gameobject is split into 4 different sprites so each sprite will occupy a tile and not only that I place them manully on the tilemap as you can see in the code. What I want to do is keep my table gameobject into a single gameobject and tell my tilemap to treat it as a 4x4. This will make it easier for me as a implement more gameobjects and bigger objects in the future and as well adding new features such as highlighing the gameobject when selected by the player.
Is there a question?
Hey folks, im tinkering on a solution to share parts of a game with a server. I can isolate that part into a .net standard library and import in the project as a plugin but that's not really handy for development.
Was wondering if there's a way to either compile the unity game as a .dll that can be imported into other projects or any ideas on what be a good practice to do this.
Sharing a library dll is the way to do it (you can use a build script to automatically copy it to the client/server projects or publish it as a package they both depend on), if thatâs inconvenient make the server and client the same app/project
The inconvenience of having to copy the dll is mainly for debugging and cross team development - its still something doable. Using the same app/project would mean i gotta run a unity game as a server right ? ( Like Mirror )
nvm someone was able to help me on #đťâcode-beginner but thanks
Yes
actually i'll move this to #archived-code-general
Hello everyone, I play the game VRchat, Recroom and I thought how did they make it possible to load so many rooms within the game for download? Do they use addressables/asset bundles?
lol
is this on a 5x5 board?
Oh no I mean physically too short, like not tall enough
pieces are 1x2 and spawn vertically
i meant have you generally looked at the profiler
oh, ya
The best solution I could come up with for rewards was to rank the next valid moves
so thats the step thats taking the most time, for sure
Is there a way to spawn a new OS window (possibly using mono winforms maybe?) and then draw a Unity RenderTexture to it? Iâm trying to make a separate window that can be captured as an overlay for streaming
Hmm, specifically this is for a mod, so I donât have direct control over setting up displays..think that still might work?
no idea
Harmony might be an option though..
It's pretty much either using Unity multi display or using a native windows plugin
Native is also an option - just not sure how to draw the texture to it
GetNativeTexturePtr?
You could also send the texture pointer directly to an OBS plugin, if it's going to end up in OBS
That's what this plugin does, though not related to Unity
https://obsproject.com/forum/resources/openvr-input-plugin.534/
This plugin provides an input plugin to 64bit OBS that allows capturing directly from OpenVR/SteamVR mirror surface in full resolution.
Either left or right eye image can be captured.
Cropping can be configured in the plugin properties, with...
Thatâs an interesting idea..I have a couple other use cases in mind that arenât specifically for streaming though too (like hooking up small dedicated screens)
Seemed like making a new window would solve both
Then I think your best bet is to just send the texture pointer from Unity to another process. It's probably not going to be fun to try to manage a separate window from within a mod within a Unity game.
Hey everyone, I have a UnityEngine.UI.Toggle, and I want to intercept the event when it's clicked/submitted to do some validation and potentially stop it from being toggled on if the validation fails. I can hook into the onValueChanged event, but this is too late as the toggle will already happen and trigger callbacks/events (like untoggling others in the Toggle group). I'm not really seeing or at least understanding a way to do this, does anyone have a direction that would make this doable?
Put a proxy handler between the toggle and any other subscribers by having them subscribe to a similar event on the proxy that gets invoked only when your validation succeeds
I'd like to, but what I'm struggling with is how to avoid the built-in subscription of the click/enter event that toggles the toggle state and switches off other toggles in the group
turn off raycast target on your toggle and put a proxy invisible button in front of it instead that runs the validation check and then toggles the toggle if it succeeds
Yeah I thought about replacing it with a button then swapping to the toggle or something similar. I don't think an invisible one on top would work because I still need the navigation animation (selection, hover, etc.) so I'd need the button to completely replace the toggle for navigation purposes (otherwise like with keyboard you'd still select the toggle and press submit on it). I was hoping I could just intercept the event instead but doesn't seem possible.
Oh maybe I can extend the Toggle class and override the OnSubmit and OnPointerClick methods
you can get all of the navigation animation stuff by setting the transition target on the invisible button to be the toggle's graphic
basically set its transitions up exactly as the toggle's transitions are set by default
a button with custom handler is often the easiest way to make a âfancyâ toggle instead of hacking a builtin toggle into submission. You can also make a fully custom widget by inheriting Selectable and implementing IPointer.
Yeah extending the Toggle class with my own and overriding OnSubmit and OnPointerDown is exactly what I was after, something like:
if (Validate()) {
base.OnSubmit(data);
}
}```
I think I'd rather make a custom fancy toggle from a Button instead of trying to have an invisible button and make sure the navigation and animations make sense between both of them. And yeah, agreed, toggle are surprisingly not helpful, like you can't even easily get the currently selected toggle from a group???
Hey guys! I have several Head meshes containing 3 submeshes ( skin, eyes, teeth ). The problem is that the submeshes are not in the same order for all the Heads, which is a requirement for a task I'm working on. Is there a way to permanently modify the submesh order? I've tried swapping the submeshes of the sharedMesh and it works until I restart the editor or reimport the mesh. Is there any way to do this permanent?
The code that I'm using for the submesh swap is:
var swappingSubmesh = meshToUpdate.GetSubMesh(swapIndex1); meshToUpdate.SetSubMesh(swapIndex1, meshToUpdate.GetSubMesh(swapIndex2)); meshToUpdate.SetSubMesh(swapIndex2, swappingSubmesh);
where meshToUpdate is the sharedMesh
you need to save the change back to the asset
if it's getting imported from an external file then you can't permanently modify it bc it'll be overridden by the import
but you can create an external clone in import and modify that
hey @granite viper thanks for answering! I appreciate it! Do you have any suggestions on how to save the change back to the asset? Are there any links that I can follow? I've read the Unity documentation and they said that modifying the sharedMesh is permanent, so I thought that should take care of it
I don't have enough context
where is the sharedMesh coming from
an external mesh file?
The code from the submesh swap belongs to an editor tool I created that modifies an imported mesh in Unity. Modifying that imported fbx and making sure it's permanent would suffice.
I'm assigning the mesh as a reference to the asset in editor mode
Check out AssetDatabase.CreateAsset to save to disk
something you can also register an asset preprocessor
I've tried doing that, but it failed stating that the mesh was already an asset
you'd need to save it to a separate location
you can't save it back to the original file
actually you'd want the postprocessor
will take a look! Thanks! I appreciate the help!
modify the FBX file to have the correct order. you can convert it from binary to text format to do this
FBX binary -> FBX text -> modify order -> FBX text -> FBX binary
don't try to modify this in a post processor
too many pitfalls
create a unity package.json for your ordinary dotnet project
reference that package in unity
đshare the codeđ
helllo any way to create a quaternion from scratch in unity ?
like with control over all parameter
I already mentioned yo you above...
or rather in the other channel
yes but its not what i need
what do you need
ah, the ol' Homemade Quaternion
six pages of personal story about grandma's quaternions
ill wait for the end
I mean you can make a new Quaternion(0, 0, 0, 0) but why on Earth would anyone do that
Dunno what you're asking but all the ways to create a Quaternion are listed here https://docs.unity3d.com/ScriptReference/Quaternion.html
as I said before
to leeeeeeearn
except I guess...
Quaternion q = default;
q.x = ...
q.y = ...
etc...```
furiously take not
Are there any good utilities for compressing byte[] audio data thats being sent over a network rapidly?
DeflateStream seems to work so far but i'm looking to compress the data more heavily
if you want to "make quaternions" you'll have to learn the math straight from a text book
there are many insights before you can understand what they are
it's very mathy
yes that, but if you don't know what those x, y, z ,w are (I certainly don't, not without a refresher) then it's not useful
dont hurt yourself in the refresher
Much more useful in day to day life are these:
https://docs.unity3d.com/ScriptReference/Quaternion.AngleAxis.html
https://docs.unity3d.com/ScriptReference/Quaternion.Euler.html
https://docs.unity3d.com/ScriptReference/Quaternion.FromToRotation.html
etc...
they are basically a thing that, when using multiplication alone, gives you numbers that are periodic
and they're way more complicated because it expresses the periodic properties of 3d rotations
whereas 2d rotations are pretty basic
this one is very good to start https://www.youtube.com/watch?v=d4EgbgTm0Bg
How to think about this 4d number system in our 3d space.
Part 2: https://youtu.be/zjMuIxRvygQ
Interactive version of these visuals: http://3imaginary1real.com
Help fund future projects: https://www.patreon.com/3blue1brown
An equally valuable form of support is to simply share some of the videos.
Special thanks to these supporters: http://3b1b.c...
well.. unless you do the textbook problems
you're not going to get this insight
what's your objective?
learn to use quaternion and get a feel for them
you definitely want to use Quaternion.AngleAxis and Quaternion.FromToRotation
that is a math class problem not a unity problem
because i don't know how thos function work internaly
hmm.. the way to express rotation sin quaternions is 1 piece of a 10 piece puzzle
thanks for your suggestion! How do I convert the FBX to text? Is there any built-in option in Unity? I haven't found any
easy puzzle then
if you are exporting from a 3d graphics program that's the easiest way
otherwise use a utility on github / autodesk
thx all
got it, thanks! đ
You don't need to learn how they work internally to get this feel and knowledge of how to use them. Remember I wrote that rotation/normal sticking code for you with Quaternions. And I have very little idea of how they work internally. I just know how to use them, compose them, create them, and work with them.
based on my research online
yes but im still confused about it so i want to learn about them intimately and also i didnt find a way to smooth the rotation + i had a gimble lock problem so i want to start over
its a 10^100 piece puzzle is it ?
luckily
i got cookies
you could try to do #4 from https://people.math.harvard.edu/~elkies/M55a.02/pdflatex/pp.pdf and you will understand quaternions
at a deep level
for me to answer these would take like 100 hours
you don't need that knowledge to solve either of those problems. I don't want to discourage you from learning, but I'm telling you it's not necessary.
The best thing to learn is just what Quaternions are and how they interact when you combine them, e.g. by composing them with *
i know thats why im doing it
if you've never written proofs at a university mathematics level then you should start with that
honestly i'm not sure i'd get it even after 100h
i didn't do well in 23a
i hate proof i prefer proof by "good enough"
if it work it work
it is what it is
those 3 are good
hmm
btw can i get a stack overflow if i let the debug.log every frame for too long ?
or is there a safety ?
you won't get a stack overflow
thx
Lines are going up! đ
I had to clean the intake filter on my radiator. it's been so long since i put any real stress on this computer it was fully clogged and I didn't know it
had several crashes
@undone coral it took 700k steps before Cum. Reward hit positive
cum ?
cuuuum ?
CUM ?
cumulative
I'm training a neural net to play my game
cumulative reward going up means that it's getting better at playing
if the number is positive (in my specific case) it means that the ai is making good moves more often than bad moves
guys, in my online game using pun, whenever the master client instantiates objects and then leaves, all of the objects instantiated by him get destroyed as well, I want to transfer all of them to the new host. How can I do this?
Made a PID controller to follow my XR controller. When I'm in the editor and just move the XR controller transforms manually (no headset) it follows it fine but when I build it and play it on my headset, about after 5 seconds it seems to just kind of disappear :/ can anyone explain why?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I've fixed the issue using Postprocessors! Thanks everyone! Specially @granite viper!
yay
you can train on a google colab instance
using a TPU
but i doubt that's going to be your bottleneck
No i think I have to come up with some alternative training methods
it's good it's making some progress
Man i am starting to hate xml, why did i choose this shenanigans f
run the profiler and see what your bottlenecks are
i dont know if it belongs in this channel but I am currently working on a tower defence game and i try to implement turrets shooting at enemies right now, but im a bit stuck. Can someone help me? What is the best way to implement bullets flying from turret to enemy (and chasing them till they hit) and on impact get deleted and deal damage?
it's better to start working at it and then asking a question when you get stuck
Hey, what would be the best way to save a number that anyone who plays the game can see and change? (this is on WebGl btw). I don't know anything about server hosting or online stuff Lol.
Yes, but I only need to get it and set it a couple times for each player, so it doesn't need to update constantly in real time
How do I load an audio file from out of unity?
I have a single component that is getting rather large in size. I could divide it into multiple components, but that would be purely for organizational purposes, because none of those components would ever be reused separately. They would literally all just Require each other.
Are there any performance concerns with doing so? Splitting functionality across multiple components?
And is it worth the grief with sorting out script execution order
Not really. Unity was made to be used like that. You might notice faster compile times splitting it up, if you edit one
Oh really? đ¤
Depends how big it is
When I was first starting out, I had a massive 6k line God component on my players. Would take ~30s to compile each change. Splitting it up was a huge difference
Oh wow lol. Mine is nowhere near that ,compile times haven't even been an issue yet, it's just an organizational concern
I've been itching to bust it up but felt like more components might be a hit on performance
It's getting to be a bit of a mess lol
I personally feel like if they all require eachother and will never be reused, not a whole lot of point in separating them out
But you could likely get them to not require eachother, but that sounds like pain
not a whole lot of point in separating them out
Like I said just working on the file is starting to be a mess, organizational schemes coming apart at the seams trying to keep relevant things somewhat together lmao
It's 'only' 1k lines
Yeah that's a bit big
Here's another question for you anyone
From what I can find properties are wonky with Unity, correct? Tricky with serialization or something?
Actually, better way to put it, do you use public fields, private with [SerializeField] or properties (somehow?) đ
wut
oh I had to reread that a couple times
what I use entirely depends on the situation
since I don't use custom serialization I don't use properties
A lot of unity stuff seems to just make literally everything public fields and say F it
Which goes against my usual programming instincts lol
But without properties you have to do getters and setters which is đ¤Ž
Fun tip you can do
[field: SerializeField] on an auto property to serialize the backing field, and it'll work just like normal
If by normal you also mean the name that is serialized is <PropertyName>k__BackingField, sure đ
That's not an issue anymore right? xD
It won't appear like that in the inspector, but it will serialize as that
which makes it difficult to work with when refactoring (using FormerlySerializedAs), or making editors or property drawers (using FindProperty).
Woah I guess I've just never run into an issue with it
If I use different layers, will masks in different layers not interact with each others?
What mask are you talking about? Culling mask, ui mask, physics layers?
I want to make several culling masks on different sprites and I don't want them to interfere with each other
Hi, i'm trying to make an external C# program press virtual keys in a unity project. So far I've got something to the effect of ```cs
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
private static void PressKey(Process proc, int aKeyCode) {
const UInt32 WM_KEYDOWN = 0x0100;
PostMessage(proc.MainWindowHandle, WM_KEYDOWN, aKeyCode, 0);
}
```in the external project. This works perfectly when the process i'm calling PostMessage with is a text editor of some sort(vscode, notepad, discord, and so on...) but when i try it with Unity it seems to not receive or at least react to the key presses being sent. Does anyone know if you need to do something special with Unity to make it accept the inputs? or am i perhaps using PostMessage incorrectly? Thanks for any help đ
- That P/Invoke isn't correct (you have some pointer-sized values passed as
int, among other things), it should be:
[DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PostMessage(nint hWnd, uint Msg, nuint wParam, nint lParam);
(Replace nint with IntPtr and nuint with UIntPtr if nint and nuint aren't available in the C# version you have)
- You should call
Process.Refreshbefore retrievingMainWindowHandle, because theProcessobject may be outdated. That said, I don't believeMainWindowHandleworks properly in Unity (iirc), you instead need to query for all window handles in the process and callPostMessageon those.
thanks! I greatly appreciate the help. I think i've managed an implementation of your suggestions now. however, it still refuses to get any keystrokes to unity
What value are you getting from MainWindowHandle? It might be IntPtr.Zero, which would just send the messages to the current process
Hello everyone. My event triggers do not work with my instantiated prefabs. The units I instantiate onto the board do not respond to the event triggers. Static objects that I created in the hierarchy, however, do. Does anyone have a solution? Let me know if more info is needed!
https://forum.unity.com/threads/event-trigger-doesnt-work-on-instantiated-prefabs.427481/ this person I think had a very similar problem to me, I wasn't able to apply the solution though
the process id is a non-zero value and the 3 window handles i got under the process seem fine aswell
Unity might ignore inputs received through window events in favor of using its own input system
forgive me if i'm uninformed, but i don't see how unity would read keyboard events without getting them from a windows message loop?
and should not a PostMessage to such a loop be indistinguishable from a hardware device as far as the process is aware?
DirectInput is one option
or the Windows raw input API
(Which can still receive input through the message loop, but not through the older WM_KEYDOWN-like messages)
Okay yeah, looking at disassembly of a function inside the editor (GetMessageEventName)
It only cares about WM_INPUT
Which is translated to Unity's own Application.Message.Input
alright, i'll give WM_INPUT a shot then...
Ok yeah, looking further, it listens to the mouse-related WM_ events, but for anything else it only cares about WM_INPUT
interesting
I mean, it's totally possible I'm reading this wrong, but that's what it looks like so far
i'm currently trying to whip something up capable of sending a WM_INPUT event but it seems more involved than the WM_KEYDOWN event
Yeah it's quite a bit more complicated
As a test you could try sending WM_MBUTTONDOWN and see if Unity reacts to it, just to make sure I'm not misreading how it responds to messages
That's one it doesn't ignore, as far as I can tell
Looks like you'll need to P/Invoke GlobalAlloc, GlobalLock, GlobalUnlock etc to create a WM_INPUT event manually, since it requires handles
yeah, from what i'm reading it seems like if it needs a lParam pointing to memory alloacted with Marshal.AllocHGlobal and written into with some arcane magic. the API only seems to document how to receive it and nothing about how to generate one đ
Specifically it needs a handle to that memory, not an address to the memory itself
Which isn't something you can get with AllocHGlobal
You'll need to P/Invoke the actual GlobalAlloc etc functions
great... more fun...
but yeah i'll give WM_MBUTTONDOWN a shot aswell and see if it likes that atleast...
Since this is an external application and not something in Unity, you can add the TerraFX.Interop.Windows NuGet package
It has all of the proper P/Invokes and stuff for this already
You'll need these imports:
using TerraFX.Interop.Windows;
using static TerraFX.Interop.Windows.Windows;
And then you can use the APIs as if you were writing C
var hInput = GlobalAlloc(GHND, (uint)sizeof(RAWINPUT));
*(RAWINPUT*)GlobalLock(hInput) = new RAWINPUT
{
// ...
};
GlobalUnlock(hInput);
// send event with hInput as your lParam
(you need to enable unsafe code in your project though, of course)
i seem unable to install the package? i'll try with a fresh one, hang on...
currently net5.0
.NET 5 is going out of support soon, I'd recommend moving to net6.0 yeah
In fact I think the latest version of the package requires .NET 6
sorry to ask a more basic question but i seem unable to install .Net 6 from the Visual Studio Installer. i can't see the SDK for it in the component list
You can install it from the .NET website https://dot.net/
yeah, i tried that aswell but it doesn't come up as an option for new project
yes
Only VS 2022 "officially" supports .NET 6
So for 2019 you need to edit the csproj, yeah
You can also use the dotnet command-line tool
i tried editing it aswell but it only complained at me
dotnet new console -n ProjectName
cd ProjectName
dotnet add package TerraFX.Interop.Windows
dotnet build -c release
I haven't used VS 2019 for quite some time, so I'm not sure of the specifics of what you need to do to target .NET 6 beyond editing the csproj though
oh wait, i got it to compile
seems it sorted it self out after a sdk repair and a restart
haha! slowly climbing back out of the rabbit hole đ
Now comes the hard part lol
yeah. boggles the mind that this is supposed to be the easy bit
ok, next problem. how do you init the structure? ```cs
unsafe {
HGLOBAL hRaw = GlobalAlloc(GHND, (nuint)sizeof(RAWINPUT));
RAWINPUT* pRaw = (RAWINPUT*)GlobalLock(hRaw);
// init pRaw here?
GlobalUnlock(hRaw);
External.PostMessage(hWnd, WM_INPUT, 0, hRaw);
}
As in, how do you assign to it, or do you mean what do you even put in there?
what to put
That much I don't know
setting should only need a dereference yea?
yeah
Looks like RAWINPUT is basically a union of input structures, with a header describing which one it actually contains
ah, so basic tagged union
yeah
*pRaw = new RAWINPUT
{
header =
{
dwType = RIM_TYPEKEYBOARD,
dwSize = (uint)sizeof(RAWKEYBOARD)
}
};
I was typing this out, but I'm not actually sure how you're meant to get a device pointer
I assume you just enumerate keyboard devices using raw input and pass one of those in
btw TerraFX exposes PostMessage so you can just do PostMessageW(hWnd, WM_INPUT, 0, hRaw) https://source.terrafx.dev/#TerraFX.Interop.Windows/Windows/um/WinUser/Windows.cs,450
Though you'll need using static TerraFX.Interop.Windows.WM; too
or rather PostMessageW((HWND)hWnd, WM_INPUT, 0, (LPARAM)hRaw); probably
ye, PostMessageW((HWND)hWnd, WM_INPUT, (WPARAM)0, (LPARAM)hRaw) even
0u might work instead of (WPARAM)0, I think it has an implicit cast from an unsigned int
this is an option, but i recommend a newer approach, in case you didn't know about it yet. there's the CSWin32 project, that uses source generators to give you up to date, project specific code without unneeded api's. https://github.com/microsoft/CsWin32 especially for non-unity projects, i highly recommend it. @frank moat
TerraFX.Interop.Windows is also generated
CsWin32 and TerraFX.Interop.Windows actually share a bit of architecture
Personally I don't like CsWin32 for a number of reasons, but they both get the job done
oh? like what? i'm curious.
I'm not a fan of the generator approach, at least how it's done currently. Editing a text file feels super clunky, and I don't like the way it deals with marshaling
TerraFX is basically the one to use if you want 1:1 signatures
It also provides a lot of niceties for COM interop
the 1:1 signatures approach is exactly why i do not like TerraFX, without the marshalling handling of the generator you lose a lot of safety
Hya. I'm instantiating folders full with prefabs in editor mode, using Resources.LoadAll and looking up typeof(GameObject). They spawn, but the prefabs are all completely unpacked. Any suggestions for instantiating prefabs in editor mode?
Marshaling can have a significant performance cost, and arguably marshaling can be more unsafe depending on how the function works
I understand the argument for either, and personally my stance is "pick your preference"
I just don't like CsWin32 myself
recommendation: do not use the resources folder. it'll mess with the maintainability of the project immensely
Addressables are usually the better option, though the Resources folder still has its uses
Just be aware that anything in the Resources folder will never be trimmed from a build if it isn't referenced
that is true. but i was under the impression that CsWin32 was also explicitly striving for providing the best marshalling option. so....
but yeah. i guess 'pick your preference'
whats the better way of doing it? I have no commitment to the recourses folder
Addressables
You basically get the IResourceLocations of each asset, and then you can load those
checking it out now, thanks
i do understand the text file feeling clunky, but, it's not all that bad. what i might see as a better alternative is putting the api's in property groups like for implicit usings
The approach you generally take with TerraFX to remove unused stuff is to publish a trimmed build
eg -p:PublishTrimmed=true
The generator approach CsWin32 takes is an interesting idea, but I feel it's unnecessary and makes it harder to make reproducible builds
yeah, but i don't really like trimming. takes more time to build and might not trim all
The trimming infrastructure in .NET 6+ is really good
It doesn't really take that long to trim
um, 'harder to make reproducible builds' exactly how?
yeah, but still not finalized and i've experienced a few issues
You don't have a versioned library to depend on, if the data the generator uses to produce signatures changes, then so does your output
but that's actually a problem imo. if you build for a different windows where the api you're using isn't available, you won't get errors with a versioned library. you'll immediately get compile errors with the generator
That's what the OSPlatform analyzer is for
If you try to call an API that isn't supported on the current platform, you'll get a build warning
There's OperatingSystem.IsWindowsVersionAtLeast etc
all of the TerraFX APIs are annotated with the SupportedOSPlatform attribute to work with that
It's a much better approach because it also allows you to produce a single dll for all platforms if you desire to
:/// i guess it's really a preference. i'll like to keep it slim and down to the metal
SupportedOsPlatform is not from TerraFX though. the generator also has this
I know, it's part of .NET itself
I'm just saying it's an overall better approach because it lets you publish an "all platforms" build, but also a trimmed per-platform build
you get the best of both worlds, basically
hm, idk.
anyway i wanted to ask, do you have a bit experience with asp web api? or anyone here currently?
I don't have much experience with web-related stuff in general, I consider myself lucky lmao
true. unfortunately i am now stuck with my project
anyway, if anyone has an idea of how i can add a custom json converter for the web api json deserializer to work with on parameters / or how i can change the schema of a parameter, that would be massively appreciated
How do I sort an array of gameobjects alphabetically by name, in an editor script? Ive been trying to use OrderBy and iComparable etc but I cant seem to wrap my head around it
I keep getting ArgumentException: At least one object must implement IComparable.. errors
and I cant seem to find another way to sort an array alphabetically, lacking some serious Google-Fu today
.OrderBy(static gameObject => gameObject.Name); should work
Doesnt seem to work im afraid. No errors, but the list remains unsorted
I'm just using it like convertedObjs.OrderBy(static gameObject => gameObject.name); that's correct right?
hmm I can't assign it to a List<GameObject> . Types mismatch?
Yeah, you need to call .ToList
if you have a list and want to sort it, use .Sort() instead, otherwise reassign it
yeah the .Sort gave me the ArgumentsExceptions
I got it to work. convertedObjs = convertedObjs.OrderBy(static gameObject => gameObject.name).ToList();
đ yeah
So, just so I understand, instead of implementing iComparable, we're giving the OrderBy function the parameters of the ordering
correct. if you had something like cost then .OrderBy(static object => object.Cost);
And, the implementing of the iComparable meant a function in the class that's using the OrderBy / Sort, correct?
IComparable is just a CompareTo function
IComparable you only need when you use .CompareTo() to compare something
like here
String implements IComparable so this works
So i have three classes, Character Data, Character Save Data, and Game Data. Character Data is a container for data attached to a NPC and before save is transferred to Character Save Data, added to a Game Data class (basically a wrapper) and then saved in XML.
this is following a shitty implementation of the Memento pattern
hey there I'm having a really long issue
so this is a lot of code, I know
I want to create a 2D endless runner game with a tilemap-system for the ground
and it should sometimes spawn a 1-block higher platform consisting out of a random length of blocks
and based on what neighbour the tile has it should change to a different version, meaning it should turn into a different tile for example that connects to the left or right
however it always spawns the same tiles and I have no idea why
I figured out it had to do something with the SpawnSpecificTile-function that is called in SpawnTiles() where the green comment is
you might have to call RefreshTile on the tile after you set it
oh thank you
though I thought it changes the graphics automatically
even when I refresh all the tiles it doesn't change anything @gray pulsar
How do I set class variables in scripts without having them attached to a gameobject?
Basically, I have spaceships that can be customized with different modules. The modules obviously have differing textures.
I want to make it so that the texture is attached to the module, and whatever I'm using to render it can just call module.texture to get the texture.
anyone have the source code for Random.GetInsideUnitCircle(out Vector2) or how the method works?
Modding discussion is not allowed in this discord.
i'm not discussing modding tho, just asking if anybody knows how i can get the same effect as GetInsideUnitCircle
wtf why?
i can rephrase the question if its an issue
Because it is generally indistinguishable from a license breach of the target software
i'm not seeing anything
the devs' of the game are cool with it
and its not illicit modding
RISE UP for mainstream modding
i don't see why its an issue
That is not relevant
it's their software...
any game can be modded
I think it is well known that this server does not allow the discussion of modding
and devs should never oppose it. boycott all devs that do that
Then it should be added to the rules, because I checked the channel too and didn't see it there.
rise up for freedom of creativity
^
.
you don't own the software after you mod it, but you own your parts
again, it's their software, they're perfectly in their right to disallow modding
Also, even if they didn't allow it, it would be fine as long as you didn't publish or share it and solely did it for personal use.
That is not relevant as nobody here wants to verify that
depends what the mod does
As long as it doesn't touch ripping the assets and decompiling the code it is fine.
@noble granite You are looking for https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html
private ownership is bullshit anyway. it's only there to strip money from people
That's laughable
I'm definitely in support of modding, but that argument is shitty, people gotta pay their bills somehow.
you cannot even patent software
i am, but that has been stripped by IL2CPP, i'm wondering if there's another way to calculate it
Most idiotic statements since the invention of civilization
Have you heard of copyright
Fogsight, if you're still here, is it fine if I repost my question in #archived-code-general, as it was buried here by this conversation.
Patents protect inventions
otherwise known as 'illicit modding'
sure
you mean the thing that prevents creative people from improving existing products?
I think we're a bit off topic, but I think you're a joke
Not sure what you are talking about. Make sure you're not mixing it with System.Random
thanks. đ enjoy capitalism
Here is how to implement a decent function yourself https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly
okay so, i'm modding a game where UnityEngine.Random.insideUnitCircle has been stripped by IL2CPP since it is not used. Thus i can't use it. So i need to calculate a random point in said circle myself, since i cannot access the property getter.
anyway thanks Anikki
Basically get a random number between 0 and 1 multiply by 2 * PI, generate a random radius, convert that point defined by the arc and radius to Cartesian coordinates
why is there a strive for this in the hardware sector https://repair.eu/, but not in the software sector?
Itâs called open source software and is abundant
Be sure to take the square root of your radius normalized to 1 if you want an even distribution within a circle, or else points in the middle will be denser.
it's very easy ```cs
while (true) {
var x = (Random.value * 2f - 1f) * r;
var y = (Random.value * 2f - 1f) * r;
if (x * x + y * y < r * r) {
return new Vector2(x, y);
}
}
``` pop that in a method with r as a parameter
or just use rejection sampling, as i show
Dude, stop bringing politics into a Unity programming support channel, everything has a place and time but that's not here and now.
although if Random.value has also been stripped then just use some System.Random bullshit if you can
This will not be uniform and inefficient
that is distinctly different. RTR does not depend on open-spec-hardware. it specifically targets company hardware that is not open
it is uniform and more efficient than sin and cos
as long as Random.value is uniform which it is afaik
Still wouldnât use it since itâs not guaranteed to terminate
it is tho
Yeah, just do the square root thing.
That doesnât guarantee it terminates in all cases
why not
the rng could always produce points outside the circle
yes
Technically there is an infinitessimally small chance that it will just continue indefintiely.
true but that's not realistic
public static float PI_2 = 2 * Mathf.PI;
public static Vector2 GetRandomPointInsideUnitCircle() {
float radiansCos = UnityEngine.Random.Range(0f, PI_2);
float radiansSin = UnityEngine.Random.Range(0f, PI_2);
return new Vector2(Mathf.Cos(radiansCos), Mathf.Sin(radiansSin));
}
public static Vector2 GetRandomPointOnUnitCircle() {
float radians = UnityEngine.Random.Range(0f, PI_2);
return new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)).normalized;
}
Why not just this
Those have a tendency of happening though
That was my original suggestion
i mean, be my guest if you wanna use the sqrt or whatever, it works, the difference in performance isn't that large
didn't even see your original post
oops
but just sayin my way is more efficient (although it's not that big of a difference), since it doesn't use Sin or Cos, and while it is technically not guaranteed to terminate it is just so unrealistic that it would never get a value within 2-4 tries
I'd personally rather take the hit with a sqrt than a while loop with a possibility of non-termination. Just doesn't make sense to me tbh.
i do get the point and it is valid technically but imo since the chance to fail n tries in a row gets very small very fast it's worth it
and also because i like how an infinite while loop with a return looks
Could guard the random sampling with an iteration limit that returns vector2.zero if it ever triggers
would be valid and equally uniform if the limit produces an expected value for a trigger > the error for uniformity
Could also use a fast sqrt and accept the error
i guess
or use an approximation function derived with some machine learning
i mean this is getting a bit ridiculous
But fun
tru