#💻┃code-beginner
1 messages · Page 345 of 1
i don't get anything in the console
Hi, I think I messed up a bit, was attemtping to make my character unavaiable to jump while mid air but it keeps doing so :( ,
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
well the first check in the if statement on line 31 should error
you didnt add the layermask into your Physics2D check
anyone knows how unity detects key press?
you want to know how you can write the code for that? or how unity actually does it internally
so what should i do ???
debug everything, find out what runs and what doesnt and then try looking why they dont run
how unity does it
i was working on a double jump and I am using a float for that like a jump counter: on ground - 0, first jump - 1, second jump - 2
you can only double jump if jump counter is < 2
it was working perfectly
however, if I hold the key, apparently the code runs twice, because I cant double jump
Why not int
can you tell me what should i write so that when i click the button the activeBuildingType change to the BuildingType that as been clicked (sorry if its not clear)
Where does that class come from?
this is irrelevant
this is for saving changes after you modify serialized data (which is an editor-only thing)
Make sure that the Awake code is actually running -- maybe log something before you add the listener to onClick
I'd also log the Button you're accessing
so store the Button in a variable and then log that
Although, given that the buttons are appearing and have the right sprites, that code is probably running (:
Oh true
Actually, it's possible that you just have a messed up UI
If you don't have an EventSystem, you will not be able to interact with the UI
So reflection is the way to go
what
yeah maybe
heyho guys, I wanna ask is it possible to add ui components for each element on a json array?
this is my array
[
{
"question": "What is .....",
"type": "multiple_choice",
"options": ["answer1", "answer2", "answer3", "answer4"],
"answer": "answer1"
},
{
"question": "tell me who is ....",
"type": "essay"
}
]
there's nothing when i type t:eventsystem in the hierarchy
okay, you need to add one
go to GameObject > UI > EventSystem in the top menu bar
that'll create a new object with an EventSystem component on it
this is responsible for things like clicks
You can use JsonUtility for this
Although, because you have multiple question types, it could be a bit difficult..
I mean is there any way to add the UI components?
but Im planning to not use the essay type though
well, sure, once you have a list of objects, you just instantiate a prefab for each object
only the multiple_choice
parsing the json is the interesting part
For a single question type, it's simple: you'll create a class like this:
[System.Serializable]
public class Question
{
public string question;
public List<string> options;
public string answer;
}
well isn't it like golang,
use a struct and then marshal it into the struct, right?
But im planning to have more than 1 question
Alr thanks!
right, and so you'll deserialize a List<Question>
A very popular alternative is Json.NET
It handles many more kinds of data -- like Dictionary<K,V>
JsonUtility can handle anything you can serialize in the inspector, basically
It also lets you do stuff like write custom converters.
@swift crag yessss i added one and now i get the debug.log that something got clicked
you'll want to install this through the package manager
...er, this page doesn't tell you how to do that lol
The name is com.unity.nuget.newtonsoft-json
I just started learning unity and am trying to make something that when 5 copied prefabs collide with a cube they add 1 to the score does anyone know what I'm doing wrong?
For documentation, look at https://www.newtonsoft.com/json/help/html/Introduction.htm
what is the problem?
I have one that takes a GUID and looks it up in a dictionary, then returns the corresponding value
my settings file looks like this 😁
when they collide it doesnt add anything to the animalsDeleted
have a look at this page
it'll walk you through the possible problems
thanks the problem was i didnt have a rigidbody
i used to have a ton of trouble making physics messages work right
that isnt the point-
It may be part of the issue since you are doing float comparisons.
Impossible to say without seeing code. Not sure if I missed where you shared it
alright
i didnt
mb
nvm
fixed it
it had nothing to do with key detection
but instead with me checking the y value for some reason
im gonna bump this since i havent received a reply yet
@swift crag can I ask?,
is there any tutorial on how to clone prefab and add it into a list
so every prefab has a property of which is the selected option
and is it possible to make it scrollable?
Instantiate the prefab and put the new instance in a list, that’s it!
hmm Intersting,
do you know any tutorial tho? so I could prob learn it before asking any furthur
This is a #📲┃ui-ux thing—I’m going to bed and can’t explain it right now, but you can look at the pinned messages in there for some Unity UI tutorials
👍 sorry for disturbing ur sleep schedule
Were you checking if the y value was EQUAL to something?
it was > 0
thats why it didnt work when falling
https://hastebin.com/share/coquqozoxa.csharp
so uh, I was trying to make a dash from memory and ran into two problems
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the main one is the most obvious one, Im using transform.position, so its gonna behave more like a teleport than a dash
so I wanted a tip for something to replace it with
and the second problem is that if I press right and left continuously, there is no distinction, so if I press a and soon after d ill dash to the right, even though the initial input was to the left
the most common suggestion for a dash would be to use a rigidbody and just assign the velocity. of course you'll also likely want to prevent other input from overriding that velocity for the duration of the dash, but that is fairly easy
so I guess that instead of input("Horizontal") ill have to split it into input.keygetdown("a") and ("d")?
or is that just elongating it unnecessarily?
rb.velocity = new Vector2(dashPower, rb.velocity.y);
like this?
nothing came out of it tho
huh
either you are overwriting your velocity somewhere, something is blocking it from moving, or there is some other issue with your setup. without having any other context it is impossible to know 🤷♂️
Good morning 🍎
Should I be using textmeshpro or legacy text?
TMP
text mesh pro . . .
Thanks :)
gm
https://hastebin.com/share/ifatudapop.csharp
These are all instances of velocity being mentioned
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you overwrite the X velocity in FixedUpdate. remember how i told you that you'd want to prevent input from doing that for the duration of the dash?
how do i shut off an update tho?
isnt the whole concept of update being called every frame?
you don't "shut it off" you can use logic, like an if statement, to prevent it from doing certain things
I create a bool like isDashing, make it true when pressing dash, and I make an if outside the FixedUpdate that says it only works when isDashing == false?
yeah, that's one way to do it
https://hastebin.com/share/ecamurapey.csharp
like this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.

i did
and the result did not change
;-;
okay now take a look at your logic again and remember that there are no delays in your code at all
you set isDashing to true on one line, then within the same method, with no delay whatsoever other than the two lines in between which also run immediately you then set it to false
IEnumerator it is then
you don't necessarily need a coroutine, if you just track when you start the dash and ensure you don't allow input when the current time is less than dash start time plus dash duration
ill check it tomorrow and ill give ya an update
This is the beginner coding channel. You should move (delete here and post at the correct location) your message to the appropriate channel.
okay sorry
first of all, #archived-networking
second, you absolutely need to understand the basics before attempting multiplayer
third, you haven't done any networking of your object there
no
Well why do you think your bullets are only client side ?
Good guess. Your script is not telling anyone it is firing bullets
What behaviour are you looking for here? The server fires all bullets and syncs to all clients or something else?
Me personally I would not let the client fire bullets
Why do you need the server to see it ?
In that case?
Hello,I have a question, I am going to start making 2d pixel game in Unity, but I wonder what is the best Unity version for 2D ?
there is no "best" version. also this is a code channel
okay sorry
although i will say that 2022 introduced several QoL changes to the 2d physics api so go with that version or newer
The server seeing the bullet will not magically sync it to other clients. Multiplayer is a bit more complicated than you think. I suggest you start reading the docs for the MP framework you are using. Try to spawn a cube server side and have it synced to 2 clients first. Then move on to bullets
oh shit, actually it was the 2023 beta that did it. so unity 6 would probably be the "best" for 2d if there were one
guys any idea why this is happening
don't expect this person to really put any thought into learning how multiplayer frameworks work, just 25 hours ago they refused to bother learning the basics because they already know syntax "basic shit like parenthesis" (exact quote from them)
dang where did everyone go
well this is a code channel so it isn't really the right place for that question. but is your camera perhaps a perspective camera rather than an orthographic one?
hint: it is. so you also see depth
oh mb
im quite new here
Oh well if he knows parenthesis n shit he is pretty much good to go the
You lack all the fundamentals to do what you want. Start simpler like I suggested.
yea thats exactly why you should try building the next valorant. Have you finished your kernel level anticheat yet?
Dont waste your time, start simpler.
does it matter? if you dont understand the basics then ANYTHING multiplayer is going to be too complex. Even if its pong
and if you truly want to do networking, then #archived-networking as suggested
you dont need to convince me, or anyone else that was advising you. Its not our project.
you also CLEARLY lack the fundamentals for unity give this is in your code
new Quaternion(0,0,0,0))
hi guys im doing my 2d game but my enemy don't trigger animation event
it just disappear after die
show relevant code since this is a code channel
Have fun stumbling in the dark then
the layer variables are just LayerMask type. then you can either create a struct with the data you want to fold out like that, a custom editor that has a foldout, or a third party asset like NaughtyAttributes which has a Foldout attribute
thanks man
image or text?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi guys, i have an trouble with an animation. i used a blend tree and input system. does anyone know the problem?
Here is my script : https://paste.myst.rs/jfg5ici3
a powerful website for storing and sharing text and code snippets. completely free and open source.
ty
care to elaborate on what you are expecting to happen? it's not clear from the video what exactly your issue is
My animation is completely non-existent, like a glitch
oh of course, how could i not have known that since i definitely have intimate knowledge of your project!
anyway, what debugging have you actually done?
need help, i cant organise my scripts
i made so many code about everything but some code need other gameobject's code to work
any tutorial to lern how to manage all the classes and how to use classes for other class?
there isn't really an "organize my project" tutorial. how to organize everything really just comes from experience. don't be afraid to refactor things either, especially when things get messy, that's how you get the experience
i dont know for sure. I use a coroutine in my script and it just happened
have you checked the console for errors? i saw at least one at the beginning of the video, not sure how relevant that one is. have you ensured that the variables you are using are the what you expect them to be?
o yeah its just an object and has nothing to do with animation
okay that doesn't really answer much of what i asked
thanks for the info, do you (or anyone who has experience in this) have a recommendation transferring the values of the item script to one another instead of just moving the array? 

Hello, I have a problem with my code. For a level y have to count the amount of steps of my player, because he dies when it reach a limit. but now, depending the size of the screen (if I play focused or maximized) for the same game distance it counts differents steps. This is my code:
The LvlManager that receive the steps:
private int stepCount = 0;
private void OnEnable()
{
MovimientoTopDown.OnPlayerMove += IncrementStepCount;
}
private void OnDisable()
{
MovimientoTopDown.OnPlayerMove -= IncrementStepCount;
}
private void IncrementStepCount()
{
stepCount++;
Debug.Log(stepCount);
if (stepCount <= timeSlider.maxValue)
{
timeSlider.value = stepCount;
// Actualiza el alfa de la imagen del panel
darkPanelColor.a = timeSlider.value * fadeRate;
fadeDarkPanel.color = darkPanelColor;
}
else
{
StartCoroutine(ShowFailSequence());
}
}
And this the PlayerMovement script that activates the event:
private Vector2 lastPosition;
private float movementThreshold = 1.0f; // Umbral de movimiento para disparar el evento
private void Start()
{
keepMoving = true;
animator = GetComponent<Animator>();
rb2D = GetComponent<Rigidbody2D>();
lastPosition = rb2D.position;
}
private void FixedUpdate()
{
if (GameController.GetInstance().isGameStarted && keepMoving)
{
direccion = new Vector2(movX, movY).normalized;
rb2D.MovePosition(rb2D.position + direccion * velocidadMovimiento * Time.fixedDeltaTime);
if ((rb2D.position - lastPosition).magnitude > movementThreshold)
{
lastPosition = rb2D.position;
OnPlayerMove?.Invoke();
}
}
}
the same game distance
it doesn't actually sound like it is the same game distance. how are you measuring this distance
because it sounds like you may be using some UI elements and your player is moving in world space between those UI elements that are in screen space. and when your resolution changes, that affects how much the camera can see in world space due to the orthographic size
The movX and movY values are obtain this way on Update()
movX = Input.GetAxisRaw("Horizontal");
movY = Input.GetAxisRaw("Vertical");
that's not relevant to what i asked
On my game the player moves on a tileMap that is inside a Grid. And then I just send this to the canvas using a renderTexture(). So I think it's not measuring anything with the canvas
can you provide some actual details related to the question i asked
I use two Cameras, one for the UI and one that follows the player with perspective Ortographic with a Size set, so this way on the UI will always show the same amount of map
did you not even read what i had initially asked you? or do you just not want to actually answer that?
how are you measuring the distance travelled and how have you confirmed that it is actually moving a lower distance on higher resolutions
how do i hit a backface of an convex mesh?
Sorry, I don't understand your question. The distance is measured using the rigidBody2D position, is this what you refer?
you said "depending the size of the screen (if I play focused or maximized) for the same game distance it counts differents steps"
how have you measured any of this to confirm that
Because I have a slider with a maxStep as slider.maxValue set, and in maximized it advance slower than focused. In focused it advance so fast as I move
so you are making assumptions without actually confirming anything. in that case, show a video of what is happening so i can actually get some relevant details
use mp4 to embed in discord or upload to some remote host
Upload it to https://streamable.com/
if u cant open this website u can also use vpn
if you used obs with default settings to record it then just change the extension to mp4, it should be in a codec that is easily supported by both
You can see here that in focused the slider is like 25% and in maximized it goes like to 50% of the slider
thank you, I will consider it for the future
i also print the rigidbody position on the same wall so you can see is the same on focused and in maximized. This is why I dont understand how it gives diferrent steps
the X position is different there where it should be the same. so you are resizing something, there is a difference of 0.08 units, which isn't a lot but depending on the values you are using to determine a step it could be significant
The difference is just a FixedUpdate error because if I play again on focused it can go up to x=11.64
FixedUpdate runs at a fixed rate. if it is printing a different position when you are in the same position at different resolutions then you are resizing the game world based on the resolution rather than the camera's orthographic size
I found something interesting. My problem is not about how is resizing the game world. Because now I have count the steps on the player movement and it gives the same result if I go to the signal in both resolutions (32). So my real problem I've discover is how the lvlManager is receiving the event, but is supose to be the same, but I can't understand if this FixedUpdate updates the steps slowly, the levelManager that is suscribed to that event gives high values (1000 and thing like that for the same distance) since the OnPlayerMove is only Invoke when a step is incremented```cs
private void FixedUpdate()
{
if (GameController.GetInstance().isGameStarted && keepMoving)
{
direccion = new Vector2(movX, movY).normalized;
rb2D.MovePosition(rb2D.position + direccion * velocidadMovimiento * Time.fixedDeltaTime);
//Debug.Log(lastPosition);
if ((rb2D.position - lastPosition).magnitude > movementThreshold)
{
totalSteps+=1;
Debug.Log("Steps: "+ totalSteps);
lastPosition = rb2D.position;
OnPlayerMove?.Invoke();
}
}
}
show the full code for both classes
Here are both in the same file: https://hatebin.com/cisdzlznqo
show the LevelManagerBase as well. and for future reference, it is always better to use two links than to post the files together like that.
Was fixing save loading bug for 10 mins, found bug: 😂
I solved it. I was also invoking the event on the Update method on the PlayerMovement script, I hadn't see that line
yeah that'll do it. you'll have more frames when not viewing the editor since it doesn't need to draw the inspector and other editor elements every frame
Thank you anyways for your work and concern helping people
How do developers attach clothing to a character that has multiple body types? Such as seen in the WWE character customization. Is there a name for that?
don't crosspost
This is a coding channel
? It's a coding question
Ok show relevant code then and we can help
delete it from #💻┃unity-talk also while no one has responded
bruh, why is my prefab not working when sending it to git, to a new branch... Its an empty object/prefab when i merge it to a other branch ughhh... :{
Is there a way of converting multi-dimensional arrays to a string value? im trying to sort a save system for my games high scores, which (due to how many varients of mode there are) are best stored in a 3D array. However, when converting these values to a string to save in a Json all the data is lost. Any ideas on how i can solve this?
This is also definitely not a coding question. Probably more blender/asset related. Once you have the model which can actually swap out body types then it's just a matter of toggling the correct one which is 1 line of code
How do developers CODE clothing to fit characters that has multiple body types?
Show relevant code, which json library are you using?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A 3d array for high scores also does really sound questionable (aka not needed). You could likely use a dictionary, since I suspect you are mapping game mode to index
You don't have to respond and it's okay if you don't know.
Im clearly responding to someone else in that message.
Sorry, those are perfectly reasonable and required questions in order to help you
Careful, @eternal needle will say that's not code
https://gdl.space/ileloxocah.cpp Heres the link to the code, and i suspect there is probably a better way to save the highscores than with the 3D array. Essentially there are 3 different factors in play for each game (Map, mode and difficulty) and i want to store a seperate highscore for each combination of factors
Ty
they would likely make different versions of the clothing asset that fit the different body types. then naturally they would just use the one that fits the body type for that body type
so not a code question
Nice way to earn yourself a block from me and anyone else that helps in these channels. Kindly fuck off
Ok, so you use JsonUtuility, try using Newtonsoft
If you're rude right out the gate idc if you block me. I PREFER it
Doing me a favor tbh
mate, you're the one being rude
I just asked a question
Do you have an actual programming question?
and you were informed it wasn't a code question. and not to crosspost. and then started bitching about it.
you should have deleted the question from here and left it in #💻┃unity-talk which was the more appropriate location for it
thing is, i tested it out, if i simply convert the array to a string and back without using Json it still loses the data, so i dont think its the converting to Json thats the problem...
On top of Steve's suggestion, I would also split this up. You dont really need such a complicated array here. You could even just store high scores for each map or mode in it's own array.
how do you convert the array to string without using Json?
why are you trying to manually convert the array to a string? just let newtonsoft serialize it properly
My question is a coding question is it not?
if i start saying code words, it's a code question, right?
no point arguing, your question in the beginning was right their response was wrong but so was yours after.
ok, 1. when i tested with arrays it lost the data not only for the 3D array, but with 2D and even 1D arrays aswell. 2. Im not sure how i would swap over to Newtonsoft as i have never used it, is there a tutorial i can use to get it set up somewhere?
How are you testing it?
Ty, I just didn't understand why they responded to me so rudely. 😕
#💻┃code-beginner message
I answered them pretty much right away. Doesnt matter if the person want to believe
sorry but saying "it is 1 line of code" isnt very helpful is it
🤷♂️ the main point being that it's clearly a blender or other model creation tool issue
i was changing the arrays to be 2D or 1D respectively, changing values within them, and no matter what it always produced this when asked to load the data. It also gave the same response when i simply used .ToString() to convert to a string aswell
It's pretty helpful if you show code as you say these, because people really have no idea how you are converting to string and back without json. And especially this would cause compile errors
Are you doing .ToString? 😅
this is the expected result when you use ToString on any collection, or type that does not have ToString overridden, it will just print the type
yep, that is how ToString() works when applied to objects
i wasnt using ToString with the JSon convertor though and it still gave the same result?
It’s not going to pretty print your elements
because JsonUtility does NOT support multi dimension arrays
And it sounds like Json converter fall backed to ToString because it is unsupported type
ah ok ok i understand now. Im assuming the Newtonsoft does support them then?
yes
Also I suggest getting the Newtonsoft converters package once you figure out setting Newtonsoft. Itll handle stuff like vector3 and other types for you
shouldn't be necessary if they are using the latest version available in the package manager
oh wait, actually it might still be definitely still is necessary for some types
Thanks for the help guys, all setup and working now 👍
Hello guys.
A newbie question:
I have controller script to my player object who work perfectly. But in the moment hes connected to animator hes not able to move.
I checked all answers in google/gpt nothing fixed it :d
show relevant !code and any errors in the console
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i have some spawnpoints that have a rigidbody2d and a boxcollider2d. these spawnpoints spawn enemies that also have a boxcollider2d and a rigidbody2d. however now the enemies push and run into the spawnpoints. is there an easy way to make these two objects ignore collissions?
why do spawn points need physics?
the objectively correct answer is to remove the rigidbody from the spawnpoints. there is no logical reason they should have one
they needed rigidbody so i could disable them when they enter terrains trigger, so enemies dont spawn in terrain
the spawnpoints move around
use a physics query, not a rigidbody
a simple checkbox or something like that only when you move it would be sufficient to check whether it is on top of something it shouldn't be active in
Hello friends, I'm struggling, someone help me 
I have a Isometric Y as Z tilemap and want tiles to be highlighted on mouseover using a sprite which is already on the scene but will show and switch positions when hovering over tiles.
- Cell size of my isometric cell layout is
1, 0.5, 1 - The projects
Transparency Sort Modeis set toCustom Axiswith following values:0, 1, -0.26
What I have tried:
- Get mouse position by using
Input.mousePosition - Convert the mouse position to world position using
Camera.main.ScreenToWorld() - Convert the world position to cell position calling the grids
WorldToCell()method - Change the position of the highlight sprite to the cell position
But the position is off like half of the tiles width in px.
(No screens right now, I'm on phone)
Appreciate every help.
this is my code and it works great but when connected to my animator i see my player replacing to walk animation but does not move anymore:
and there is no errors
The buttons I'm adding listeners to only sends the same wrong int to selected choice, it sends the int 4 which is 1 above the choices.Length through all buttons which shouldnt be possible.
//Setup new buttons
for (int i = 0; i < dialogue.choices.Length; i++)
{
choiceButtons[i].gameObject.SetActive(true);
choiceButtons[i].GetComponentInChildren<TextMeshProUGUI>().text = dialogue.choiceText[i];
// Add listener to the button
choiceButtons[i].GetComponent<Button>().onClick.AddListener(() => SelectedChoice(i));
}
If I were to make my boss decide one random attack and make it unable to repeat the last one, this is how I would make it right?
Also how do i tell it to reroll in the else{}?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i had same issue, i think what you have to do is move it by a different amount based on where you move the mouse
since going up/down is like 1 or 0.5 but then going diagonally is 0.25 or something
could just use a list and add/remove the ones you used and only use the remaining ones
Yeah but idk how to use those tho
i really hope you aren't creating a new instance of Random every time you call whatever method this code is in. but also you don't need this super complicated if statement, just use a while loop where the condition is checking whether attackNumber is equal to lastAttack and call Next until it isn't the same
then learn, its quite easy to use a list
Actually comparing attackNumber and lastAttack is so smart
you also don't really need to use a List for this as you don't actually need to remove anything from it since you aren't preventing it from repeating an attack permanently, just preventing the most recent one from being repeated. So you could use an array of Action and store the attack methods in the array, generate an index, and compare that to lastAttack. then when it is different, just invoke the action at that index of the array
But I wanna make the numbers come back after use, so I figured using a variable that changes value better
how do i make it so an object with a boxcollider2d doesnt get pushed out of another object with its own boxcollider2d?
make one of them a trigger
is this still because of the spawn point thing? because i already told you how you can solve that #💻┃code-beginner message
the spawn point wouldn't need a collider or a rigidbody if you do what i suggested
yeah but i tried that but then the spawnpoints push the player when they are pushed out of the terrain, because they are a child of the player
what is a physics query?
I figured out that for some reason it's adding all the listeners at the end with the reference to i which is going to be 4 at the end. So adding what looks like to be a completely unnecessary index ref before adding listener fixed it.
// Add listener to the button
int index = i;
choiceButtons[i].GetComponent<Button>().onClick.AddListener(() => SelectedChoice(index));
How do i tell it to reroll then?
well that just proves you did not try what i suggested.
a physics query is a query of the current physics scene to check for colliders in a specific area or path. Physics2D.CheckBox is an example of that and is literally all you need instead of relying on OnTriggerEnter2D/OnCollisionEnter2D
still this #💻┃code-beginner message
this is a very common mistake made when using lambdas, you've hit on the solution
ah closures, the curse of the anonymous method. here's some info about why it happens and how you can avoid it (which you're already doing) https://unity.huh.how/anonymous-methods-and-closures
Such a weird thing 😅
Thank you for the source.
It's simple really, lambdas pass by reference even for value types, so you are passing the address of i not the value of it
Is there any Attribute for a variable to set if it's required or optional to set on the inspector? I have look into this but I haven't found anything, maybe I'm searching in the wrong place: https://docs.unity3d.com/Manual/Attributes.html
not a built in one, no
sorry but i really do not understand. physics2d.CheckBox is not a thing in unity, and i cant find anything like it when searching
https://pastebin.com/X8A9E4FN
this is my current code if that helps understand whats going on
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.
ah right, only 3d physics has the CheckXXX methods. so you'd use an OverlapBox. or a raycast, or literally any other physics query that makes sense in context of checking the position
you should also really consider not naming your classes the same thing existing unity components unless you really know what you are doing (and can also easily articulate that you are using your own component type when trying to receive help with it)
this is a code channel. delete it from here and post in #1179447338188673034
ive tried reading this but im not sure how i should implement it
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
well that's the 3d version not the 2d one
oh sry. ive found the 2d one, but still. so it checks if a collider is within a certain area. but should i do that in the tilemap script (should be renamed as you said)? and can i then do something like check if that collider belongs to something with tag spawnpoint and then ignore it?
do it from the spawnpoints themselves whenever they move. and you can check if they are on top of something they shouldn't be active over. and if they are you can just not spawn anything
Im using a character controller for third person movement, and I also created separately an hoverboard that moves based on rigid body and forces. Basically I want to let the player hop on the hoverboard and "change comands". How should I implent this? like, do I disable the character controller and make the player model a child of the hoverboard? or is there a better way?
yeah that would typically be how you would swap to physics based movement from the CC
i see, thanks!
Yo peps, just asking if there's a linq method where you can get the current # of iteration?
What's the use case?
But like... what's wrong with for?
Gonna convert it into a dictionary that stores an item and an index with a string name key from an array of items. Just need to get the index.
Now i gotta make a loop.
And that's... difficult?
No. But i wanted to know if there's something that alr does it.
Why is Object Variables not clickable?
Why is the prefab not being noticed by the problemManager? I dont understand it. Someone can see the mistake?
public class ProblemManager: MonoBehaviour
{
public ActionDialog IndividualDialog;
public IActionDialog GlobalActionDialog;
public List<Problem> ProblemList;
public ActionDialog GetIndividualDialog()
{
if (IndividualDialog == null)
{
Debug.LogError("Failed to get a valid dialog from IndividualDialog! blaah");
}
return IndividualDialog;
}
( it returns the LogError)
is there perhaps more code in this class that you aren't showing?
public class ProblemManager: MonoBehaviour
{
public ActionDialog IndividualDialog;
public IActionDialog GlobalActionDialog;
public List<Problem> ProblemList;
public ActionDialog GetIndividualDialog()
{
if (IndividualDialog == null)
{
Debug.LogError("Failed to get a valid dialog from IndividualDialog! blaah");
}
return IndividualDialog;
}
public IActionDialog GetGlobalActionDialog()
{
return GlobalActionDialog;
}
}
public class ProblemPopup : IPopup, IPointerClickHandler
{
//// Will have some relation back to the student.
public Student originStudent;
private ActionDialog dialog;
//// Temp variable, will be replaced with a service locator to the ProblemManager.
//// Later variables will ensure that only if the student has been touched, that the popup will be clickable.
public ProblemManager problemManager;
public void OnPointerClick(PointerEventData eventData)
{
if (originStudent == null)
{
Debug.LogError("originStudent is not initialized!");
return;
}
if (!originStudent.isInRange)
{
Debug.Log("Student not in range");
return;
}
if (problemManager == null)
{
Debug.LogError("ProblemManager is not initialized!");
return;
}
dialog = problemManager.GetIndividualDialog();
if (dialog == null)
{
Debug.LogError("Failed to get a valid dialog from ProblemManager!");
return;
}
dialog.student = originStudent;
dialog.ShowPopup();
Debug.Log("Individual action: Open dialog.");
}
it fails on dialog = problemmanaer.getindividual
Why is Object Variables tab not clickable?
Im trynna access object variables
why cant i click it?
try to reference to a GameObject with the given Script and Assign it in the Inspector
!code 👇 large blocks of code should be posted as a link to a bin site
but are you certain you are accessing the correct ProblemManager instance? and that nothing else is assigning that variable?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hmm I think i see it. Why or how come it says mistype match? I'm trying to import the problem manager inside this var. that literally the same type :{ zZzZz
I don't really think I understood how persistent path works haha
public static void CreateAndWriteSaveGame(string gameState)
{
var currentDateAsString = DateTime.UtcNow.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
var currentDateFormatted = currentDateAsString.Replace(" ", "-");
var currentTimeSuffix = "-" + Time.time;
var saveGameFileName = currentDateFormatted + currentTimeSuffix;
var pathStart = Application.persistentDataPath;
const string gameSaveSubPath = "/Save Games/";
var saveGamePath = Path.Combine(pathStart, gameSaveSubPath, saveGameFileName);
File.WriteAllText(saveGamePath, gameState);
}
So how do I make it point to some game related folder?
you're just using Path.Combine wrong, remove the slashes from the gameSaveSubPath
you'll probably also need to create the folder if it does not exist already
private void ComboThree(System.Action finishAction)
{
bool firstDashAttackDir = Random.Range(0, 2) == 0;
System.Action spinAttack = () => { TeleportToRandomCornerAndSpin(finishAction); }; // third
System.Action secondSlash = () => { TeleportNearPlayerAndSlash(secondDashSlash); }; //second
TeleportNearPlayerAndSlash(secondSlash); //first
}
is this an ok way to use delegates? when a state ends it calls the finishaction and starts the next state
Yup works now, cheers
Just wondering: is there a Unity shortcut to move into the "persistent app path"?
Because in the editor I can't see the file
the location of it depends on the platform, but if you look at the documentation for the property it provides the path so you can navigate there on your file explorer
I put a button in my game that opens the persistent data path in your file browser
it would be easy to add that as as menu item in the Editor
Would you mind sharing the button script? Sounds useful
yeah i was about to suggest that, i don't think there's any built in way to do it automatically, but making a button for it is pretty trivial
Cheers
There is no Application.logPath, so I had to construct that myself
I haven't checked if that works on Linux
using System.Diagnostics.Process.Start to open the folder feels scuffed
you can also slap a Menu Item attribute on that if you want to add a menu item like with the GameObject, Edit, etc menus at the top
yeah
there is
EditorUtility.OpenFilePanel("Persistent Data", Application.persistentDataPath, "*");
[MenuItem("Foo/Bar")] adds an entry to the menubar up top that runs the static method the attribute was attached to
doesn't that open a dialog to select/open a file rather than just opening the file explorer to that path normally though?
It does
Yes, but it is basically a file explorer window
although it's a dialog
you could finagle your way from that to an actual file explorer window
This worked like a charm on windows though
Yup serialisation works :)
Now I would like to plug in this service. Do you guys know easy to use libraries for encryption?
Anyone know that feeling where you've been looking for a bug for hours and the longer you search the more you realize it's gonna be something insanely stupid and you're gonna hate yourself when you finally find it? I'm 4 hours in ...
Have you tried turning it off and on again?
what are you trying to accomplish
should i instantiate prefabs or components on the fly?
Encryption. But I found C#'s Aes class :)
well, obviously
but what are you trying to do with it?
Are you asking about the difference between instantiating a GameObject and instantiating a specific component type?
If so, there is no difference, other than what Instantiate returns to you. When you instantiate a Transform or a Collider or some mono behaviour type you created, Unity instantiates the game object it's attached to
scritpable objects can be changed or are read only tho?
You can modify a scriptable object just fine. However, this can have some surprising behaviors if the scriptable object came from an asset.
The changes will stick around until the object is unloaded.
In the Editor, an object referenced in a scene you have open for editing will not unload when you quit play mode
So it will look like the changes are persistent.
If you load a new scene that does not reference the object, it will unload, and your changes will go away the next time the object is loaded.
Found a much better solution, if you're interested, I can share.
And, of course, in the built game, you can't permanently modify assets at all
So if you quit and reopen the game, the changes you made will be gone
i am very dissapointed in myself for reading this c#'s ass class bruh
Hey I have a questions about the Bounds of a prefab. Currently I'm getting the bounds of a single prefab from its meshRenderer to perform calculations in a script, but I now want to create a prefab made of different prefabs by just dragging them in a parent prefab, and still have the Bounds to encompass the size of the prefabs together. Is there a simple way to achieve this? I tried wrapping the parent in a BoxCollider but it needs to be instantiated in order to get the bounds
because there's no maxLinearVelocity on Rigidbody
in your version of Unity
Looks like it started in Unity 2022
should almost all textures have the read write disabled?
yes
[BurstCompile]
public struct MyFirstJob : IJob
{
public NativeArray<float3> ToNormalize;
public void Execute()
{
for (int i = 0; i < ToNormalize.Length; i++)
{
ToNormalize[i] = math.normalize(ToNormalize[i]);
}
}
}
how can i call this?
Is there a way to apply the force of a rigidbody into the forward direction of an object and not just an axis?
Because when I use AddForce on a rotated object it still applies force towards the global z axis not local
You can either:
- Use AddRelativeForce
- Convert the vector yourself
Ohhh thanks
e.g.:
rb.AddForce(rb.rotation * force);
// OR
rb.AddRelativeForce(force);```
Convert the vector from local to world space
https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html
So turns out everything was working correctly, I was just trying to load the wrong data ...
Trying to load the itemslot id instead of the actual item id, 6 hours well spent!
HashSet<string> keys = new HashSet<string>();
/*foreach (var key in character.ItemSlots.Keys)
{
if (character.ItemSlots[key] != 0)
{
keys.Add(key.ToString());
}
}*/
foreach (KeyValuePair<int, int> pair in character.ItemSlots)
{
if (pair.Value != 0)
{
keys.Add(pair.Value.ToString());
}
}```
Confusing that your HashSet name is just keys, naming is important 🙂
well it is a "list" of keys
very new, working on a Udemy course that is very helpful, but it is doing a poor job at explaining syntax and differentiating structures. For example, this structure below. Or when you need to use <> braces to identfy an object, etc. Is there a course, video, or something that anyone can recommend on the different structures and the required syntax? Im struggling when it comes to parsing through documentation and feel like there must be a lesson someone put together.
itemIdsToLoad?
The thing you are looking at in your screenshot is called an "Attribute" in C#
Thank you! This is one of maany examples. Looking for a succinct rundown of the various structures, common syntax, where they have to be declared if so, etc.
Basically you use it to mark that the ScriptableObject type it's adorning can be created from a menu within the editor
THere isn't really such a thing. C# is a big language with lots of features.
The best I can do is link you to the C# docs I guess
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/
the Language Reference is a good place to look for general information https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/
i also consult the actual specification for really fine details https://learn.microsoft.com/en-us/dotnet/csharp/specification/overview
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Trying something srry
Hey I need some help. I'm trying to add a simple countdown timer into my game. Copied some code for it but the timer does not update ant stays at (0:00) : (1:00) when I press play. I can see the timeLeft variable go down in the inspector but again the text(legacy) object isn't changing. Any help is appreciated
Code is in that link above
it doesnt update cause you wrote it wrong
not sure where you got that from, but It should be
timerText.text = string.Format("({0:00}:{1:00})", minutes, seconds);
you can also do
timerText.text = $"({minutes:00}:{seconds:00})";
I have a magnet pickup in my game. So I have defined a range of it to attract coins. Earlier it was attracting coins only in range as I was creating new coins every frame. Now I have been using Object Pooling, so whenever magnet is active, all the coins in the scene are attracted. Please do help.
{
if (pm.canAttract)
{
transform.position = Vector2.MoveTowards(transform.position, cs.playerTransform.position, cs.moveSpeed * Time.deltaTime);
}
}```
Ref: https://streamable.com/mnz8lu
Oh my God it works
then 1) do not move them in update, use fixedupdate
2) do not move them by transform. use their rigidbody
Yeeesss
when I move it in fixedUpdate, they dont seem like moving, they disappear in 1 frame
the transform and rigidbody will be fighting each other to overwrite the position
then you should fix that. not make it extra wrong by moving it to update
this problem wasnt occuring when i was using instantiation. Its occuring after I applied Object Pooling. What I suspect is its because its treating the other coins as the same coins that collided with the player
when you bring something out from the pool, you need to really reset it
like how??
{
if (!poolDictionary.ContainsKey(tag))
{
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true);
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
public void DeactivateGameObject(string tag, GameObject collidedObj)
{
if (poolDictionary.ContainsKey(tag))
{
Debug.Log("Contains tag");
foreach (GameObject obj in poolDictionary[tag])
{
if(obj == collidedObj)
{
obj.SetActive(false);
Debug.Log("Item False now");
return;
}
}
}```
- i am not writing code for you. that is your job
- you need to reset all the internal variables
- Im not asking u to write code
- How do i reset
i recommend you use an interface, where every monobehaviour that needs to reset on the object gets a Reset() method called
then the spawn object looks for all the IResettable components and calls Reset()
it resets nothing
this is new for me, never used that
if you have a script in the coin that gets a variable set at 0 at start, then it becomes 5 in its lifetime, explain to me how that coin comes back into play with the variable at 0
because the point of a pool is to save time by not reinstantiating
but that means you need an equivalent way to bring something back from scratch
as though it were brand new
otherwise code will depend on whatever happened during its old lifetime
can you please elaborate more on how do i begin with?
start by not object pooling until you have a better grasp on some more of the basic tools, such as interfaces
but if i want to, how do i begin with interfacea
watch a guide video
because i really want to
okay
Debug.Log(string.Join(",", myAes.Key.ToString()));
Debug.Log(string.Join(",", myAes.IV.ToString()));
Why can't I see the array properly formatted?
I don't think this code is producing those logs
Can you prove it? Add some more info to the log
You're converting the arrays to strings before trying to join them
assuming myAes.Key is an array
Byte[] yes
I had a question. Why would I use an interface? Like its primarily used for abstraction so what purpose would it solve? Why not just create a function Reset()????
because an interface lets many different classes implement Reset(), even if they have nothing to do with each other. and then let you call that method via the interface
Instead of writing a lot of different code that resets different things
void ResetCar(Car car) {
car.Reset();
}
void ResetComputer(Computer computer) {
computer.Reset();
}
// etc...
You can just do it once:
void Reset(IResetable resetable) {
resetable.Reset();
}```
what if we create a function with generalised arguments? Just call that method with different arguments.. so like wont it work the same way?
or imagine them in a list:
List<object> thingsToReset = ...
foreach (object o in thingsToReset) {
if (o is Car c) c.Reset();
if (o is Computer comp) comp.Reset();
// etc... :sad:
}
You can do:
List<IResettable> thingsTOReset = ...
foreach (IResettable resettable in thingsToReset) {
resettable.Reset();
}```
I don't even understand what you mean.
where you would you create that function???
How would you call it?
Hi, this is a script for gun in my game that seemed to work well until I added few lines of code in there https://hatebin.com/ekpgcteqoo
the problem now is that the gun wont even shoot
before you shoot a bullet, your bullet variable is null
So doing bullet.velocity = ... will be an error
Okay. I will create Reset() in the main class. Now if an object is to be reset, then pass on the arguments (GameObject obj/tag) on that function call whenever a certain event happens
What is a "main class"?
Pass on the arguments to what?
Show me a practical example of what you're talking about.
I see...
why are you calling BulletTrajectory in Update?
What's the point of that?
And you realize it will only affect the most recent bullet right?
Is bulletbehaviour on the same object as gunbehaviour
well, idk to be fair
seems pointless
nope
You should know, you wrote the code, right?
Think about what your code is doing and why
aight will fix that then
Then getcomponent will not work as written
I am gonna try it thx
the main class I mean the script by default. Pass arguments to the defined function.
Example:
void update()
{
if(resetCoin == true)
{
reset(coin)
}
}
void reset(gameobject obj)
{
reset(obj);
}
}
```
//code BETWEEN the ticks
```
Also needs ticks at the end
void reset(gameobject obj)
{
reset(obj);
}```
What? This code will just give you a StackOverflowException (assuming you fix the `GameObject` typo)
I mean
void reset(gameobject obj)
{
///do reset the object
}
Ok and how do you "// do reset the object"?
Which object?
How do you know which component it has to be reset?
Are you using code to do it?
Might be better in #🖼️┃2d-tools
I dont know how to reset that object. Thats what I was asking before
no code apply, just putted images so far
You might as well have written "wave a magic wand" there.
This is a code channel
haha
The way would be to use the interface
thanks
how to reset it using that?
will it be fine If I paste my main question here again?
e.g.
void reset(gameobject obj)
{
if (obj.TryGetComponent(out IResettable resettable)) {
resettable.Reset();
}
}```
this
This would be with the interface
without the interface, you would need to check for any number of different resettable components
I don't know what this has to do with interfaces
is that already defined method?
seems unrelated
TryGetComponent is defined yes
IResettable is a hypothetical interface you would write and implement
I don't know I don't have enough context
may i explain
I have a magnet pickup in my game. So I have defined a range of it to attract coins. Earlier it was attracting coins only in range as I was creating new coins every frame. Now I have been using Object Pooling, so whenever magnet is active, all the coins in the scene are attracted. Please do help.
{
if (pm.canAttract)
{
transform.position = Vector2.MoveTowards(transform.position, cs.playerTransform.position, cs.moveSpeed * Time.deltaTime);
}
}```
Ref: https://streamable.com/mnz8lu
Object Pooling Code:
``` public GameObject SpawnFromPool(string tag, Vector2 position)
{
if (!poolDictionary.ContainsKey(tag))
{
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true);
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
public void DeactivateGameObject(string tag, GameObject collidedObj)
{
if (poolDictionary.ContainsKey(tag))
{
Debug.Log("Contains tag");
foreach (GameObject obj in poolDictionary[tag])
{
if(obj == collidedObj)
{
obj.SetActive(false);
Debug.Log("Item False now");
return;
}
}
}```
is it possible to disable this through script?
yes
how can i do it
Rigidbodies are not Behaviours
rigidbodies don't have disabling
they have no enabled property
The screenshot you shared was a CircleCollider2D
notice there is no corresponding checkbox for a Rigidbody2D
yeai jus noticed
i thot all of them have it
if its 2D rigidbody there is a Simulated you can disable
https://docs.unity3d.com/ScriptReference/Rigidbody2D-simulated.html
thanks man
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what would be the best way to like to pick up objects in unity in your opinion
raycast, physics casts/overlap
can anyone look into this? Im ready to explain more
i want the player to pass thru the object so i used layermask to do it , but the raycast wont hit
you probably used layermask wrong
is there a better way?
I made some code to load data from cloud, but i dont know how to make it wait first, any ideas? (DataStore is not my code, its part of API, and it doesnt have async methods)
public void LoadData()
{
DataStore.Get("bombBuffCount", false, value => { SaveValues.instance.currentGameData.bombBuffCount = int.Parse(value); });
DataStore.Get("shakeBuffCount", false, value => { SaveValues.instance.currentGameData.shakeBuffCount = int.Parse(value); });
DataStore.Get("slowMoBuffCount", false, value => { SaveValues.instance.currentGameData.slowMoBuffCount = int.Parse(value); });
DataStore.Get("coinCount", false, value => { SaveValues.instance.currentGameData.coinCount = int.Parse(value); });
LoadingManager.instance.RestartAsync();
}
yea probably
if you want player to pass through make it trigger? unless it needs to be solid
its going through the ground man
you can also disable collisions between specific layers
yea i made a layer for the player and disabled its collisions
but the raycasts wrent hitting
use Async, with await operator
they were hitting before
uhh... any example or smth?
are you able to run DataStore.Get async
oh wait sorry
API i downloaded from asset store/github
i can change it... but never worked with networking and stuff, i use GameJolt to make cloud saving and achivement stuff
thats very vague..
also generally these type calls should be async
since they vary in speed, especially client internet speed
well... its fully on C# but... i dont wanna mess with it...
you dont want your app to lockup while waiting for dl
what?
"its fully c#" what does that even mean.
like, some API uses .dll's
you using a library if you're not sure how it works?
do you know what an API is ?
no..?
so why are you using the term so loosely
yes..?
seems this is a waste of time, since you have no clear goal in what you're trying to achieve
what you mean by clear goal? well.. i was asking if is there any way to use async/await like Tasks with void
can somebody please tell me why i cant wall jump https://hatebin.com/avoqugypda
this code has absolutely no errors at all
i have no idea why i cant
if the function is async it doesn't matter if its void or Task
you still haven't explained why you are using this library, thats what I mean with no clear goal
you just said you're using a library, which you haven't even linked
it dosnt
ah dam..
then you cannot await
What debugging steps have you taken?
this code has absolutely no errors at all
This is really meaningless. Getting correct code is about making it do the right thing, not just getting rid of errors
it means.. its imposible to make it wait before executing next line?
absolutely none cause i have no idea how to do it
Debug.Log
to start with
why not do the sensible thing and actually explain what it is you're trying to accomplish with this library in the first place?
yea but like where
wait, do i need to explain what is this lib?
Start with the place where you expect code to run that doesn't seem to be running.
Print the variables that are expected to be a certain value and make sure they're as you expect, etc..
Use logic and reason to deduce the problem
is there like a language barrier or something ?
ye..
ah wait
you mean why i use this lib and not trying any other?
Which purpose did you add this library, what are you trying to accomplish with this ? what issue does this library solve ?
whenever i put debug log it just has red lines under it
mate you have yet to say why you added this library in the first place..
Red lines indicate you have written invalid code. They also come with error messages which you should read which will help you fix the invalid code you wrote.
Its the only "API" that handles all GameJolt stuff, like sending requests, getting user data, and other stuff related to gamejolt accounts
I can send my own requests with scripts and recive data, but its really hard, so i used this one because it has pre made prefabs/menus and examples
Link the Library, send url
https://github.com/InfectedBytes/gj-unity-api
https://infectedbytes.github.io/gj-unity-api/tutorial.html
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
i have no idea what that means
well, show your code
You have to show what you wrote
these errors are too generic to tell what it is
i wrote debug.log;
well thats now how you call methods
it sounds like you tried to do something like 1 + 2;
you can't just write an expression by itself like that
As the error mentioned, one valid expression is a call expression
like SomeMethod();
"call" is basically ()
My man
oh so i put the code in the brackets
this is just a WRAPPER to an API not itself an api. Ok so you're trying to use GameJolt ?
yes
because it's not:
- assignment:
val = 1; - call:
Debug.Log("Hi"); - increment:
val--; - decrement:
val++; - await:
await SomeAsyncMethod(); - new object:
new Something();
🌠 the more you know
If you don't know how to call a method, you should really consider following the tutorials on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i already tried making my own with tutorials on GJ docs, but managed to send request and recive data once (trough browser lol) and that all... when i tried again didnt receive anything, only bunch of API errors
if you made your own webrequest then you could potentially do coroutine awaits
but doesn't seem the library you sent has any async
maybe it does it for you
it does have a callback action at least
!paste
you are probably looking for !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes, thanks
can you explain again why you need to "to make it wait first," exactly ?
Yes, because you don't want to freeze the game for 300 milliseconds as the request is sent.
i want it to download data, then restart scene
so put the callback for RestartScene
This library uses callbacks. When the operation finishes, it runs the method you gave it.
https://gdl.space/jukilezoru.cs
could someone talk a looke at the isWalking logic I feel there's a neater way to write it
This means that the game will continue running while the operation is taking place.
what if i have multiple of keys that i need to get?
then make all of the requests and wait for all of them to finish
You have to write it however makes most sense to you, if it works and you can read it.. shouldn't worry
I mean it just looks really rough and redundant
it's a bit odd to have both "is walking" and "is running" as two separate variables
well maybe i'd use enum instead of bool for states
you can't be both walking and running
so yes, an enum would be appropriate
public enum MovementType {
Stopped,
Walking,
Running
}
What could it mean when i try to instantiate a object. is says it found the correct prefab to instantiate, but it wont load into the scene at all?
Using a obstract class for this, where one type of popup does work, but the other doesnt... And I cant find the mistake...
perhaps it is instantiating really far away
If you don't give a specific position, you'll get the prefab's position/rotation/scale
~~could you share screenshot exact error and ~~ oh nvm thought you got errors, but yeah link code maybe ?
// test
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sec
I have no idea what this is but i'll look it up, thanks
enum lets you create a new type with a fixed set of values
MovementType.Stopped, MovementType.Walking, and MovementType.Running are the three values of the MovementType enum
so it's like a boolean dictionary?
I wouldn't say that, no
You can use them with switch statements to run different code for each possible enum value.
checks which is currently True then works with that?
You could check if the current movement type equals one of those three values
yeah I get you
switch (moveType) {
case MovementType.Default:
// stuff
break;
case MovementType.Walking:
// stuff
break;
case MovementType.Running:
// stuff
break;
}
this is so smart omg
how do I set the movementType.variables tho?
the normal way?
just assign it to a boolean?
MovementType moveType = MovementType.Running
As fen said, it is not a boolean, so not sure what you mean by "assign it to a boolean"
the if statemen / switch is what makes it boolean
switch is just a fancy if else chain
Also, my unity remote 5 keeps randomly stop working 😦
I'm not that much of a beginner lmmfao
just making sure , you did call enum a boolean dictionary lol
Is this a unity unique thing or a C# thing
https://gdl.space/voviduxici.cs
Hope that this will give a lil sight in what the thought of it all is. :x
in what regard ?
some things exist only in unity not C# is enum one of them?
ohh enum is a c# type yes
No features of C# are unity-specific.
Damn I should really learn C#
There are certainly unity-specific types (like MonoBehaviour) and unity-specific functionality (Unity runs the Update method on every enabled-and-active MonoBehaviour every frame)
Yeah I get this part
Coroutines are unity specific, but they use the C# type IEnumerator which is common for iterating
It looked so similar to java I just never bothered to learn it
and importantly, there's no "magic" with coroutines; they aren't some kind of brand-new C# language feature
its much easier to understand the unity API once you got a lot of the traditional c# down, also allows you to write better code overall anyway
a coroutine is just an iterator that unity will call MoveNext on regularly
Can I learn on the go tho?
As I work on projects
Learning C# with what tho, projects?
yeah just learning new things and messing with them repetitively. The Microsoft site has very nice lessons of random stuff
the modules are very well done, gotta respect m$ for that
thanks
there are many ways to debug
and it sitll didnt work
what are you trying to debug ?
Prints statements everywhere has never failed me lo;
an if statement for wall jumping
VS debugger is good to see the states of all the variables at a given point in time
do you know where its spawning now instead?
no, it says in code it instantiated it (cuz i assume cuz it doesnt give any error on that line), but it does not show up in the scene hierarchy at all, niether the prefab. So I'm rlly confused.
instantiatedPopUp = Instantiate(popUp);
you're talking about this ?
yeah
because when you do not pass position it is spawned at World 0,0,0 iirc
does the code actually run
note that you're calling SetActive on the prefab, which does not make sense
Yeah its supposed to spawn at 0,0,0. its the location of the canvas.
so parent it to canvas, pass the transform in Instantiate
it runs yes. it goes inside that method. and calling the correct prefab. Iknow the setactive dont make sense. was just trying for hope by now :p
you aren't instantiating it as a child of anything
also if its a UI element could also explain why you wouldn't be able to see it, even if you found it in world
no, its a canvas that needs to spawn, that will create a popup dialog of some kind.
okay, so popUp has a Canvas on it
yes the canvas is the prefab
put a Debug.Break() after the Instantiate line, then try to find it in hierarchy and press F when selected
Perhaps your code is immediately destroying the popup.
Is there a variable type that can reference a json?
Im trying to avoid the Application.persistentDataPath thing as that makes it hard to share the project through github.
You should log instantiatedPopup right after it is created. You can do it like this:
Debug.Log("Created: " + instantiatedPopup, instantiatedPopup);
Clicking once on the log message will select the object in the hierarchy, if it exists
what?
what does Application.persistentDataPath having anything to do with github
json in unity is just a TextAsset
contents stored in Appdata instead of the same folder
then use Application.streamingAssetsPath
public virtual void ShowPopup()
{
Debug.Log("Arrived in THE showpopup method in IPopup class");
if (popUp == null)
{
Debug.Log("Cant find popup object.");
}
Debug.Log(popUp.name + " going to be instantiated.");
// Check if the popup has already been instantiated
if (instantiatedPopUp == null)
{
popUp.SetActive(true);
// Instantiate the popup if it hasn't been instantiated
instantiatedPopUp = Instantiate(popUp);
Debug.Log("Created: " + instantiatedPopUp, instantiatedPopUp);
Debug.Break();
}
else
{
Debug.Log("Popup already instantiated.");
}
}
You see it ? :c
video needs to be mp4
why can't i use this on a button
first check what that error is
because it doesn't like that signature
yeah but then how do i get a button to support two object
Its a error related to a button that doesnt have stuff
what are you trying to do with that exactly ?
i wanna disable one thing and enable another thing
add 2 handlers, one for each tab
what's a handler
did it run? I dont understand. I dont see Break pausing the simulation
event handler. what you define in the event on the button
I removed the break yeah to show what was actually supposed to happen when clicking the popup that DID work, and not the other one when i walk at the other icon.
is there like no way to just do two items
no
I still dont understand what is going on in the video tbh lol
showing both dialogs come inside that method, with the correct gameobject(prefab. but 1 of them not spawning.
damn
The first pop up/dialog that shows is a popup that works lol. that was a sample of what its supposed to do. but then i walked at the top of the classroom to click on a different icon, which is supposed to spawn a different dialog, which uses the same class. ( u can see that cuz both of the times i clicked on something, the same Logs came in the Debug window(on the right side)
Hi! I am making a simple 2D platformer for school and wanted to add a lite feature, although I am not certain on how to do it. Right now in my game you can claim checkpoints, and I wanted to create sort of an inventory screen which shows you all claimed checkpoints and makes buttons for them (or at least unlocks their buttons depending on how many checkpoints you've unlocked). I thought of making a list where I add a checkpoint each time I claim one and using that to determine how many buttons, but I am really bad with UI elements. Any tips?
You dont even need any code to do this
store them inside an array then loop through the array to spawn the Buttons for eeach, make button script that links specific checkpoints or whatever you're doing
Could someone have a look at why the bullet movement behaves differently, when using GetComponentInParent, and having the script in the parent object or in both the parent and child object. Thanks
code on https://gdl.space/ledaxuqeci.cpp
Note that GetComponentInParent will search the current object before going up to the parent. If you have the script both on this object and the parent, it will return the script on this object.
oh, i thought it go search from the parent object right away. thanks
years later we still don't have a Skip self type of parameter..
trying to add package from git url (https://github.com/Unity-Technologies/NavMeshComponents) but keep getting this message
this is the old NavMeshComponents use com.unity.Al.Navigation instead
how do i install that
via the package manager
ok installed but got a bunch of compiler errors
Library\PackageCache\com.unity.ai.navigation@1.1.5\Editor\Updater\NavMeshUpdaterUtility.cs(47,61): error CS0246: The type or namespace name 'NavMeshSurface' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\com.unity.ai.navigation@1.1.5\Editor\Updater\NavMeshUpdaterUtility.cs(52,45): error CS0103: The name 'CollectObjects' does not exist in the current context
Library\PackageCache\com.unity.ai.navigation@1.1.5\Editor\Updater\NavMeshUpdaterUtility.cs(112,17): error CS0246: The type or namespace name 'NavMeshModifier' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\com.unity.ai.navigation@1.1.5\Editor\Updater\NavMeshUpdaterUtility.cs(112,60): error CS0246: The type or namespace name 'NavMeshModifier' could not be found (are you missing a using directive or an assembly reference?)
How do I add touch control for mobile?
this is wildly old
whats the new one
in the package manager
have you tried googling those exact words
is it this one
because when i installed it i got a bunch of errors
did you remove the old ones?
fixed itself after i restarted the whole thing
yes
so i saw in the obselete navigation tab there are options for bake and object that arent present in the new navigation tab, where would i find them now
they are on the navmeshsurface component. I suggest you go and read the documentation. Actually the old docs on the github repo are better than the new ones and they are very similar
and?
maybe i missed the navigation static option but i dont see it here
because the process is changed
you no longer need nav static
just bake, and choose if you want Collides or Meshes
This unity is absolute buggin. what the flip.
public void ShowPopup()
{
Debug.Log("Arrived in THE showpopup method in IPopup class");
if (popUp == null)
{
Debug.Log("Cant find popup object.");
}
Debug.Log(popUp.name + " going to be instantiated.");
// Check if the popup has already been instantiated
if (instantiatedPopUp == null)
{
try
{
instantiatedPopUp = Instantiate(gameObject);
instantiatedPopUp = Instantiate(popUp);
Debug.Log("Created: " + instantiatedPopUp, instantiatedPopUp);
}
catch (Exception e)
{
Debug.LogError(e);
throw;
}
it works but only if i apply use BOTH of the instantiatedPopUp = Instantiate... If i commend 1 out, it wont work... doesnt matter which one. but it works if i let it run both omfg... I'm so confused... It also runs through the instantiatedPopUp == null with the new popup, so it can keep spawning the popup.. what a mess..
also this #🤖┃ai-navigation question
ok thanks
oops i didnt know that was a channel
who's he ?
what
is that related to Google?
i found a yt video
the whole point of parenting to something is to inherit its properties
so what part of it you don't understand?
also show video cause it might be bad
in code?
transform.SetParent(null);
How do I limit the movement to just the left part of the screen
clamping
in the drop down for the new input control it only specifies the number of fingers down
i think
transform.position = parent.position
then you need a position or parent constraint
oh right ^^
how do i prevent both cards from being in the same gameobject?
make the slots custom objects
so it can have an occupied check
if its occupied return it or put it on closest slot
what does custom objects mean? sorry if it's a stupid question
the slot is a gameobject, which is stored in a list in the card script
like a c# object
use a constraint like I said
public class Slot{
public Card CurrentCard;
//etc
}```
thx 🙏🏼
just an example , basically make a method or property
if(slot.CurrentCard == null)
//place hard
else
//return card / put on closest
got it 
ur in #💻┃code-beginner asking about multiplayer 
Then less likely your question will get buried
It would be faster if you included all the relevant items in the original question. Seeing your three (3) messages in that channel, they have a pretty much insane lack of context, code blocks and debugging attempts. Check out #854851968446365696 for guidelines on how to ask a good question, and do it all at once, don't drop the info bit by bit as the conversation goes on
You miss 100% of the shots you don't take
Ask a full question there and wait for an anwser
You can't just undermine the organization of the server and expect positive reactions
That's just how it works here, nobody is entitled to get immediate help, but when someone is available and given that the question is nicely formatted they will help
also generally when you're doing networking , you should already have years of experience
multiplayer is not trivial
In that case, do what we did, read the documentation, experiment and figure it out for yourself
when I’m trying to download the lts 2022 2 errors comes up, the errors are android SDK & NDK Tools and OpenJDK how do I fix this?
also show relevant messages and log
is there a way through code to lock the cursor in the center and keep it visible
How in the world do I check if an object is moving in unity 6? they have changed how rigidbody.velocity is and its confusing me
im using this line of code to make my player move forward and backward so why doesn't it work? transform.Translate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical") * speed);
how do i make a cursor locked to the screen but not invisible
Cursor.visible = true;
ain't work
Huh then I aint got no idea lmao
hi everyone, i wrote code that makes the player jump as long as its touching the ground. an issue is that when i walk from one gameobject onto another one directly beside it it must mess up the code because i can no longer jump
this is all the code that handles jumping, top part is in Update void
bad way to do groundchecking
im new to this how does that work
if (y.velocity >= 0) :trollface:
the code i used was what i learned to use in unitys learn pages
that works in most cases
but what if youre at the peak of a jump
As for why it doesn't work your way: it's a timing issue. OnCollisionExit is most likely executed after OnCollisionEnter, which leaves you in a permanent playerGrounded = false
at very least you would use OnCollisionStay rather then Enter but again, using those physics messages is unreliable
you would jump over and over
that makes a lot of sense
that doesnt work cause youd always be jumping
oh
do you know how to lock a cursor and have it visible
im using this line of code to make my player move forward and backward so why doesn't it work? transform.Translate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical") * speed);
yes but that doesnt have anything to do with this code
can you tell me
how much you set speed ? also is code running
everything is working fine but when I press w or s my player aint moving
yuou could make your own cursor with a canvas
working fine ?
its not working, then its not fine
when I turn off character controller its working when i turn it off it stops working
you have a character controller ?
you should not be using translate
Why would you want the cursor locked but visible in the first place? It's pretty frustrating for the user to see that they're not in control of the cursor like they usually are. That's why it's hidden
i was kinda planning in on making it the crosshair
but whatever is fine
use the canvas to make a crosshair
Make a UI Canvas with an image in the middle?
im following a video guide and the guy uses translate and his is working fine
yeah thanks
the video is bad then
Character controller should be used with proper method
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
show video
i ended up with this
raycast is good but too thin
I use a sphere usually if its a capsule
so you can use a box
can you do a plane ray
Is there a way to place a UI object into a specific position in a scroll rect list based on where your mouse is on that list? So like if I'm dragging an object it gets added to the list in the position I dropped it at.
got it to work
thanks for the help
Hi, here you can see my way of implementing player damage from enemies it has 1 flaw though and thats that when enemy enteres my collider he damages me once and then just stands there. how do I make it so the enemy will damage my player over time inside of the trigger? https://hatebin.com/tuukdqeltt
Physics casts detect colliders, so when BoxCast() returns true you don't need to check whether the collider is not null. So the code can be simplified down to
return Physics.BoxCast(boxCenter, new Vector3(1, 0.1f, 1), Vector3.down, out _);
// Notice 'out _' which explicitly tells the engine to discard the value, as it's not used
thank you, i use AI to help me so i wasnt sure if it was needed or not
You would have to implement OnTriggerStay similar to your enter. https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay.html
There you would check with a timer if the player could be damaged again/ if it currently ticks.
thx, will check it out 👍
@short hazel if i could get your help one more time, this code still lets me jump even when i am in the air as long as there is an object below me, is there any way i can set a distance that object has to be below me for it to return true?
hi, im new to this scripting thing i was wondering if anyone can help me make a script for a school project
dont crosspost, also did you read what was sent to you in #💻┃unity-talk ?
ya
Bad Idea to use AI for learning
Yep, supply a maxDistance to the method. .BoxCast(..., maxDistance: 0.5f)
By default the distance is set to Infinity
https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html
in most cases i would agree but i think im using it correctly
nvm i can figure it out
i dont have it write scripts for me, i try on my own using the docs pages and then have it check it for errors, and it almost always finds them
thank you
what did you guys use to learn coding?
our brains
thx
Why are people here so rude and sassy to each other?
idk
https://hatebin.com/kcuovfovuk this is the functioning version with OnTriggerStay thx!
a lot of people in the industry tend to usually be more blunt
maybe because we get fed up of people asking stupid questions they have put no thought or effort into
This isnt the industry though its a place where people come for help