#archived-code-general
1 messages · Page 72 of 1
And the script also is being used for multiple cubes
So?
change the type of owo from string to Transform. then you can set owo to collider.transform
You're getting the reference on OnTriggerEnter aren't you?
Transform is a data type?
Yes?
it’s one of unity’s
So then that’d work
So why would the name help you more than directly using the reference?
Because I need it to happen repeatedly
you should familiarize yourself with Unity’s data types and not just C#’s. I think that’s where you got stuck on
The name is not what you want here
Thanks for the advice
It literally worked though
?
I need the name to be stored so then I can move that data into the update function
No
So then the movement of cubes can happen repeatedly
The name is not useful
I’m going to say this as respectfully as possible. Fuck off
Please and thank you
The Transform reference is useful
/shrug some people prefer ignorance
Ohhh noooo, how shall I code without your oh so important advice on code that already works
D,:
You were speaking to one of the more skilled people in this discord, before you told him to fuck off
good luck getting help beyond that
I would've told you exactly the same thing praetor did, for your problem.
You can store the name in a string variable, if it's really that important right now.
When I stored it in a string Unity was giving a incorrect storage error
what is an incorrect storage error
But pumpkin let me know that Unity has special storage type called transform
The top box on this
So you weren't storing the string. You were trying to store a collider in a string
and it told you that
Ohh
Generally this is why you listen to seniors
instead of giving up and calling them an asshole
I did not actually, I specifically said they were being rude
Do not exaggerate the situation
I was also trying to follow along with someone else who was giving proper explanations and not just short answers without context
Whom they were talking over
There's a reason why he was telling you to do that.
You are wasting space storing individual names as strings
they are already stored in the transform
and can be directly accessed from the transform's reference. The reference is the size of a pointer.
Arguably he wasn’t telling me anything because he wasn’t explaining
How could it be directly accessed from the transform’s reference?
So I need the objects name?
You need a reference to the object.
Generally you learn this stuff before you dive into unity
Is this what you meant for me to store?
Yeah, I’d change that of course
second of all .name is not a transform
I'm saying get the reference of the GameObject you want to store, get the transform from that, and set the transform to the reference
By reference are you referring to the name of? Or information of
I'm referring to the reference of the object in memory
Since you're posting in general I assume you already know how to get a gameobject
The information or name
the pointer
to the object
in memory
Again, this is why we learn C# instead of just trying to do random stuff inside unity
if you need help doing that, let me know
Boi, if I wanna practice c# in Unity I can do so, and if you don’t want to help me you can also do so
I assume that you would at least read over some documentation and understand how it works
Since you don't know what a reference is
I did so
GameObject myGameObject = GameObject.Find("ObjectName");
Transform myTransform = myGameObject.transform;
THAYS HOW YOU DO THAT?
Yas, thank you
Trust me, I do have the documentation open, it’s just difficult to sort through
Where do you recommend I practice C# if not Unity?
I mean it doesn't matter since you already have unity open
It's good to understand what an object is, how stuff gets stored in memory, rather than "update loop go brrrr"
I understand how it generally gets stored
I just didn’t know how to store transformation information, because that’s a Unity thing
Yup
One that I didn’t know about :)
“Update loop go brrrr”
You don’t have to help people if you don’t want to
Good lord
Keep in mind that there's only one object in memory, per GameObject.
If you reference "GameObject1" in one script, change the name, and then access the name in a different script with another reference to "GameObject1" you'll see the updated name
and with the transform reference, you can access literally anything gameobject related
https://hastebin.com/share/mapicizoje.csharp
Essentially what is going on is that I am moving the gameObject that the script is attached to back and forth between a undefined set loop of transforms using a horizontal input,
when going forward through the transforms, it will select the next one in line as the one to go to, however when going backwards for some reason, it doesn't select the one before it as the one it should be heading towards? (When it should)
Any ideas of why this could be happening? (2D URP)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is probably just something small I'm missing, I'm setting my NPC SetDestination to the selected object and due to the door in the way its setting the path to the front of the door which is the closest it can get. Is there a way I can force it to set the destination to the selected object (im aware the npc will get stuck at the door)
The door is a NavMeshObstacle right now
there may be a way to have the agent ignore obstacles but i don't think so...you are asking for two things which are directly contradictory
the nav mesh doesn't extend into that room because there's an obstacle in the way which exactly how it should be
you could try unchecking 'carve' so that the mesh does extend past the door
oh actually it looks like you do have some nav mesh in there, maybe you just need to set up a link between those meshes?
but it sounds like you want to generate your nav mesh based on anything that could be accessible, and then block parts at runtime
the doors gonna open for my little buddy i just need him to believe it's going to. right now he has no faith in the orange slab and takes the half measure of waiting out front
ill try messing with carve
right, because all he knows about is the mesh you see there, which has no way to get through the door
yeah just killing carve is probably exactly the right setup for me
tyty
Now that my blue boy gets stuck at the door, does NavMeshAgent have anything nice like a bool that lets me know if he's stuck?
Why don't you just detect he's infront of the door
then open the door?
wouldn't that be the most logical solution?
Thats the goal! But he won't be infront of the door unless he goes to it and his destination isn't what I want it to be things break
The pic you posted. Is that how far he currently gets?
if you are ever going to start a question with 'why don't you just...', I recommend not asking that question (or rephrasing it significantly)
dumb low effort response
'why don't you just...?' yeah totally, which is why i would say to avoid them
Nah thats Unity trying to be smart and setting the destination to what it can get to, and not what i told it to get to
no
yeh
No thanks!
everyone would be better off without the kind of help you are offering
oh sorry i missed this, navmeshpath has a status which may be enough info https://docs.unity3d.com/ScriptReference/AI.NavMeshPath.html
tyty
@night harnessyo sorry for hurting your feelings earlier. Gonna be the bigger person and apologize. It's now obvious that my tone of voice can scare people or hurt people's feelings. I'm sorry.
I won't be responding after this
Hello everyone, I was just wondering what is the best way around coding 4 raycasts pointing out from all 4 directions of a enemy. Similar to this:
would really appreciate some help, thank you.
is there a reason you prefer four separate raycasts only in the cardinal directions and not like an overlapbox or something instead?
whould an overlap box be better?
@chilly prawnDepends what you're doing
it depends on what you are doing which is why i asked
the map i am adding the enemy into is a very cramped location just like a maze
oh yeah ai movement
DIY pathfinding?
You need to look at navmesh
shooting raycast isn't the way to do it
I mean, you could
ok ill take a look thanks
Then if you want to detect if a player is infront of the enemy, and you want the enemy to "see" him, I think the best route would be to first use dot product, and then shoot a linecast
since you don't want your player getting detected behind the AI
@void basalt came across an issue. My project I am now trying to add ai pathfinding to is completely procedurally generated. Can navmesh be compatible with levels created at runtime or no?
You may have to apply it via code
but it should be
rust does pathfinding on their procedural terrain
Maybe #🤖┃ai-navigation is a good place to ask?
Is there a way to draw the Enable checkbox of a MB (like in Physics Body) from a custom inspector? (Basically I would like to make the Balancer Authoring script be disabled/enabled but without actually disabling the MonoBehaviour but writing the enabled state in another variable)
You need to add behaviour for when it's enabled/disabled, and it will show (such as adding the onEnabled/onDisabled scripts)
transform.x and transform.y properties tell you the directions
Yeah but if I disable the script I don't want it to actually be disabled (I want to save the enabled state in another variable as I said.. I need the script to always run but know if it's disabled/enabled)
they do not
transform.forward will tell you a direction
Then why do you want to disable it?
That's the whole point of that button
wdym, they literally do
Oh you edited the message
transform.x is not a direction
show me where the transform.x and transform.y properties are
Because I still need to run some things even though the script is disabled
transform.y is the downward vector
what is it then
You can add the methods but not add any content in them?
nope. The name is confusing.
oh wait nvm
youre right, i though this was godot discord
my bad, I keep messing them up
Or do you want to disable the script, but not have any drawbacks of disabling it (like update not running)?
bruh you guys are confusing me
Yeah this
Riiiight. I honestly don't know if you can add a checkbox there manually using custom scripts. You can add it as a boolean variable, though?
Probably better to ask in #↕️┃editor-extensions
disregard what I said before
there is no transform.left either, but -transform.right would accomplish the same thing as transform.left would if it existed
wait really? I was pretty sure there was
Yeah but I don't like the position it would be put in as a boolean variable (like I would prefer it to be drawn near the script's name)
alright then
then the directions would be
transform.up
transform.right
-transform.up
-transform.right
You can modify the position of it using custom editor scripts, hence #↕️┃editor-extensions , but IDK if you can overflow it outside the actual definition like that
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
So I have been using navmesh for my project including navmesh components and was able to create a navmesh at runtime for every new level created. But when I want to create a new level, I am not able to remove the previous navmesh created from the previous level:
@chilly prawnDunno man, I've never used Unity's navmesh before
oh my bad
thanks for the help anyways think i am getting somewhere
likely something like this
thank you
Hello. I need some help with TMP Regex. I need to validate code like "xxxx-xxxx" where can be set symbols count to 4 for left and right parts and validate that has an "-" between them. I tried to use something like this "^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$" but i doesn't work
So I have heard of Array.Max
But this is a little different. I have an Array of classes and each class has a value, lets call the value 'B'. I want to find the class that has the highest B value out of all other classes.
How can I do that? Its a lil confusing (Still googling but not finding anything)
Why does BoundInt size not extend from the centre?
And how would I fix it?
I set my my position to the origin and it's extending like it's at the bottom left
Im thinking separate all B values into a dif array and use Array.Max. Ill try that rn
Sounds like a common problem? 
Also, there are regex testers online. Not sure if there are any Regex guru's in here.
problem that its doesn't work in TMP can't write any symbol, but online tester works fine
I would like to ask how to achieve localization (multiple language) on some text that will change or not static (eg. a weapon description, item description). All tutorial I saw is some text that is unchanged (eg. starting button, setting button). Is there any tutorial about changing text?
Cant u just save the navmesh in a variable and clear or destroy it when u create a new navmesh?
Or overwrite
hey guys super quick question, i want my character with a circle collider and rigidbody2d to somewhat "fall" off the map, by making it's layer above everything else's. i've tried setting it's order in layer to 1 on the sprite renderer, but that's only its render and it's collider still stops it from falling. how do i make it's whole layer above everything else so it falls off the map, kinda like mario when he dies
you want it to collide with nothing? make the layer not collide with anything in the collision matrix Project Settings > Physics
how would i do this in c#?
you dont?
you go wo where i said Project Settings > Physics
nah i mean i need it to be in c# so on my death function the layer gets set to above everything else so it falls over everything off the screen
just make a new layer and set the player to that layer? when he dies
on death() layer = above all
ohhh i need to make a new layer ok
where do i make the new layer
in circle collider?
or project settings
sure
oh yeah i already have it's own layer
but its third out of 6 layers
so do i need to make it the 6th one?
you can probably actually set what this collides with right there
on "Exclude Layers", change that when you die maybe
ok
oh yeah
its doing something now
the character doesnt collide but instead goes behind
does that mean if i used the include layers instead then it will go over them?
that means you will collide with them probably
exclude, you wont collide with them
oh yeah
you can check the docs probably and see
i already collide with them anyway
ok
oh i did it
i did the thing with exclude layers, but then i just also made the character's sprite renderer in the top layer
and now it doesnt collide and also goes above them as it falls off the map
do you know how i'd activate the exclude layers in c#
so like in my death function i'll have spriteRenderer.sortingOrder = 1; aaand also change the exclude layers to the targeted layer in the collider component?
how'd i do that
look at the documentation, but you probably would just set have 2 LayerMask variables and set the Exclude Layers to those layermasks
Does BoundsInt size scale up from bottom left?
what's the simplest way to access the manual for a given package? google rarely gets me there and there doesn't seem to be a list/search function for all the packages
https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/ this manual for example
The Package Manager has a view documentation link for each package
ah, that'll work, a little annoying to have to open the editor and a project just to get a link to some docs but that helps if I'm already in editor
google -> unity <package name> package manaul
hey guys how'd i access and change the value of a circle collider's exclude layers section? i've tried this but it doesn't work. i want to change the exclude layer value to the pipe layer which has an index of 6 in the layers at the top of the inspector.
the .excludeLayers is the correct definition by the way
read what i said
i said use LayerMask
public LayerMask mask1; - nothing
public LayerMask mask2; - layers you want to collide with, so probably everything
set the excludeLayers to one of these variables
its like ExcludeLayesr in the inspector
same thing
ok
so a layermask is basically just a variable for a layer inside code
is how im thinking it
oh yeah its looking good so far
so i can basically set the .excludeLayers to the layer mask variable
alright this is good
yes
i think so at least
yeah
yesss dude it works
now when i die my character falls through the world aaaand it's sprite renders infront
(i just realised you could disable the collider) but we will ignore that
thanks so much i wouldnt have done it without you i coudlnt find anything online
yeah i dont wanna disable it
hey guys this is hard to explain to docs so im gonna ask here but how do you find the child of a GameObject without having to like make a public gameObject for the script and then drag the gameobject from the hierachy into it? so i've heard about a FindChild() or GetChild() how does that work
so for example in this prefab i have i want to be able to select the top pipe or bottom pipe and then setactive=0 it
GetChild(0); is Top Pipe
1 is Bottom Pipe
2 is Middle
wdym
like this?
yeah i know that
but i cant just go in update() and put GetChild(0) and then i will get the top pipe
why not
oh wait
when you type GetChild() in a script, will it get the child of the gameObject that the script is in?
yes
thats it?
yeah?
oh ok
so how would i get the child of a gameobject that doesnt have the script as it's component
the script is supposed to be on the parent
and it can get the children
so for example i have an empty gameobject which has the current script in it, and i am using this gameobject to spawn pipes that then lead to moving from the gameobject's position
but the pipes that start spawning from the empty gameobjects position are prefabs
so they arent in the game yet until start
so i have the parent of the prefab saved as a public gameobject in the script thats in the empty gameobject that then spawns the prefabs
and im trying to get the children of the prefab that gets spawned by the script in the empty game object
so how would i do that
i dont understand, just do GetChild(indexOfChild);
yes but im trying to get the child of another gameobject to the one the script is in
pretty sure you can do SomeGameObject.transform.GetChild();
what doesnt work, how does it not work
it says the transform doesnt have a definition for getchild
pretty sure because transform is just the info about the state of a gameobject
show code
ok get ready because it might be really confusing for you because you dont know what the code is intended to di
pipe is a public gameobject of the prefab i have
yeah Getchild() does indeed not exist
oh shit
i need capital C
oh now its saying it dont have def for setactive
its worked before tho
because thats not how you set the value of SetActive either
more because it doesnt have a value, its a method
because its not the same...
im so dumb
i forgot it takes a parameter
my bad
ive only been doing unity for a bit
also next time go to #💻┃code-beginner , that will be a better channel
i used to do it years ago and i was absolutely brilliant but then i stopped doing it and ive only been back on unity for like 3 days
im using a Game Makers Toolkit video on youtube to refresh my mind
its a 40 min tutorial on how to make flappy bird and i've finished it but now i'm adding my own stuff to the game for practice
alright thanks
oh yeah the reason i made it take the bool value instead of parameter is from when i made somethings component disabled by doing .enabled = false and i mixed it up with setactive because they are similar
Hii
hi
fine
just adding my own features to a flappy bird game i made off a yt tutorial
lol
@honest meteor !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
when I do Formatting.Indented with JsonConvert.SerializeObject, but then I later do string json = File.ReadAllText(files[randomIndex].FullName); this comes out empty var description = Serializer.DeserializeDict(json);
is there a way to make Formatting.Indented that I might not know of? I just like how it looks really, and I do want to make modding these easy
if I remove Formatting.Indented it works fine
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Your IDE should underline errors in red and give you proper autocomplete
How do I code PlayFab to save "public void AudioApply()"? because in the tutorial video it has "Data = new Dictionary<string, string>" and when I change the void to string in "public void AudioApply" I get errors, how do I make the PlayFab script save my public void AudioApply?
oh thats sick
how do i get it because i dont get red underlines at all in my code
and im on microsoft visual studio
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
this is giving an error
how transform doesnt have a definition for the setactive method
Configure Visual studio using the instructions I keep linking
how do i configure it though
So you can actually type code without guessing
Click the link associated with your IDE.
Follow the steps listed.
where is the link
in the bots reply <#archived-code-general message>
solved this with chatgpt.
if I did Formatting.Indented
I needed to add json = Regex.Replace(json, @"\s+", ""); (with using System.Text.RegularExpressions;)
after File.ReadAllText(files[randomIndex].FullName)
and before var description = Serializer.DeserializeDict(json);
hopefully will help someone in the future searching it
lmao how did chatgpt do that
I pretty much pasted the same thing I asked here
minus the part about modding
chatgpt is great if you know how/what to ask. it did take me telling it that I had already debugged and was sure it was blank, since the first thing it wanted me to do was confirm it
@quartz folio ive instally unity onto my visual studio now but it hasnt changed
it still looks the same in visual studio
Restart VS and click the Regenerate Project files button in Unity's preferences where you configured VS while it's closed
yeah ive done all this
i restarted everything
and just now ive clicked the regenerate button like you said and visual studio is closed
and now ive opened visual studio and nothing looks different
If it doesn't start working in a minute then you must have missed a step, it you installed VS manually then you mustn't have added the Unity module
then how will i switch between files
wait do i just need to use visual studio code instead of visual studio?
No, VS Code is much harder to configure
Can you screenshot the two steps you configured just to confirm they're done?
ok
i clicked modify
unity is installed
the correct visual studio is selectred
Is this 2022 VS? It looks old, but I'm not familiar with it
Try opening the script from inside Unity
oh yeah ok
looks old because thats just the light theme i guess
Also check that plugin in Package manager is updated
no change
and open Help>About and check the version
there is no plugin package
It's the last one, no?
About of the VS
You can open the package manager window to confirm, and update it if there is any updates
And package manager is here. Find VS plugin and update.
If it's still not working, comment out that line of code and once Unity complies again that may fix it?
and the only available update is for version control
The plugin is Visual Studio Editor iirc
ill checl
Did you confirm in VS About that it is the 2022?
i cant find the about section in vs
open Help>About and check the version
About Microsoft Visual Studio
oh crap my bad
why does Material.GetTexturePropertyNames() return names i dont have declared in my shader?
maybe because that method returns all names instead of just names youve specifically declared
idk
im not that good at unity
the documentation says "Names of all texture properties exposed on this material." and as far as i know only the ones i declare i the shader should be exposed
It's property names saved into the material asset iirc, which doesn't care about the current shader
so technically all materials will have those properties then?
No, materials accrue the properties of all previous shaders they have ever used with the inspector. They'll get stripped in the end so it's generally not a concern. I'd have to do some testing to confirm myself that that's what the method is returning, but I'm on my phone. You can see the data structure with debug mode in the inspector
hm ok ill have a look
i got this error and it wont let me do anything with it here
Close Unity and VS, reopen project and create a new script in the Assets folder inside Unity, then open it from there and see if it is properly in the project.
ok
i made a new script and opened it
but nothing changed
If there are other errors when you open a project it can't compile anything properly, so you have to fix it/comment it out
how do i decrease the timescale of only certain gameobjects
commenting out the lines got rid of errors about those lines
you seem to be right. all the previously exposed properties are still there even if the shader does not declare them. is there an easy way i can get around it and clear it somehow? or get only the shader properties?
but now ive still got this and only this which was never here before
Not that I know of
Multiply movement with deltaTime * multiplier(scale)
ok ty
but that will only slow down the movements though
It depends how you move, if it's not physics based you should be using deltaTime already and just add multiplier than
multiply it by something until it works fast enough
make a new multiplier
At this point I have no idea why it's bugged, but these things sadly happen in the world of development. You will have to close Unity, and delete the Library/ScriptAssemblies folder in your project and hope once it regenerates everything starts working. Because even if you get rid of the new error you can't go on without a functioning IDE!
ok ill try
maybe you know what c# reference file i can check out to find a workaround with reflection?
im basically trying to implement time deceleration, similar to superhot
@sullen loom Previous IDE might be conflicting with a new one, it could be cached by the project settings. You should remove it just to be save. If that fails reinstall cleanly both.
I believe that AssetDatabse.ForceReserializeAssets could strip the unused properties.
how do i remove
Uninstall
The VS 2019 remove it
ok
And if persists remove everything and reinstall
Have you tried https://docs.unity3d.com/ScriptReference/Shader.GetPropertyName.html or NameID (with https://docs.unity3d.com/ScriptReference/Shader.GetPropertyCount.html as the loop max)
https://docs.unity3d.com/ScriptReference/Shader.GetPropertyType.html to check whether it's a texture
just wondering is it also possible to use a coroutine to add a delay at the end of Update() to do this
its got rid of that big error message i had
Your normal (non physics) movement should look like float lengthToMovePerUpdate = speed * Time.deltaTime * desiredTimeScale;
alr
hey, i have a question...
how do i press a button from code?
i used "EventSystem.current.SetSelectedGameObject(buttonOpt);" to select it, can i click it in a similar way?
the button does have a onclick event, i just want to add controler support
There's an event you can send that presses a button, don't remember from the top of my head, research it.
this is part of that "research" here...
maybe just used the onclick event in code
well, its a gameobject, not a "button"
like maybe get the button gameobject and do button.OnClick()
and i get countless errors trying to convert it
public GameObject button
button.OnClick()
try that
and set the button to the gameobject
Type `UnityEngine.GameObject' does not contain a definition for `OnClick' and no extension method `OnClick' of type `UnityEngine.GameObject' could be found. Are you missing an assembly reference?
here you have that detailed answer
yeah idk just use that doc
is there a way to make certain colliders not interact with other certain colliders without using the layer system?
I have the same question
building on this, is there a way to make certain colliders not interact with certain ither colliders based on some variables
this is your other option https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Very good
Is there a way to make this an If statement
who knows how to fix it?
for Example if im holding something then my hands dont collide with it
Why would you need an if statement?
It's a regular statement to set colliders to ignore one another..
No i need it to collide only when i want to
not a constant not collide
Look at the code example from the docs for more information
is there a way to atop all ignore collisions from being ignored or would i have to do that manually
Third parameter + your manual state management.
Sorry im not following
Im very new to coding
Look at the docs and read it.
so i dont know what a Third Paramater is
Sure thing
Ah, that's a big problem..
Here's the docs on c# method parameters - good luck.
Good for you. !learn Unity and c# instead of constantly asking basic questions here
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Yes
manually probably if you aren’t using layers
Basically my first time using the new input system properly and was wondering why this isn't working?
Actually
I never tried doing &&
Nope still nothing
ok
Please verify none of those if-statements work by logging each step
Alr
Those if statements should be working fine though
If I remove the requirement for 0 or the alt key it works fine
Yeah
Alt if statement is triggered but not the digit0 if statement
Your code requires you to press both keys on the exact same frame.
Oh right. That's a bit irritating. How should I go around doing this? Some bool trickery?
Well, a messy solution, 1 sec
What is the method for when the key is pressed in general, not just the exact frame?
Assuming it's wasPressed, what you probably want is this:
var keyboard = Keyboard.current;
var pressed = (keyboard.altKey.wasPressedThisFrame && keyboard.digit0Key.wasPressed) ||
(keyboard.altKey.wasPressed && keyboard.digit0Key.wasPressedThisFrame);
if (pressed) {
...
}
The reason why it checks twice is because either one needs a check if it's pressed "this frame". If you don't add the second two for example, the code won't run if you press digit0 first, then alt.
I see. Thanks. I'll give it a shot now
Man you asked all this an hour ago just get some programming courses and dont start at the very highest level
I tried and no luck unfortunately
As in the if-statement is not entered?
Yeah it just doesn't happen
WAIT
I implemented it wrong sorry
It works fine now. Thank you!
Nice
Hello I am trying to upload my project to github using the unity desktop app, I do have a gitignore for unity, however, every time I open unity it says i have 800 changes that are made even if I never edited anything. Is this an error with the gitignore?
Is your current repo empty or already has everything in it
already has everything i think?
Then its likely gitignore
Just google the default one and download that, should be fine
Have u placed it in the right folder?
If you go to that directory and run git status are you seeing it saying things are mostly added? Or modified?
i think so
Bcs maybe u uploaded the full project without gitignore, and now that u have gitignore its removing the files? Idk
I think gitignore just ignores changes to already tracked files
Ok then my last message doesnt make sense
Maybe the files were moved? They'd show up as missing (I forget the label git uses) and there'd be a bunch of new, untracked files
this is what it says on most files
this
Oh hang on. Try git fetch --dry-run from that folder on your local machine
Maybe the gitignore is only containing the right stuff in the pushed repo
nothing happened
yes but i changed no code
Ah yeah, everything seems normal in the client.
Did you change anything in the editor?
probs an editor script or smth that ran
Even just clicking and dragging something?
nope
Asset rebuild can sometimes trigger a bunch of changes
The changed files are logs and the Library folder. You're not supposed to commit those anyway
So either your gitignore is wrong, or you already committed these before, meaning they're not ignored anymore
this is it
You're supposed to use this one: https://github.com/github/gitignore/blob/main/Unity.gitignore
Notice it ignores library and logs
I also see Library and Logs here
Manually delete and commit the delete changes
Then your gitignore should work, if you ignore them
Unity will regenerate the library folder for you
so delete "library" and "logs" folder?
Yes
alright
It is possible the changes are not tracked, because your gitignore is partially working
In that case remove the gitignore, make sure to only commit the right changes, and then make a new commit to readd it (preferably the one I linked)
ignore stops tracking from the moment that you added it
i used the github template gitignore
deleting logs and lib worked tysm
WAIT what about usersettings bc that is also being updated
i changed nothing in usersettings i dont think
Hey guys. Is it possible to support different Steering Wheels with the InputSystem? I'm finding it impossible to generalize wheels button like we do with gamepads 'Example: Button South'
@thin aurora
wait now its creating a usersettings change every time i close unity
If you look at the diff, what is it changing?
Isn't that part of a different folder?
Has someone tried Roslyn C# - Runtime C# compiler with dotnow intepreter? Do you know any more examples apart from the one in the dotnow interpreter github?
!cdisc -> #roslyn
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
This channel is for general coding questions regarding Unity. For basic questions like these: 
yes it is
It's supposed to
I'm not sure, but I think later versions don't change it when you close it (then again, I'm probably wrong)
what is your goal
this is part of the growing pains of learning how to use git
there are lots of ways to "redo everything"
without losing a single file
You are responding to a problem that was already fixed
okay
😄
Is it possible to in someway use a variable as a type? (specifically talking about casting) or is there an alternative solution to this?
I have a method that takes in a FieldInfo parameter and in the method I need to do GetValue. I know that I'm taking in an array (specifically int so therefore i could cast it as int[]) but I am unsure if I'll only use int arrays (maybe I'd use float arrays too? Basically, how do I dynamically cast a variable?
why are you using digit0 key? that's the numeric keypad zero i believe
trying to do that usually means you are doing something wrong
can you show the real snippet where this would be used?
Nah that's numpad0key
altKey is also a combination of left alt and right alt
it depends on your platform
var.GetType()?
you might have to check them separately
are you trying to express, "alt+0"?
@languid hound so my suggestion is to explicitly check left and right alt
your keyboard might also not have "alt". it could be "meta". depends on the platform
you should use an input action for this
then you can press the keys on your keyboard and find out what they are
using the input map window in editor
Oh this was just like a quick 5 minute thing to test AssetBundles not a fully blown thing lol
I appreciate you putting so much thought into your response though it'd be super helpful
@stuck forum before you say anything more
can you show the real snippet where this would be used?
thats what i am trying to explain
because you're going to write something so ambiguous
wait a sec
focus on the snippet
private void SetupUI()
{
FieldInfo[] fields = _gameMode.GetType().GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeof(bool))
CreateConfigFieldBool(field, "Enabled", "Disabled");
else if (field.FieldType.IsArray || field.FieldType.IsEnum)
CreateConfigFieldMultipleSelection(field);
else
Debug.LogWarning("Invalid type has been used for game stats. It has to be either of type bool, array or enum");
}
}
thats literally all atm
okay
and in the function in the ElseIf statement im trying to do the casting thing
is this a UI at runtime?
yes but it will only be called once
is _gameMode the only object you will want to "inspect" at runtime?
yes
how about in the future?
hmm got no plans for changing anything
okay can i make a recommendation?
not use reflection?
that's correct it's unnecessary
when tf does one use reflection then xD
when you don't know the types ahead of time
but in my case, i used this to that if i were to change something in the class, i wouldn't have to change the UI separately, i'd let the code do it for me
since you control your own code and see all the source, you know all the types ahead of time
you are actually not using reflection, you are trying to write a macro, which is just as brittle
you think you are using reflection
you are calling .GetType() and touching things in the Reflection namespace
but actually, you know the types ahead of time, so you are not using reflection
you are using something, to write a macro
it's not worth it
welp...
in my opinion this is a very challenging thing to wrap your mind around because the namespace literally says Reflection in it
99% of the effort will be in creating the different UI widgets. it will take you 5s to add or remove fields that you want to visaulize
For usages on reflection: you could find implementations of an interface at runtime, and then do something with that. I personally use to build a dictionary which maps enums to specific implementations, to minimize the number of places I have to change stuff when I add something
don't do that stuff either
if you know the types ahead of time, you are not actually doing reflection
you might be using Reflection namespace and such
but it's not reflection
it's just macros
could you name one good situation where reflection is actually useable?
yes, for serialization for example
if you are writing a serialization library
you do not know the types it will be used on ahead of time
however, many modern serialization approaches, for example Unity's JsonUtility and protobufs, do try to find out the types ahead of time
so that they do not have to use reflection
a common pattern for typed ui inspection is something like
GameMode gameMode = ...
CreateCheckbox("X", getter: (GameMode edited) => edited.x, setter: (GameMode edited, bool newValue) => edited.x = newValue);
of course all of this would be a lot more abbreviated
i am showing you the labels and type names so that you can nunderstand
in your code it would look like
CreateCheckbox(nameof(GameMode.x), edited => edited.x, (edited, newValue) => edited.x = newValue);
@stuck forum does that make sense?
UIToolkit already has this
hmm im trying to understand this
the signature of createcheckbox is
so it does what i want it to do, but just more... better?
GameObject CreateCheckbox<T>(string label, Func<T, bool> getter, Action<T, bool> setter) { ... }
i am showing you that c# has a limited form of macros, they're called generics, which is part of a category of language features called templates
I am so confused... I'm struggling to understand what exactly your snippet is doing
sorry
okay
well i think you do things the way you need to do them
your game mode object has what, like 10 fields
i think create the checkbox
it's too much new syntax for you
actually some will be checkboxes, but some will be multiple selections
sure
something like this
@tropic relic just post in here instead of sendin me a DM request
Hey people, how are you doing? Let me ask you this, i'm trying to create an inventory system for my survival game, i'm trying to create with Scriptable Objects, the problem is, i'll also have a party of npcs that will have an inventory too...if i use scriptable objects i will have to create an scriptable object file for each npc, and if i want an enemy to have it too, i will have to create for each enemy, the solution that i found was to create a deep copy of a single scriptable object file into the Monobehavior property Ex: SOInventory inventory = DeepCopy(inventoryScriptableObject), but deep copy doesn't seem a good efficient solution, can someone give me a btter way to create an inventory system?
So, I want to make a way for my player to be able to have a "lock on" feature as part of my combat system. Something similar Bully or Assassin's Creed where you lock on by holding the left shoulder. I'm not sure what the best approach to something like that would be. I initially was going to try and use sphere collider that, whenever an NPC enters, that NPC would be "targetable and when the player presses the left shoulder, it would lock on to the nearest valid target. But then I read something about using raycasts instead.
So I guess I'm asking, are either of the solutions better than the other, or is there another solution that is better overall?
i was working on something similar about a week ago, but have shelved it to work on other parts of my game, but the solution I came up with was to give each item that can be part of an inventory a few key values like its name, its stack count, and other things like that. Then I gave each NPC in my game an associated inventory ID, not sure if this is the best way to do it, but its what I did
Its a bit more complex than that but I don't wanna bore you with the details lol
Got it Mayo, thanks 🙂
the object don't teleport
do you have a CharacterController?
no you need to disable the CC before teleporting
There is also method you can call that updates the CC
Is this not how you do this?
PromoteUnityTo returns void
If you're trying to pass it as a delegate you should not be providing a parameter list
It should just be ButtonBind(PromotUnitTo);
When you provide the () with parameters you're invoking the function
So what's the syntax for passing the parameters?
Call Physics.SyncTransforms after moving your Character Controller and it will work. No need to disable it
Does OnTriggerEnter() work with a character controller as a colider? Cause I don't have another collider on my object and its executing anyway? If it DOES work with a character controller, how can I make it not do that, and make it so I can just have it work with a sphere controller?
Or do I just do that with the passed argument?
I thin OnCollisionEnter works
if it's calling the function then it is working lol
this doesn't work
is Debug.Log printing
yep
Hod do I get it to NOT work? lol, its supposed to only fire when the sphereCollider that is attached to my game object hits something not my character controller
I guess this is how you have to do this?
does anyone have any good resources on learning about cancellation tokens?
put a filtering by component / tag
a filter?
mhm
show the current code you said is being called.
public void OnTriggerEnter(UnityEngine.Collider other)
{
Debug.Log("Hit: " + other.name);
validTargets.Add(other.gameObject);
}
you want to execute this Only when
don't want to disturb but do u know fix for mine?
Only if the collider calling it is a sphere collider attached to the gameObject the monobehavior the OnTriggerEnter is running from
attached to what?
So I have a characterController, sphereCollider, and my script on the same object. I need the OnTriggerEnter to only work if the collider is the sphereCollider and not the characterController
wait a second, is the code snippit you posted used for this?
if so, i still do UI's the old school way
put a tag or component you look for that ONLY sphere collider has
idk what am i doing wrong but it's just doesn't work
then use that filter it out in OnTriggerEnter
what do you mean "doesn't work"
did you try the first option?
won't teleport
right, but how to I even get the information to filter? Like how do I get reference to it?
i mean i try yours and also that Physics.sync...
let me see what you tried
through the other parameter in the TriggerEnter
eg if(other.TryGetComponent(out MyScriptOnThisSphereCol _)) // do stuff
now i have this, i tried playerBody.transform.position = spawnPosition;, transform.position = spawnPosition;, i also tried to duplicate the vector
is this block of code running ?
since it always printed position to the console i guess yes
maybe it's hitting an error
is controller assigned ? check console for any errors
Debug.Log(spawnPosition) Debug.Log(control.transform.position)
before doing move and after move
nope, any errors
hey guys i know this is probably super easy to ressolve, but how would i set a bool in one script to whatever the bool is in the other script? cuz i want to detect whenever it's gameover, which does all of that work in my playerscript but i want that same bool to be updated in my logic script so i can detect if whenever i try to pause the game it will let me or not depending on if its game over or not, and all of that pause stuff is in my logic script which is a different script to where the bool gameover is being done
okay i think the object is moved but the game sees it as it was
Can I make an Update loop like this that I start whenever I need it?
public IEnumerator SelectiveUpdate()
{
while (true)
{
// This is a normal Update() loop until we use return;
yield return new WaitForEndOfFrame();
}
}```
since debug after move printed the location that i specified as a target location
Turns my problem was that I just shouldn't have had my script attached to the same gameobject the characterController was on and just create an empty with the script and the sphere collider by themselves.
No extra code needed 💪
sure
thats good
you mean the position of player or the target location
i was so confused lol. Thank you for your help tho
Thank you :D
what's confusing ? also your question belong in #💻┃code-beginner
the last debug threw the spawnPosition
I was confused as to why it was so complicated to get the data that I needed. And I figured this channel was more appropriate cause I was asking for help regarding a concept and not my code specifically.
well filtering out or looking by script should've been also a nobrainer so yeah def #💻┃code-beginner
so it did move it
Right, but that wasn't even what I was initially asking about but I'll keep that in mind
How do i make my projectiles have no collision with eachother? Like how do i stop them from bumping each other away lmao
Layers would be my solution
Also, nice bio
prob yes but i stay on same position as before teleport
🤷♂️ check you're moving the correct object
what is the point of UnityEvents? They just seem like regular delegates
They are but they are serliazed in the inspector making for easy drag&drops
Guys I'm going nuts 🥜
I'm trying to do something so simple. I'm trying to have a "frosted background" look for behind my popups.
My setup is as followed right now:
I have a camera that renders all my UI (excluding my popup)
I have a copy of my main camera only this time it renders to a texture instead
I have a canvas set to screenspace camera (with my main UI camera linked)
I have a "blur popup" canvas with screenspace camera (with my frosted camera linked). In side this canvas is the popup and a rawimage with my RT in the backgound
With this setup the result is I simply don't see the frosted canvas at all and the RT displays the content of my frosted canvas instead of the main UI
But this isn't working at all for some reason and I've tried every combination of depth, sorting layer and settings I can think of 😢
Hey everyone! So I'm working on a game jam, and i've ran into a weird issue--Everything about my code is working pretty well for this implementation of sound from FMOD. I am getting the Debug.Log of the "Moving" and "Not Moving"
And! I am getting the debug.log for the start of the InvokeRepeating function.
The only thing is that the InvokeRepeating function isn't calling my CallFootsteps, as im not getting any ping from the debug.log to "PlayFootsteps"
Does anyone have any ideas as to why that might be?
Are you sure "playerismoving" is true there?
I mean, it should be, when debug.log is spitting out "MOVING" the value should be true. Right?
(also use nameof(CallFoosteps) instead of the string directly, you'll avoid hard to find typos that would lead to no errors like this)
not if it's set back to false straight away
try a breakpoint at the if there and check if it ever reaches this if
Okay! thank you for the help!!
from what I can see, it can only be playerismoving is reset to false imiedtly after set to true, or walkingspeed is more than the default 5 you have there (check the inspector is also saying 5)
invoke repeating is in seconds by the way, a foot step every 5 second is normal? your boy must big a really big boy haha 🙂
Hahahahah
Okay good to know haha
I didn't realize invokerepeating was in seconds XD
so you dont have to make custom delagate, nothing more nothing less
also UnityEvents can be serialized, which means that they can be exposed in the Unity editor.
Any clues? 🙂
Ahh, unfortunately I don’t know much about working with the unity UI stuff 😅 I wish I could help!
Are there any downsides to making my classes sealed in unity ? Or making most of my fields static if i know im not turning them into objects.
I just dont see this alot and im wondering if there are any downsides to this approach
I make all of my classes sealed by default, as I despise class inheritance. If I end up needing it, I can remove it. I do this for myself so that I don't somehow end up creating a chain of 8 inherited things when it only needs to be none or 1 + an interface.
Ok so im not crazy
I just dont see it anywhere else and it feels like im doing something wrong
Hey guys. Im working on designing a system to handle enemy spawn in my 2D game.
Im going to have a lot of enemies, so i'll be object pooling. I only want objects to appear at the edge of a collider I have on my character. But I also need to update the position of my enemies through the map. Any ideas on how i should approach it?
Right now I have a grid system that gets Points of interest and then activates the enemies on all the adjacent cells of said Points of interest
Problem is, that is highly inneficient :/
I didnt read ur whole post sorry
Common use-cases tend to be the easiest and most viewed. So take that for what you will 😄 I very much like composition and explicit data-flow, so I make the most that I can without inheritance wherever possible. And that explicitness turns into making sure there is no guesswork in the types or the data. sealed on nearly everything, no virtual, prioritize interfaces without properties or local state changes, etc. There are some exceptions, like needing to inherit for various GraphView things, or other specific APIs ofc but for the most part that's what I do.
thank u nomnom
Just needed reassurance
I am also i very big of being explicit and trying to avoid inheritance hence why i try and make everything static as much as possible. No Idea why sealed isnt the default state of all classes. Besides just the small performance boost. Interfaces are a fucking amazing tool as u mentioned. But seeing as how DOTS is becoming the standard unity is looking forward to pushing. Im thinking about dabbling with the ECS
So you're right, something about how the code is working right now it's not actually updating the bool at all.
So i think it's starting false then its not being updated too true when I move the player.
If i comment out the entire Update section then set the bool too true it does work - it just plays the audio file at the start.
I guess I'm just unsure how to make sure that the bool value is being updated when I do move.
Looks like aspect ratio issues where some pixels aren't drawn due to floating point imprecision or simply not able to draw said pixels scrunched up.
This is the coding channel, perhaps you should be asking this in #💻┃unity-talk
You'll need to provide more specific details with what you're doing or have done. Ask the folks in #💻┃unity-talk (they'll figure it out for you)
When I use MovePosition on a dynamic rigidbody every frame, velocity is ignored. Is this intended?
Move position was meant for kinematic rigid bodies
ah
Is there an alternative? I have top down movement but want to use velocity for things like knockback as well
To Rigidbody physics or not to Rigidbody physics
(Want some "physics" functionality but overbearingly difficult to undo)
So you're saying I should code it myself?
Kinematic or Character Controller with your own implementation of non real physics is the normal approach.
why dont you move with .velocity for regular movement and use AddForce for like knockback ?
If I set the velocity every frame won't the knockback be overriden?
It would. You'd have to work around it with edge cases, constraints and whatnot.
Yeah, but then you lose control completely while knocked back
you have to work around that like Dalphat said
Wouldn't be surprised if there are half-baked non-realistic but semi-realistic physics assets on the asset store. This is a pretty common issue 
You dont need to. Kinematic character controller is free on the asset store. There isnt a better one
I have two scripts: PlayerCharacter, and EnemyCharacter. They both derive from UniversalCharacter. I get the component using GetComponent<UniversalCharacter>(). This is then stored in a variable characterComponent. How do I check if my characterComponent is a PlayerCharacter or an EnemyCharacter?
if (universalCharacter is PlayerCharacter player) {
// use "player" to access the player
} else if (universalCharacter is EnemyCharacter enemy) {
// use "enemy" to access the enemy
}
you can use the is keyword
if(characterComponent is PlayerCharacter) // do stuff
But you shouldn't
The whole point of having a base class is to not know the "real" type behind it
You should be able to call a method or get/set a property, and C# handles the action of selecting the right method/property on the "real" type
How do I make a method in UniversalCharacter that can be overridden in PlayerCharacter and EnemyCharacter?
Can UniversalCharacter be used on its own?
No
It just has basic unity events
So make that class abstract, and declare an abstract method in it. It'll force the deriving classes to override that method
Thank you
Exactly what I needed
public class AStarAlgorithm
{
public class PathFindResult
{
/// <summary>
/// Whether or not the algorithm found a path.
/// </summary>
public bool foundPath;
/// <summary>
/// The optimal path found by the algorithm (Is empty if foundPath is false).
/// </summary>
public List<Vector2Int> pathFound;
}```
This is inside a namespace. I use `using MyNamespace.Pathfinding`, but how can I access `PathfindResult` without having to write `AStarAlgorithm.PathfindResult`? Like I can access `RigidBody` from the `UnityEngine` namespace
I don't know if I explained it well
Wait is it because it's a class within a class?
Take the PathFindResult out of the enclosing class
Alright
Thanks
What about public PathfindResult FindPath(Vector2Int[,] _map, Vector2Int _startPos, Vector2Int _target) This has to be inside a class right?
Yes, as that's a method
Okay. Thank you
int temp = GetOtherValue();
if (temp < currentLowestValue) currentLowesValue = temp```
Is there a short version for this? It feels like there would be. Overwrite value if its smaller, otherwise keep current value?
currentLowestValue = Mathf.Min(currentLowestValue, temp);
perfect, thanks!
I assure its advanced
ah
Is it good architecture practice in Unity to keep the Assembly-CSharp project just for thin wrappers around functionality implemented in a main class library project?
or is it more typical to basically write all the code for the game in Assembly-CSharp project?
Hello! Is there a way to make 3 random bools turn true in an array?
hi everyone. Does overlapcircle2d works with triggers?
should work with any colliders
you generate a random index and use that to do whatever you want to a random element
can i make it work only with specific colliders?
then repeat X amount of times - in your case, 3
sure
specific as in trigger / nontrigger or you mean filter it by specific objects?
use layermasks
I have a text box that I am going to use to display health as a number, but when i define it as a public GameObject, it doesn't let me use getcomponent to define it as text, and when i use public text, it has an error saying cannot convert float to string. im pretty new so this is probably an easy fix. i also tried a health.ToString() method but it won't let me drag my text into the script.
im a bit lost rn ngl
you'll have to post code - this is vague enough that i'm not 100% sure what you're doing
!code
alr one sec
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i mean something like make it work only with colliders of Gameobjects with specific tags
sure check tag on collider, or filter directly through the physics function with layermask
this is just what i have atm
but this code doesn't let me drag my text object into the script
ok thanks
typically, you would have a class variable that is the actual text component of the thing you want to update, rather than a GameObject
public TextMeshProUGUI textBox
(this might not be TextMeshProUGUI depending on the type of text you're using)
then you would just textBox.text to change the text
this looks fine, so what's the error?
ah i see
it's not a Text box. show your inspector for the GO you're trying to assign
wait i just changed it to textmeshprougui
it let me drag it on
let me see if it works
ok yeah it works
public bool[] boolArray = new bool[10];
private void Start()
{
int count = 0;
while (count < 3)
{
int randomIndex = Random.Range(0, boolArray.Length);
if (!boolArray[randomIndex])
{
boolArray[randomIndex] = true;
count++;
}
}
}```
so what is textmeshprougui
is that like some sort of command for text boxes?
anyways thanks!
AFAIR, its the component for UI text (text on Canvas) using TMPro
oh!
that is why i have a canvas linked to all my ui
i just assumed it was a "folder"
when i made my ui
nope - a canvas is required as a root game object for any UI elements. go through this, it will help
https://learn.unity.com/tutorial/working-with-ui-in-unity
How do I send strings through network variables?
are you talking about ngo ?
yes
pretty sure you can also add extension methods for the FastBufferReader/FastBufferWriter ReadValueSafe and WriteValueSafe methods to implement your own serialization for strings (or any custom type for that matter) for RPCs
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/custom-serialization
Hey all i got a quick question i have this line :
{
public AudioSource CreakSound;```
But in the inspector i cannot put my .mp3 file in it ?
What am i doing wrong here?
i can see it in the inspector
an mp3 file is not an AudioSource, at best its an AudioClip
AudioSource is a component that plays an AudioClip
so you say i can better make my sound effect a .wav ?
change type to AudioClip
no, i'm saying you are using the wrong variable type
ok Ty!]
Maybe i stupid question but CreakSound.Play(); does not work with a Audioclip, So how do i play the Audioclip ?
assign the audioclip to the AudioSource's clip property