#π»βcode-beginner
1 messages Β· Page 90 of 1
Take that in mind that some ppl are understanding things through examples and not just a text and that I need just a simple answear to make me realize how something works and how I should use that so sending me a whole documentation is not really gonna help me with understanding how line of codes works
Like, 90% of programming is reading documentation. If you're bad at it and you intend to do anything more complicated than hello world, you should start getting better at it
And there is a saying that u shouldnt fix something that dont want to be fixed. Wich means that if I need a help with understanding why something isnt working then I am not really intrested in a whole comentations wich is like asking about grass and getting a book about biology
Or maybe use the debugger to see where something breaks/doesnt behave the way you expect it to?
There will come a time where you're trying to integrate an asset and your only sources are the code itself, an auto generated GitHub documentation page, and a 400 page forum thread
Yeah. Through my expirience its not like that. I can read documentations but I didnt really spend much time reading them and without any other expiriene with C# and Unity I made multiplayer game in month. Dont tell me how programming looks like because I already know it π
Tbh, unity documentation, is while really helpful, not that good imo
And my expierence with ppl "helping" is that noone really helps you but demotivate you
Could anybody help with this? I'm getting a CS0019 error for 65,12 and I'm not sure why since I've used //&& isGrounded // on an if statement before. https://hastebin.com/share/xugiqoyoxu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Unity documentation is among the best and most plain English documentation of any framework I've ever used.
||The sad truth is both of our statements are true||
I'm curious, can you link me to some docs that you find good/better?
There's also the fact that the pages you were linked were not "documentation" but rather plain English walkthroughs on how to solve common problems written by a moderator of this very server
Also I linked to the unity.huh.how page which is not official documentation, it's maintained by vertx
Demotivating through sending so many infromation with link when someone want a simple answear or like when ppl were telling me that I should make my first game just a simple singleplayer something instead of making multiplayer and that multiplayer is something I should do with minimum 1 year expierience. I dont want to put u down or something but try to realize that there is ppl who are diffrent than you and they can learn faster than you and dont need a whole documentation to realize something because they can just see thing how they work and learn
I could have explained it in simpler terms if you weren't giving such attitude
Yeah. the PLAIN english is perfect name for that
If you're afraid of reading documentation you should not be touching multiplayer
No u couldnt. U even said that u cant. And Osmall, dont start something that u wanted to end π
Sorry did you expect an explanation on how to serialize a reference to have dragons and political intrigue and a murder mystery subplot
We can discuss. With "stop" I meant the insults etc.
Thanks. I touched this and made a multiplayer game that now I played by my friend and it works perfectly β€οΈ
Can't and won't are not the same word
What are you gonna do when the tutorial finishes and the projects not done yet
If a small insults can hurt you than u have to be really weak mate. Imagine be so weak that barly a text form discord can make u whining about it
I'm not hurt. I just don't tolerate bullshit
Accessing the game object property from a null reference will throw nre
Says the guy who is throwing a multiple hour fit over being told to read a webpage
U just explained more of my work. I dont use tutorials so much because ppl here dont have a much of multiplayer expirience. That was my hard way of learning. Documentation, not a lot of answears from forums, aruing with ppl that have more ego than wil to help and trial and error method
Let's move on
I really cant. What i've found to be better is to try and look for examples of how people use something. Lot of the times the comments or the example itself is the "documentation"
Unity docs is one of the bests if not the best docs out there tho
Yeah, it's good, but some features lack examples I agree
@bleak vale π«΄ #π»βcode-beginner message
Could I get help with my problem now? π
Meybe
!mute 915967054421581846 3d Really can't help yourself. You can return when you've settled down.
dwiezaby was muted.
can you screenshot the error
make sure you run the latest build after u saved and all that
What do you want to check about jump input? What is the thing you want to know about it that'd answer "yes" to your statement
wait no sorry jumpinput is a bool
That's weird. Is it because it's using the Input.GetButton("Jump")? I figured that would be a bool, considering it would take extreme precision to press the spacebar halfway lol.
you're right myb i misread the code
No it isnt
You're okay lol. I'm basically trying to say, if the key is pressed for jump, and the player is on the ground, then.
It's defined as a float up top
ahh yes wtf
this threw me off
jumpInput = Input.GetButtonDown("Jump");
so the error was correct
as usual xD
Oh snap, okay. My B. Okay, so just change it to a bool, got it.
xD
I don't know how I had jumpInputReleased set to a bool RIGHT beneath it, and somehow still missed that lol
I'm surprised that other line isn't throwing an error itself
Which one?
jumpInput = Input.GetButtonDown("Jump");
you should be getting a CS0029
Cannot implicitly convert type 'type' to 'type'
How would i go about implementing a static message log which maxes out at like 24 messages? The code part should'nt be the problem, rather the choice of Unity object. Not sure if i should have like 24 pre-positioned gameobject in which i just change the text, or if there is a cleaner way to do that
pretty sure i answered this yesterday no ?
I think so, you told me to use a List, but thats not quite the answer to the question i have
I'm not sure what you mean. The way I read it is, the jumpInput variable is equal to Input.GetButtonDown("Jump")
well now you changed the question
anyway I would use a Vertical layout group
inside a scrollview
well you had it a float so jumpInput = Input.GetButtonDown("Jump");
should've have thrown an error first
before the line 65
since you cant convert bool to float
So, using that same code I had before ( I already updated to bool) it's working now, but for some reason it's missing inputs. I can sit on the ground for like 6-7 button presses (spacebar) and it will only register once.
Oh, I see what you mean.
Vertical layout group. When one of the messages "falls off" move it to the end of the child list with the new text in it, so everything else scoots up to fill the space and the new message appears
Ah, it was because I was on fixed update. Somebody told me that movement should be restricted to FixedUpdate that way framerate doesn't cause issues. Is there a reason why jumping doesn't apply to that?
inputs should be taken in Update.
Rigidbody movements go inside FixedUpdate
That's how I had it before, but for some reason having it there caused missed input. I moved Jump() to update instead, and now it works fine.
yeahbecause you put the bool for jump in FixedUpdate
I'm confused. I have bool jumpInput established at the top, and defined under Update() but the script for the actual if/then under my Jump() method was under FixedUpdate, where it was causing issues.
Well, I thought all problems were solved but using this is causing me to space jump. If I attach //isGrounded = false anywhere in my jump statement, my player begins floating away. What's causing this? https://hastebin.com/share/nimaseroxa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
because you're jumping whenever if (jumpInput == isGrounded)?
That means when you're NOT on the ground and NOT pressing jump, you will jump as well
Well crap, that causes a huge issue.
right now, when i instanciate an object with this script, it has a z value of 51, but i need it at 0. how would i set that? https://hastebin.com/share/weviqozocu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Replace the transform.position part of instantiate with a Vector constructed from it
new Vector3(transform.position.x, transform.position.y, 0);
thx
Is it possible to have an empty modified? As in I have a player character jumping midair after falling off of a ledge because there's no trigger midair to set isGrounded to false. Could I add a // OnCollisionEnter2D(Collision collision) and then make collision.gameObject.CompareTag(//and somehow leave this empty to denote that the player isn't on the ground?)
OnCollisionEnter tells you when you ENTER a collision
OnCollisionEXIT tells you when you EXIT a collision
if you want to know when you are leaving a collision you should use OnCollisionExit
Oh sweet, didn't know that was a thing. Thanks. I'll google that.
remember to use the 2D version if you're doing 2D stuff
There is also OnCollisionStay, but that isn't what you need here. Just an fyi
Hi guys, i need help
How to make unity 2d game have 3d effects(parralax doesnt work on my game)
Parallax will happen when different objects move at different speeds.
normally, perspective does this for you
If you have an orthographic camera (which you usually do for a 2D game), there is no perspective at all
Which 3d effects do you want to include? Parallax is a 3D effect.
so you have to artificially create the parallax
I have 2d platformer type game, the theme is like castle dungeons and i want to make it 3d(when i move my camera i start to see the side of the walls
oh, that's not parallax
Sounds like you want a "2.5d" game. Which is just a 2D game with 3D models and a perspective camera
I have wooden boxes, walls and my cube nemies i want them to be 3d
yeah, you can mix 2D and 3D renderers just fine
Yeah something like that
The answer is to use 3D art models and a perspective camera, that's all
maybe you want something like Paper Mario
that's a mostly-3D world that just has some flat stuff in it
Btw im rly beginer
How? How to make 3d art models
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
And also can all of this be done in 2d project?
There's no difference between 2D and 3D projects.
You don't make art models in Unity., you make them in external tools like Blender.
Maybe it'd be relevant if you were using the new URP 2D renderer?
Oh no... I dont know how to use it and i only got 2 days to do everything
I haven't actually touched that yet, mind you
But yeah, there's generally no difference between 2D and 3D
Making any game in 2 days is going to be hard.
beyond which kind of renderer components you use
I have the game but i want to make it feel 3d
Then you need to either get more time or lower your standards
I have the map, player, boss, enemies, meniu...
That's going to require a lot of learning and effort on your part
I cant...
and redoing all of your art basically
then perish
there's no magic button you can press to turn your 2D art into 3D lol
Maybe that makes it easier
it makes it easier to tell you that you will need to redo all of the art if you want it to be 3D
I made my map using tile map, would it still work?
No. You will need to use 3D models instead of 2d sprite art
hello im having troubles with referencing between scripts, could someone take a look?
Please configure your !ide first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
You have basic syntax errors - seconded you must configure the IDE first
- You are trying to store a
Characterinstance in aGameObjectvariable - If it's public why not just drag it in
- Configure your IDE
Is it possible make a 3d map in unity building it like minecraft?
Please stop asking these questions in here and use the correct channel, this is a channel for beginner coding questions #πβfind-a-channel
Im a beginner
And these are not coding questions but "how do I make a game" spoonfeeding questions
Oh ok
They helped you with providing suggestions but please don't continue pinging them for completely different questions
i can drag a script into another script?
Yes but you still have to make it and since you seem to be averse to creating anything at all you're in trouble
Yes, as long as it's public or serialized
Ok i think ik the solution but idk if it exists in unity. Is it possible to add z axis and y axis grid to my game? And then i can paint it like tile map?
Also z axis and x axis bc i need roof and floor
There is no built in 3D tile map. You would need to make one
!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.
objects like closet doors and doors
@unique relic #π»βunity-talk message
its just small example
π 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.
UnityEngine.Tilemap is 3D I think.
||Damn slow bot making my sarcasm not work||
yeah kinda ruined it
but idk if it has proper support for 3D renderring and collider generation
Tilemap itself stores everything with Vector3Int
The tiles themselves are sprites. It has layers, which the Z axis uses
but it doesn't deal in Voxels
Tilemap as a component is mostly just a container
you need TilemapCollider2D and TilemapRenderer to actually use it. I do not think Unity has equivalent 3D tools
to use tilemap like minecraft. But maybe someone made an asset or package etc for that
digiholic is probably right, tbh
Hey y'all. So im making a match 3 type game.
I was wondering does anyone know how i could add boosters?
Eg. Color bomb booster (auto generates on the board at a random position when selected and player can use it to destroy desired color they chose)
Hammer booster (allows the player to destroy a selected block without using a move)
Arrow booster (auto generates in a random position on the board and removes a whole row or column when used)
These boosters will be purchased using in game currency or given to the player at random times like after completing an event or something like that
that is a very broad question
your blocks should be represented as a base class from which specific types of blocks derive
This is a lot of question. Which specific part did you need, and what do you already have
π my bad i didnt know how to make the explanation simpler.
So, I've been trying to google this but can't seem to find exactly what I'm looking for. I'm making a Hollow Knight clone demo, and I've got the movement down pretty good, but now it's time for the more advanced movement options like dashing, double jumping and wall jumping. The problem is while I can find the code for making the actions themselves, I don't want them to be something you can do right away, and want to impliment them as object upgrades you can pick up later down the line. Would anybody be able to point me in the right direction for finding something like that?
Wrap the movement of those actions in a bool check that IsDoubleJumpUnlocked
Set it to true when they unlock it, done.
Thank you
I have to board setup.
So i can adjust the layout of the board. The amount of different dots/candies. The amount of obstacles like blank spaces, comcrete tiles, slime tiles etc.
I can create different bombs when a certain number of the same dot is matched.
I can set score goals to tell the player what they need to collect to win the level.
I basically have a working game. I just have no idea how to add those boosters.
There is a tutorial on Godot to add boosters in a candy crush clone game. But it uses GDscript so i dont know how to change it to c#. Because that stuff looks complicated lol.
Also my levels are scriptable objects.
Not sure if any of this helps
Sorry for spelling errors im on my phone and seem to be misspelling things alot today
just GetButtonDown works for me
"Adding boosters" is still a vague and undefined question. Break it down into smaller sub-tasks. Find one small part of the thing then implement that
for things like collisions, is it more sensible to do using layers or interfaces? Like if i want my bullets to collide with enemies, walls and doors, but not my player, my bullets, enemy bullets etc.
Use the physics layer matrix to do general ignoring of collisions
See i know that i will need a button that will apply that booster to the specific level the player is on. If they exit the level then the booster is lost.
Also if they purchase a booster then it will have to apply to that booster button that they now have another booster to use.
Its just the fact of how to actually implement the booster on the board once the player clicks on that booster button.
You keep adding to the list of things you need to do, which is what's making your question too big. IF you know you need x, y and z, start with one of those an work on it.
If your main issue is how to get boosters to appear on the board, then don't worry about how they get the booster, just start with a "press Space bar and a booster appears on the board". Figure out that logic first before handling the player actually owning the boosters.
how to add text on a gameobj
TextMeshPro
doesn't work
Yes it does
well why am i not seeing the text on my game object
Presumably because you have no idea what you're doing, not that it's broken.
Right click, 3d object, text mesh pro
This isn't a coding question.
How to make parralax?
Make sure you're using the right version of TMPro as well.
its not on the gameobject,
its int own object
you need to move it around into position
ty
Move the background slower (or faster) than the foreground
hi, what's the difference between checking for an object like this
if (object)
vs
if (object != null)
how can i reset scroll rect to the top?
nothing
they both check if the object is set
both accomplish the same?
okay thanks
yeah then if you want something to happen if its false
you would do...
so 1 will be top?
if (!object)?
yup
if (object)
{
//Code
} else
{
//Code
}
yeah works thanks
oh, so use else instead, got it
yeah its easier since you dont want a bunch of if statments for the same code
just use else, or else if ()
Or it can be nice to do
if (object)
{
//code
return;
}
//other code
It depends on the situation, but simply returning can make things a little cleaner in some cases
that would stop other code from runing
after its true
Yes. That was kinda the point
"Depends on the situation" "in some cases"
one more thing, im reading the docs and im not sure, to disable the movement, would i just do scrollRect.enabled = false?
or do they have like a specific thing for that
cause scrollRect.StopMovement() just stops it
but doesnt disable it
Yes you can just disable the component
alright thanks
Why don't AI open doors? There are sounds, but no animation.
If the sound plays, then it is the way the animation is set up
#πβanimation
If I open the doors myself, then there is animation.
ffs @echo badger .. delete that huge block of code, you've just been told about this
!code
because of this
if (inReach && Input.GetButtonDown("Interact"))
it will only be true for 1 frame
π 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.
The animation is ok
Thank you
Hey guys, how can I fix this issue? I wanted to add a sprint functionality for my game, which replaces the movementSpeed variable with a sprintMovementSpeed variable. I set sprint movement speed to 10% more of movementSpeed, but I can't put it in update (it'll keep increasing to infinity) or start (it gives out some error). Thanks in advance π
hi everyone i have try to test a thing for check if a value are on my list the problem is my condition be executed but i dont have the value in my list this is my list:
public List<int> boutonListe = new List<int> {2, 3, 5, 9};
and this is my condition:
{
if(boutonController.boutonListe.Contains(1))
{
rend.color = Color;
}
}```
Have a variable for normal movement speed, sprint movement speed, and current movementspeed. Use current to actually move, and set it to either normal or sprint as you change
Sorry, but what is the problem?
The list doesn't contain it, so the color change won't happen.
That is exactly how you wrote it
Ohhh, I see, it IS changing
No you're fine. Maybe put a Debug.Log inside the condition
Debug.Log(boutonListe) to know what it currently has at that second
i gonna try that ty
Thanks for the help π
However, it still gives out the error:
You can't set a variable to another variable outside of a function
Use Awake
got it, so should I create a set function for these two variables?
I'll try that, I just don't know exactly what it does
but don't explain it i'll google it π
hey everyone ! i have this code thaths whenever my player gets under a sprite renderer(i.e a tree) the tree lowers his alpha color over the course of "fade time" to be transparent so the player is visible under it , howhever the tree wont go transparent at all ! how come ? help would be much appriciated
System.Collections.Generic.List`1[System.Int32] wtf... that want say i only have the value 1 in my list???
so this or awake? which one is better?
Even if you create a set function, you still have to call it somewhere
Awake is called when the script.. awakens (for the first time, once per instance)
oh, that makes sense. i'll use awake π
thanks for the help guys!
Sorry, maybe you have to do boutonList.ToString()
Hopefully you don't have to iterate it.
Other choice is to just put a breakpoint at the line where you change the color and check the values using the debugger.
Worth it to look up how that works
So I put this in Awake(), but I can't make them public otherwise it gives out a ton of errors. And I can't use them unless they're public. What should I do? I feel like I'm overcomplicating things....
wait i have try debuglog the count of my list and put 3 value in my list and he say me 4 wtf
You're creating new variables in Awake there
Don't make new variables, set the ones you already have
I believe a C# course might be needed, but just declare them outside of awake and set the value inside
Try making the list private.
Maybe something is being added to the list?
Ok! I'm coming from java/python but haven't coded in a while so you're prob right. I'm currently making this game for a game jam, but I'm planning on taking the junior programmer course on learn.unity.com, would you recommend it?
anyone?
public class Foo
{
//declare the variable here
public float thing;
public void Awake()
{
//set the value here
thing = 5;
}
}
but if she is private i cant use it on my other script no?
Yup thanks that's what I did π
Anything on learn.unity.com is good, but a plain C# course is also recommended
You can make a public method that the other class calls. Then you can control how it is modified
And you can put a debug there so you know every time it IS modified
Are you sure the coroutine is even running? Try adding debug logs
See what is happening and when
Any specific recommendations?
so that work in private but i not understand how i can get the value if this is private :(
Actually, the more programming I do the less public fields I use - from my experience it's better to just keep most things private and if you really want to expose something to other classes then either a method or property is good. It's easier to control what's actually happening to that field
Well, you can make it a property too
public List<int> boutonListe {get; private set;}
Then you have public READ access, but only private write access
my brain gonna explode wait
welli added a debug log but it seems to always print
Not really a coding question. Ask here
#π»βunity-talk
And also say what the proboem is
Did you log the actual values though?
so there is a problen in the while loop i guess ?
Hi dont know if this is right channel to ask but would be appreciated if anyone know why this happens. made a model in blender rigged it with mixamo. Downloaded rig with idle animation made it to humanoid put it in scene. Downloaded another walking animation. When transitioning from idle to walking everything looks weird. But when i change the avatar to the walking avatar it works but then the idle animation looks weird / crooked
ok ty
oh ok, I'm going to ask there, thanks
yes i want it to go from 1 to 0.8 which is the targetTransparency but it print alwyas 0.99....
Ohhhh, you are using startValue in the movetowards.
You need to use the current value
please explain ?
You move it a tiny bit from start value, cache that in newValue, then move it FROM the start value again
It doesn't ever go anywhere, because you never update the start point
float newValue = MoveTowards(1, 2, .1);
This will return 1.1 over and over
float currentValue = 1;
currentValue = MoveTowards(currentValue, 2, .1);
This will return 1.1, 1.2, 1.3, 1.4
really ? but the a value gets incrimented by the t value
The newValue does
But you don't USE that in MoveTowards
So yes, it increments by t every time, but the increment starts from the same place each time
Just look at the docs
https://docs.unity3d.com/ScriptReference/Mathf.MoveTowards.html
π
newAlpha should be your first parameter of MoveTowards
i have a prefab item that is tying to instantiate a button ontop of itself, it gives that button aces to 2 scripts but for some reason the button is only getting the invitem script and not the inventory script. im not sure what could be the problem. also the prefab that trying to summon the button does have a refrence to the 2 scripts its trying to give to the button.
is it possible for an event to return a value?
Yes
google: how to return a value with event unity
First, are you talking a Unity event or c# event?
works ! ty man u blew my mind lol
much appriciated
I have a script named Dropdown.cs and it obviously has its associated .meta file. I'm trying to rename the script to DropDown.cs, but whenever I do that, Unity gives me a warning about the .meta file having inconsistent casing, and lets me know it has reverted the name back to the "correct" name, which is not what I want. I know that I can't rename meta files, so how can I rename this script?
How are you renaming the file
And you probably shouldn't use either of those names
Yeah I know I shouldn't be using those names, but I'm just renaming it within the Unity Project window
Renaming the file in unity should rename the meta file as well
Nah
Asset file 'Assets/Scripts/DropDown.cs.meta' and meta file 'Assets/Scripts/Dropdown.cs.meta' has inconsistent casing.
Renaming meta file succeeded.
And if you know both names are bad, why are you still using them
Well yes because you haven't actually renamed the file
I'm not planning on actually using these names I'm just curious why it's happening
Windows file system is case insensitive
So how can I rename the file to DropDown if I wanted to
According to windows, you did not rename the file at all
if you actually change the name, then it will work
Oh of course, thank you!
error CS2001: Source file 'C:\Users\s9316622\Documents\GitHub\CipherDecoderApp\Assets/Scripts/DropDown.cs' could not be found.
You should give it an actually descriptive name that matches what it does
@polar acorn as I said ^^
The answer is: According to windows, those two names are the same. Unity and C# care about the capitalization, but windows does not. As long as you are renaming something in a way that is just capitalization, it's not going to work, so you should give it a real name
Cool. Do you know why I am getting this error?
I renamed the file to DropdownMenu
Did you rename it in windows or unity?
Unity
I dont know if this is a weird one: I want to make a fancy "Mover" and show the start and end position in the editor when the object is selected and update accordingly. The Problem is: The End Position right now is on the World Origin, even when i do something like:
endPosition = startPosition + someVector
Question: Where do i put these? Hope you get it, my english isnt the best.
PS: I know how to do it. Vector.MoveTowards with a step Variable, so thats not the problem. Just where to update this Gizmos and dont get confused with the "normal" code. thx in advance
Did you rename it to the same as the meta file before changing it to DropdownMenu?
Every time I rename the script it automatically renames it back to the same as the meta file anyhow, so yes
Your code does not set the endposition at all
Huh... are you in play mode? That should not happen
Nope, not in play mode. Let me start Unity.
its public i set it in the inspector and the plan was to add it to the cubes position.
Weird. Not sure then, sorry
but where do i put the line?
in update and it only works ingame, in the gizmo selected and it only works when i select the cube.
im confused
What will be setting your endposition? the mouse, some pre-set value?
if you set it in inspector you dont need to change it at all in code, just change the inspector
No worries, restarting Unity seemed to magically fix everything... oh the wonders
red cross where it should be, cube where it is. changed the inspector value to Vector3(0, 2.5, 0).
Quick question for someone new to Unity, how did you serialize endPosition without using [SerializedField]?
So you dont want "EndPosition" but "PositionDifference"? π
They're using public
public isnt right? saw the serializedfield stuff above the attributes π
Oh, I forgot you could do that. So what's the point of making a serializable field if public does that anyway?
good question thx
So you can keep things private but also expose them to the editor.
yeah looks so simple, but i dont get it.
What you can do, create a public Vector3 positionDifference, then in the Start() add the difference to the start position to calculate the end position
To var or not to var?
I used to do specific Types everywhere but I pretty much exclusively var nowadays.
A company I applied to mentioned how they specifically Type everything to 'prevent' bugs but that didn't make much sense to me. what do you guys think?
not that it matters, just looking for opinions haha
Functionally it doesn't matter
var everywhere is ok unless you NEED that readability, but modern editors still display the type anyways π
For readability, it obviously makes it more clear if you include the Type
Why my pause broke?
my ranged enemy bullets pass through my player.
public class EnemyAIRanged : EnemyAIMelee
{
public Enemy_Projectile projectilePrefab;
public float ProjectileSpeed;
public Transform projectileSpawnPoint;
public Sprite ProjectileSprite;
public float stopDistance;
protected override void MoveTowardsPlayer()
{
float distanceToPlayer = Vector2.Distance(transform.position, playerTransform.position);
if (distanceToPlayer > stopDistance)
{
transform.position = Vector2.MoveTowards(transform.position, playerTransform.position, Speed * Time.deltaTime);
}
}
private bool IsPlayerInRange()
{
return Vector2.Distance(transform.position, playerTransform.position) <= Range;
}
protected override void Attack()
{
if (Time.time < lastAttackTime + AttackCooldown)return;
if (IsPlayerInRange()) Shoot();
lastAttackTime = Time.time;
}
private void Shoot()
{
Enemy_Projectile newProjectile = Instantiate(projectilePrefab, projectileSpawnPoint.position, Quaternion.identity);
Vector3 targetPos = playerTransform.position;
targetPos.z = 0f;
Vector3 shootingDirection = (targetPos - transform.position).normalized;
newProjectile.SetProperties(Damage, ProjectileSpeed, shootingDirection, ProjectileSprite);
newProjectile.SetLayer(9);
float projectileAngle = Mathf.Atan2(shootingDirection.y, shootingDirection.x) * Mathf.Rad2Deg;
newProjectile.transform.rotation = Quaternion.Euler(0, 0, projectileAngle);
}
}
will try that. thx
Your IDE is auto completing for you, so you're not saving time by typing var instead of the type, really. If one allows for more readability, why not just use it?
I shouldnt be able to move when its pause and the pause meniu open when i press play
It should only open when pressing esc
I'd argue that often I find var code more readable than Typed code due to it's conciceness. It's when you need to actually figure out the typing from just a github repo or something that var becomes suckier imho
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_Projectile : Projectile
{
protected override void OnTriggerEnter2D(Collider2D hitInfo)
{
if (hitInfo.gameObject.CompareTag("Player"))
{
Debug.Log("Hit Player");
IDamage damageable = hitInfo.GetComponent<IDamage>();
if (damageable != null)
{
Debug.Log("Applying Damage");
damageable.takeDamage(Damage);
}
else
{
Debug.Log("IDamage component not found on Player");
}
Destroy(gameObject);
}
}
void Update()
{
Debug.Log(transform.position);
}
}
ranged enemy bullets pass through player and do not damage him
Not auto completing but it shows them like this: https://img.sidia.net/ZEyI5/keXiGUru53.png/raw
I'd also say that it kind of makes you think about proper variable names more unconsciously, as the Type doesn't help you identify the object.
Pls help me, it worked 5 minites ago and i cant see anything wrong with the code
!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.
I posted the image of code
works π
Yes that's why I sent !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.
Oh i cant acces discord trough my pc rn(dont ask why) ik there is internet version
then best of luck solving your own problem
Anybody see why my enemy projectiles pass through my player without damaging him?
Whats different if i send ss of my code trough pc?
Nothing, I would still send the link to tell you to post it properly
Maybe your bullets dont have collider
- Are either of the colliders set to triggers
- If this is 2D, are they at the same Z position
- Are you moving them via teleportation of the transform instead of using physics
So, the bullet is a trigger, meaning it does not physically collide with anything. It's not going to stop when it hits a collider
There's no On trigger anything in this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_Projectile : Projectile
{
protected override void OnTriggerEnter2D(Collider2D hitInfo)
{
if (hitInfo.gameObject.CompareTag("Player"))
{
Debug.Log("Hit Player");
IDamage damageable = hitInfo.GetComponent<IDamage>();
if (damageable != null)
{
Debug.Log("Applying Damage");
damageable.takeDamage(Damage);
}
else
{
Debug.Log("IDamage component not found on Player");
}
Destroy(gameObject);
}
}
void Update()
{
Debug.Log(transform.position);
}
}
sorry that's the one i meant
Pls someone help with that
ontriggerenter2d on my projectile. And i'm basically using the same logic on my player and his bullets are working
Trigger colliders do not use (as much) prediction compared to regular ones, as such projectiles can pass through without reporting if they're fast enough
Then it would seem that this object never collides with anything tagged Player. The tag seems to be there, but are they at the same Z position in game? You've shown screenshots of what seem to be prefabs, are they maybe being spawned in at the wrong depth?
that's a debug log of the transform of the bullets next to my player inspector and they are on the same z coord
Hm, then it seems like SPR2 might be onto something, it might be moving so fast it's passing through?
I'm gonna rewrite the enemy projectile with a different collison detection
and test it
that broke my game in interesting ways lol
would this apply if he put it into continuous detection mode?
No
then that is probably a good start. takes literally no effort to test
Non-triggers collision messages are reported from the Rigidbody, that's probably not the case for triggers
iβve never fully understood how the message broadcasting works
lol now my enemy bullets hit me, but my bullets no longer hit them. IDK what i did.
Can someone help me with my animations when I my character walks it keeps glitching back and forth and then the animation will randomly stop
this is code related channel
you need to show the code for the animator
Hey guys i have a question. I have a script which allows the player to "recollect" objects when you collide with them, it makes a sound and gives you +1 score. How can i make it so it also grants you, lets say an ability? like jumping.
ok thank you \
how do i fix this. i know why it doesnt work, but how do i get a bool value thats specified on a different script from an object?
Like that
Assuming RangedEnemy has a bool called BowShoot
You never assign enemy
but unity doesnt let me, it gives me this error
Generally you want to serialize the field, assign it in the inspector, and then use that reference in code https://unity.huh.how/references/serializing-component-references
also i think you got the structure wrong, shouldn't BowEnemy inherit from RangedEnemy? why are they separated classes?
does this error have to do something with my code, it says i do but my code shows that it is right
if its UnityEditor namespace not likely, check the full error stack.
you can then use virtual functions for Attack for example and override it for specific behaviour for bow, crossbow etc
all the errors are the same thing
i know its not null ref
but check how to read the error, you can expand the error and see where its coming from
i serialize field the first one and now i get an error from a different, completely unrelated script giving me this and im turbo confused
could have been there before your previous problem
seems pretty straightforward - ArrowTracker.instance is null
is trigger calling somehow before instance its assigned? are you assigning in awake or start ?
Get used to seeing NullReferenceException. It's both the most common error you will see and the easiest to diagnose / fix
im just turbo lost, i accidentally assigned the player arrow to the enemy bow and the player ammo is tied to ammo count
you need to just breathe, relax, and slowly tackle one issue at a time
I assure you, you are dealing with trivial errors that are simple to fix when you look at them systematically and calmly
Where do you assign enemy
i serializefield it and now it works
Hey, guys! How to load my volume slider text when saving it and when loading the options scene?
Do i have to use OnSceneLoaded method maybe?
I'd just use OnEnable/OnDisable on the menu
I mean i click save button and I change my volume slider value to 0 but when I load back my menu scene and then loading again settings scene this value is 1 and not 0
I hear no sound and and I have programmed it correctly only the text is not updated after the scene load
Top 10 most difficult concepts in unity programming: 1. Generics
2. Interface
3. Encapsulation
4. Interface
5. Delegates
6. Lambda
7. polymorphism
8. inheritance
9. Singleton
10. Struct
There are really only two hard problems in programming at all. Cache invalidation, naming things, and off-by-one errors
if chatgpt is good for one thing it's giving me some great alternative class names
Yeah, coming up with words is what it's designed for
oh u
That is unironically one of the good things to use it for
I used it to make names for characters in my book. I am terrible at that. Usually just write a book with [Character1] as a placeholder for too long haha
Just make what you name a bit longer
π
right now, my script makes the enemy go between two points and be idle for a while. now i want to change it up so that the enemy always stays at the point closest to the player. i am not quite sure how to achive it. i guess compaing the difference between enemy. pos.x and the player, both points and the player and then let the enemy go to the one with the smallest difference, however idk how to approach that
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey guys, I only have this IF here to check if I can spawn the boss. 100% of the time I play it.. it works.. sometimes when some friends play it, they spawn the boss at level 28..30.. 32.. and that should not happen.. how can i debugg this ? with me always works and I always spawn him at lvl 50 or 15m game. cs if (_player.playerLevel >= 50 && _canSpawnLastBO || Time.time >= 900 && _canSpawnLastBO)
they spawn the boss at level 28..30.. 32..
Technically it's possible, if they've been playing for more than 900 seconds
Also the condition can be simplified down to if (_canSpawnLastBO && (_player.playerLevel >= 50 || Time.time >= 900))
Do note that if your user hangs around in the main menu for 14 minutes, then plays, then the boss will spawn after 1 minute!
Hey, I am trying to create a GUI with images however, even after i have assigned the image in the inspector, im still getting the error
Ah yes, The Errorβ’οΈ
Are you sure you didn't attach this script to something else by accident? Tip, you can do Debug.Log("stuff", gameObject); and upon selecting the log in the console, it will highlight the object that sent it in the Hierarchy
Either image1 or image2 is null. They're the same error text so I'm not sure which one. The stack trace should tell you though
its only attach only one
Good. Change the log messages so you know which of the two the code sees as not assigned
its says only image 1 but i have assigned it
Now post the one that's attached to an object in the scene - as the message suggests, these will only be applied in Edit Mode
yooooo
basically i installed a 2d dating sim so that i can rebel against the greedy devs and hack it for unlimited diamonds but its all encrypted
plz helpe
- That's not encrypted, that's binary.
- Cracking is not something we discuss about here
hackur
but its fun
Go have fun somewhere else, this is not the place
fine, ig when i decide to make my own game ill come back
I have a character controller that gets moved with a velocity value every tick but for some reason it likes to stick on ceilings
// Hit Ceiling
if (hit.normal.y < 0f) {
playerVelocity.y = -1f;
Debug.Log("Hit Ciel " + hit.normal);
return;
}```
like it works if I'm not moving horizontally it seems but if I have a tiny bit of horizontal movement you like stick to the ceiling and float down slowly for a second before unsticking and falling at normal speed
- That's just a binary file
- What does this have to do with unity
wait so it wont appear after i build it
Even when you enter Play Mode while still in the editor
hey guys, is there anyway to make a vector3 or a quaternion using floats or doubles ?
Yes, new
I'm assuming you're getting the log? Is there anything else in the function after the if statement?
how ?
a lot of complex code but yes it outputs the log so multiple times so it seems the sticking is happening there
Is that other "complex code" stuff that you're expecting to run if you hit the ceiling? Your return statement means the rest of the function is skipped
yes im intending to skip the rest of the code if it hits the cieling
ok i found a fix from visual studio help, i just had to type (float) before the numbers.
thanks
actually I thikn I fixed it because I think I know what's happening
Do you have anything else that might be setting playerVelocity.y to 0 before your next Move call?
the character controller isn't perfect and it collides multiple times when you hit the ceiling while moving
no they were playing for 5minutes level 28 and that happened..
and the vent is asynchronous probably
so I think it's setting the velocity to -1 more than once, which means it falls slowly, and it collides multiple times because it must be like intersecting the wall or something idk
but regardless making it so it sets it to the minimum of playervel.y and -1 works
im assuming it's because the collider somehow is touching the ceiling, then moves down a bit, and then touches the ceiling again
or that collision event can be called multiple times between each update
Can't verify that myself. Does it display the time somewhere as they play it?
If not, what you can do is make a "debug text" with a UI TextMeshPro text, and display all three values of _canSpawnLastSO, playerLevel, and Time.time, as well as the result of the if statement.
Then build and ship your game to your friend, and have them note the values when the boss spawns
yes it display the time.. prob is how can I debugged it.. if that never happens to me only with them and not always
I thought about it.. will do thank you
I'm kinda lost. Whats the proper way to reference a Handler class creating and destroying objects? Do i create a empty gameobject, add the script,- and lookup the gameobject + attached script every time i need something executed in the handler?
I'm trying to execute the functions from different classes attached to gameobjects
redoing some code to allow for remaping keys and im trying to use the input system to run a function with an input when a key is pressed and i cant figure out how to do it i wrote some code that i think should work but it dosent. its giving me Delegate 'Action<InputAction.CallbackContext>' does not take 0 arguments
performed is expecting the function you give it to have parameters, but yours has none
The delegate Action<InputAction.CallbackContext> will only accept methods or functions that have the following signature:
void Method(InputAction.CallbackContext);
Or in other words, a method or function that returns void and takes one argument of type InputAction.CallbackContext
The lambda function you've given here takes no argument! It's not compatible.
Guys silly question, I have an NPC with a capsule collider 2d only and a sprite in a custom layer, I created a raycast for my player that is in the same layer. It debugs the gameobject hitted but its not hitting on my npc. Any idea?
so what did it hit ?
I'm hitting myself lmao
dont tell me that is because its inside the player
haha. use layers as filter
already created a custom layer for interactible objects, both npc and raycas are in that layer but no magic happening 
you have to exlude player from that layer of ray
it seems like it is just happening when I build the game and play it.. tested my self and boss appeared at 10m in lvl 42.. but when I play in unity it doesnt happen
any ideas?
Debug text will help
acksually, the raycast is a child object from my player, my player is in the default layer
then you need to put Player in its own layer and exclude from the raycast
thanks 
π
hello, how do you get the direction of an object and turn it into a vector ?
(I'd like to make it move with charactherController.Move() function)
how are you moving the other object?
gameObject.transform.forward
just transform.forward
it can be either
you can just do (currentpost-lastpos).normalized also
I only have 1 enemy object moving with its default direction in the scene (2D game btw)
thanks for the answers π
transform.forward dont work for 2D
depending on ur sprites direction the equivalent would be transform.right or transform.up
I am using 3D objects not sprites so transform.forward does actually work ^^
hello I need some help with this script for my class project. The class is for Audio and I know literally nothing about coding nor do I want to know but I wanted something simple to make my lights flicker in the project and just found something online. Someone was helping me last night and said I just need to add a Class to fix my error but I forgot to mention I have 0 experience and need to be babied through the whole process so unfortunately I've made no progress and I feel very stupid having to ask the same question again. here is the script and error:
The first thing you need to do is properly configure !vs so you get autocomplete and error highlighting
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
Then, you need to re-create your script, because you've removed the fundamental body of the class, and it would be easier to just recreate it
Now I remembered I have the level, the time already in the screen all the time.. and its always correct. and there shows I am on lvl 38 for instance, 10m int o the game and the boss appears.. the only one I dont have yet is the bool
maybe it's more trouble than it's worth
Having a configured code editor is required to get help here, see #854851968446365696
Okay, so something is triggering the spawn that's not the if statement. Or the if statement doesn't work the way you think it does.
Currently, the condition will pass if _canSpawnLastBO is true, AND (either playerLevel is greater or eq. to 50 *OR * Time.time is greater or eq. to 900)
I PROMISE you, it is not. Once you see what it can do for you, you'll kick yourself for waiting so long
It is a game changer
It takes 5 to 10 minutes and is SOOOOO easy
yeah but this is not something I want to learn I just wanted to add a small detail to this school project. It's not needed I just wanted to be extra, it's an audio design class
no one will do the project for you
you could already learn unity very basics instad of asking 2 days the same question
the only place that contains the instantiate method is inside that if. and yes that is the condition I want, and it works for me playing in unity, but not when its built and played outside, and its random, sometimes it occurs when I am level 27...32...45..
I know unity basics not coding basics
no you dont
Kinda irrelevant. Knowing how to troubleshoot and fix things will help in anything. I have two degrees in audio, and it uses a lot of computer skills a lot of the time. Doing this will help with that
If the 4 steps are too hard, audio will be too hard too. Push yourself
Either way though, it is required in order to get help here π€·ββοΈ
Show the code that updates all that UI
public void UpdateLevel(){
levelText.text = "Level: <color=yellow>" + _player.playerLevel + "</color>";
levelUpScreen.SetActive(true);
RandomSkills();
_player.canShoot = false;
fillEXP.fillAmount = _player.playerExperience / _player.playerExpNextLevel;
Time.timeScale = 0;
}``` Here when I level up is one method I use to update it. for the time it is this one: ```cs
private void UpdateUITimer(){
int minutes = Mathf.FloorToInt(currentTime / 60);
int seconds = Mathf.FloorToInt(currentTime % 60);
countdownText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}```
Time scale set to zero, intentional?
yes, when I level up appears in the screen some stuff to choose, so I stop the time to give time to the player to choose
when player chose it time is 1 again
in update method: cs currentTime += Time.deltaTime;
this is inside my UIManager that is an object that is always on the hierarchy since start
You might want to use that everywhere instead of using Time.time as a quick reference. These might differ with time scale, but as long as you don't spend 3 minutes between each level it should be alright to keep as is
I don't see any issues, can you post the code that triggers the boss spawn?
The whole class
yes sure, thank you for your time. I can try to maybe try something. Thinking now. I normally get to level 47 sometimes 50 when is close or at 15m.. so I can remove the time check as its the same as I am already almost 50 close to 15m.. and if the bug stops. that was the thing..
its like 700 lines
π 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.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
How can my object hitted by raycast know it? I want to launch a function every time a raycast hits him or leaves him
Have the code that runs the raycast call a function on it
will it crash if that function doesnt exist?
If the function doesn't exist, it wouldn't even compile
I mean, If I have 2 different elements able to be raycasted. Let's say an NPC and an item, do I check what kind of object did I hit to get the script from that kind of object or theres a more generic way?
You would have your raycast get the components from the object and if they exist, call the function in it
thanks both!!
what If I want my object to know when the raycast stopped hitting him
Then the object doing the raycasting would need to keep track of the last thing it hit, and when the raycast hits something else (including hitting nothing), call that function
But won't it use lots of resources? If I have hundreds of items expecting to be hitted and my script calls a function to tell them they are not being hitten every frame the raycast hits nothing
You don't call the function every time the raycast hits nothing
oh I see
you call it whenever it goes from hitting this thing to hitting something else
thanks digiholic
Also, I remember you helping me for dozens of times literally like 2 years ago
Thanks for everything
master
im spawning 2 prefabs using this script and then trying to make the button prefab a child of the first prefab but when i run the code they both spawn in but the button is not a child of the item
im not sure whats wrogn with my code
Why do you set the parent of buttons to one thing then immediately something else
How do I access a bool variable saved to a script which is attached to a game object, from another game object using GetComponent?
I tried this:
{
public GameObject ObjectWithScript;
...
if(ObjectWithScript.GetComponent<MyScript>(boolVariable))
{
//Code
}```
Why is your variable of type GameObject if you want a MyScript
Can GetComponent be used not just on GameObjects?
You can use GetComponent on GameObjects or anything that extends MonoBehaviour, but also you don't need to GetComponent at all
But preferably what digi said
i need to access the bool from a script, but I couldn't find a variable type for scripts
Because you made the type
It's whatever you called it
iecs public MyScript myScript;//Exposed to the inspector ... if(myScript.boolVariable) ...
The object you drag in from the inspector will need to have the appropriate component script attached to it.
And it should be something from the hierarchy-scene unless you're really wanting to evaluate/modify prefabs.
here, is MyScript the name of the class?
does that mean I have to use the same class for the script I wanna access too?
If you want to access a class you need to use the class you want to access
Each component on an object in the scene refers to an instance of the script.
The script that you originally wrote can be thought of as a template or blueprint for many other objects to own their own instance of.
You should not be creating multiple identical scripts with different names
You can always call get component for less popular components on the same reference.
alright, thank you very much!
Reference the most useful component to avoid having to call excessive get-component calls.
https://i.imgur.com/zVTjELH.png
cmon c# let me crash my program if I want
Every component would have the gameObject and transform properties, so you shouldn't be referencing those unless the reference solely only uses either of the two components only.
Thanks for the tips and help π
It's against the rules
holy fuck I've done it. After configuring I tried a few things that didn't work, tried one last time before giving up, simplest solution worked ahhhhhhh thank you to all those that helped me I appreciate it so very much
What is a GameObeject
Configure your !ide so you can't make basic spelling errors
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
It's a step by step guide
If you're finding it difficult, ask a question
Consider it the tutorial boss. It's significantly harder to try to code blind than it is to follow some steps to configure an IDE
It is, quite frankly, pointless to attempt to code without it
I don't understand what part of that could possibly be confusing at all
Well good thing we don't need to speculate, if someone's confused they can elaborate and get an answer
they refused to elaborate when they were having trouble with it yesterday so i doubt they will today
well, if it continues it'll be a mute, so feel free to @ me if it's still unconfigured next time
One thing I really hate with step by step guides is that it points to something in the UI and I have no idea where it is.
Sorry, I was hoping it would prompt them to expound so I could explain
I have a function that pauses my game by changing Time.timeScale = 0, then is suppsed to open my pause menu. but my pause menu wont open if the game is paused.
public void WinGame()
{
StartCoroutine(HandleWin());
}
public void LoseGame()
{
StartCoroutine(HandleLoss());
}
IEnumerator HandleWin()
{
//PauseGame();
WinPanel.SetActive(true);
yield return new WaitForSeconds(2);
WinPanel.SetActive(false);
OpenPauseMenu();
}
IEnumerator HandleLoss()
{
//PauseGame();
LosePanel.SetActive(true);
yield return new WaitForSeconds(2); // Wait for 2 seconds
LosePanel.SetActive(false);
OpenPauseMenu();
}
private void PauseGame()
{
Time.timeScale = 0; // Pauses the game
}
private void OpenPauseMenu()
{
PauseMenu.SetActive(true);
}```
If the timescale is zero then your WaitForSeconds will never finish
the pause games are commented out that's how i know everything is working as it should if i dont pause the game
ohhhh, should i do waitforrealseconds?
I think you'd want to use unscaled time I believe
The real solution is "don't use timescale to pause" but that works for this specific problem
Visual studio is the ide, so that question doesn't make much senseπ€
You don't have to. VS 2019 should work.
why doesnt it work
π 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Init : MonoBehaviour
{
// Start is called before the first frame update
async void Start()
{
await UnityServices.InitializedAsync();
if (UnityServies.State == ServicesInitializationState.Initialized)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
if (AuthenticationService.Instance.IsSignedIn)
{
string username = PlayerPrefs.GetString(key:"Username");
if (username == "")
{
username = "Player";
PlayerPrefs.SetString("Username", username);
}
SceneManager.LoadSceneAsync("MainMenu");
}
}
}
// Update is called once per frame
void Update()
{
}
}
would i just pick the first option
Check the docs for the required namespaces and packages:
https://docs.unity.com/ugs/manual/overview/manual/services-core-api
i dont understand
Which part exactly?
If you don't know what namespaces and packages are, you might need to go back to learning the basics.
You would pick the option that applies to you
Try looking for an up to date tutorial. Assuming that the tutorial is outdated.
Otherwise hire a programmer or learn it yourself.
do you see errors underlined in your code now?
Do you see errors underlined in your code now?
wdym it "went black"? your high contrast setting is doing that
and it was like that in your screenshots yesterday
The VS window is super tiny, so it's hard to say, but it seems like it's not configured.
i have a background picture i want to move with the cameras x achsis, but stay in y,z .
i wrote a simple script which has
public Camera cam;
as a parameter and in the void update sections its
gameObject.transform.position = new Vector3 (cam.transform.position.x, gameObject.trans.pos.y, gameObject.trans.pos.z);
and the background image is following the camera, but its not exactly on the same position on the same frame and its also very jittery.
what would be the proper way to do that?
Put that in LateUpdate instead
alternatively, just use a PositionConstraint
have you removed the other component you had controlling its position? and are you certain it isn't actually the camera's movement that is jittery?
yes, the script is removed and the cam is buttersmooth, however i am using cinemachine and pixelperfect camera which might be the cause of this
can someone help me why it's didn't show the content of the string...?
also this error, (i'm using 2d mobile project)
Did you ever remove the value in the inspector?
Try setting the variable to private, compile, then set to public and compile again
yes its worked, thanks
The inspector "wins" over the initializer in code if it is ever changed. If you want to make sure that doesn't happen, you can assign the value in Awake or Start.
public class ParticleTray : ScriptableObject
{
public struct PTEntry
{
public string Name;
public Particle Particle;
public PTEntry(string name, Particle particle)
{
Name = name; Particle = particle;
}
}
public List<PTEntry> particles = new();
}```
how do i make this list display in the inspector?
gotcha thank you
serialize the struct
system.serializable
TY so much
i disabled/temporary makes it as comment but the button still direct me to scene 1, it's doesn't show where the error was when i didn't input anything, it's preventing me to load into another scene last night....
make sure you have saved your code and that unity has compiled it. if it has been compiled and your button is still loading that other scene, make sure nothing else is subscribed to the button that would load the scene
Fixed it:>
the script already saved... about the "subscribed" idk how to check/tell that one
No? Is that a question or a statement
A question. It has the "?" on it.
is there a class or method i can use to get two random numbers?
Then no
Use the Random.Range twice?
ok
None of this code makes sense
i dont get it
You need to start by configuring your !ide for error detection
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
oh
Then following that, you need to do !learn to actually learn the basics of coding and Unity.
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
So guys, tell me what would be the best solution to make a functional crouching system that allows you to crouch but if you have an object above you that is less than the player's height, will the player continue crouching until he has air of the same height? (I already asked this but now I'm paying attention to them) https://gdl.space/ivujivuvuj.cs

You weren't paying attention before? Why would anyone waste their time then?
No, I just asked at the wrong time
i have already installed visual studio why would i have to install it again?
Nope
Because otherwise you would know what they talking about.
I don't, I'm answering your question about not having to reinstall it.
oh ok i musunderstood it srry
That is visual studio code, and your ide isnt pointing out the very clear errors that exist. Which it should be
what is an ide???
The application where you are writing your code
If you add what you were suggested to, your visual studio should look like this. (The botom part will tell you if your code has errors)
it used to do that
but it doesn't
Hence !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Also mandatory for question here
so i set this up for a combo system so it would do the first attack animation then if you click again the next and so on but if i click before the animation finishes it just skips it how do i add it so it waits till the previous animation is done to let you continue
https://pastebin.com/nRAM5wnW
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.
Hey guys i have a question. I have this script which destroys any gameobject which touches. I was thinking how could i add a CompareTag? Also. I have a script for picking up and dropping stuff. But even when this is dropped it shoots when i click, and i dont have any clue on how to unable that unless i pick it up.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public Transform BulletSpawnPoint;
public GameObject Bullet;
public float BulletSpeed = 5;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
var bullet = Instantiate(Bullet, BulletSpawnPoint.position, BulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().velocity = BulletSpawnPoint.forward * BulletSpeed;
}
}
}
(This is my script for the gun)
disable its Gun component when you drop it and enable it when you pick it up
i am not sure how to do that, but i just had an idea to avoid that problem.
So, I'm trying to write a dash script following a tutorial, but it looks like me and the tutorial guy used a different way to flip our sprites. I tried calling //currentScale from my Flip() method but I get the error CS0103. I tried making the //currentScale.x public and private, but it breaks my script. Is there another way to do this? https://gdl.space/yopopiyadi.cs
if you want your currentScale variable to be accessible to other objects you need to declare it in the class as public. Right now it is declared inside of a method which makes it a local variable so it cannot be public.
So if I just remove it from that method and place it at the start as a float then I can call it in another method?
well you'll still want to assign to it in that method, but otherwise yes. as long as it is declared in the class it can be used throughout the entire class. and if you make it public it can be accessed by other objects
Well, I'm trying to call on it's transform properties in my Flip() method, basically trying to write the dash so that it see's my currentScale.x at that exact moment, so it can tell which way to dash.
realistically you don't need to use the currentScale variable for that, just access its transform.localScale
So I guess I'm still confused. If I assigned it to a float, say as private Vector3 currentScale = gameObject.transform.localScale; as long as the remainder of my Flip() method remains the same, would calling it in my Coroutine still allow it to see those changes?
also it isn't a float. you literally have the correct data type on the line you originally declare it on
Oh whoops. That's not what I meant. Just assigning it as a Vector3 var, would that still work?
Oh nevermind, I see what you meant.
So, now I have the dash working, and I moved on to a double jump which I want to operate the same ( only being able to double jump when it's unlocked outside of the script) and I adjusted my code as correctly as I could with his code based off of what I had ( he didn't have a jump buffer or coyotetime on his script) but nothing happens. I don't get an error, my jump isn't broken, but my character also isn't double jumping whether the bool for the unlock is true or false. Where did I go wrong? https://gdl.space/lovareluqi.cs
for starters, you call Jump before you receive the input. any check will be false bc there is none (the input) . . .
Anyone with no experience and looking to learn together to create a game with unity
The input is defined in line 160. jumpBufferCounter is defined as the jumpInput on line 142
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
sure but you call your Jump method on line 66 in your Update method. then 3 lines later within the same Update method is when you actually get your input. that's backwards. you're jumping on the frame after you've pressed the input button to jump
Ohhhh, okay. I didn't realize that it mattered what order you put it in.
Jump is called on line 66 but you don't receive input β for jump β until line 69 . . .
it always matters. imagine you're making a sandwich. you put your peanut butter on the bread. then you get the bread out of the packet. does that seem right to you?
Huh, it always matters. Code execution is done line by line, top to bottom . . .
That's subjective; it could be either. It depends on the person making it and the complexity . . .
Fair enough. π Well, even after changing that order, and calling Jump() and Dash() after defining the inputs, my problem still persists. No double jump.
what have you done to ensure that your variables are in the state you expect them to be? have you printed any useful logs or set any breakpoints?
Work on getting regular jump to work first. Does that happen?
Depends. Have you configured your IDE yet
Yeah, regular jump is fine. Even with this script there it doesn't break it
You can follow tutorials. There are videos and step-by-step guides . . .
the coyote time and variable jump are still functioning too.
I was thinking of doing a debug.log but I'm not sure how that would work since the function I need to work is a part of the jump process, and I already know that the script itself works because the jump is unaffected.
you can still log useful info. don't forget you can create strings that are more than just useless statements like "here"
That's a start. You should log or debug your jump counter. Doors is increase of decrease when you press it again?
Doors?
"Does it (your jump counter)," my bad, drunk typing on the phone . . .
Oh okay lol. Lemme code it up and see what happens.
You don't store the number of jumps?
No.. Am I supposed to? I haven't seen anything about that when it comes to making a PlayerController
There is no one way, or a right or wrong way to create smth, but if you can do an act multiple times, typically, you store the number of times that act is done and/or the total number of times the act can be done . . .
I dunno, that's never really fit my needs. It's just a Hollow Knight clone demo. Keeping track of the number or jumps or especially limiting the amount of jumps would seriously hinder my platform game with jumping in it lol. Also, I'm having a hard time trying to find out how to make a counter.
When you shoot from a gun, you decrease the amount of available bullets in the magazine. When there are none, the firearm is empty, and you can no longer fire (until you reload). It's the same concept . . .
I don't understand how tracking the number of jumps would hinder the game. You're just storing a value . . .
I had misread what you said. I thought you were saying that I needed to have a finite value for how many times a player can jump.
But I added the counter. https://gdl.space/anuyewaliy.cs
Running that, allows it to pass through the scripts and the jump counter goes up while normal jumping as expected, but with doubleJumpIsUnlocked set to true, there's no double jump, and it doesn't count a second jump midair.
You can if you want. That still won't hinder anything. A lot of games have a jump max to ensure the player cannot jump infinitely . . .
So if my jump counter is going up, and I can jump but not double jump, does that mean maybe that the conditions for the double jump are being met actively all the time? I'm confused lol.
You're logic (and its order) seem to be the issue . . .
Is it maybe because I called isGrounded twice technically? On line 167 I call coyoteTimeCounter which is an if statement of isGrounded, then I call isGrounded on the second if statement on 168.
You only need to check the jump buffer and coyote time when grounded. They don't matter when airborne . . .
Also, it doesn't make sense to call Jump every frame. It's an action that requires input. It should execute when jump is pressed . . .
Yeah, but because Jump() calls on jumpInput, trying to put it in FixedUpdate() results in missed inputs.
I didn't say anything about FixedUpdate; Jump doesn't call jumpInput. Not sure what that means . . .
Basically, check for jump input. If it occurs, call the Jump method . . .
Do you have them enabled?
https://learn.microsoft.com/en-us/visualstudio/ide/reference/how-to-display-line-numbers-in-the-editor?view=vs-2022
your !IDE is unconfigured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Hey, how would have my dust particle play if speed is above 0.1 but stop when speed is at 0
better go through the guide and get it configured if you don't want to get muted
#π»βcode-beginner message
where does the speed variable come from? because you are using your horizontal variable to start it.
also you are currently checking if speed is greater than 0 to stop dust
Share screenshots showing the unity workload installed and the correct ide selected in the unity external code editor setting.
its a public float set to 6f, and would "speed >= 0f" work as equal to 0?
how would that work? if speed is set to 6 then speed >= 0 would be true
but also if it's just set to 6, why would you be using that variable to determine when to stop the particle system? wouldn't it make more sense to use either your input or the magnitude of your CC's velocity?
the unity workload is something you were supposed to install when going through the configuration guide
If you don't understand, you probably didn't go through the config guide. These things are mentioned in it.
Then either you looked at the wrong guide or wasn't paying attention.
it's literally the first set of steps in the guide
Here's a quote mentioning it
Select the Workloads tab, then select the Game development with Unity workload
Why would you ask the yelling people about it?π
Also, configuring the ide is a direct answer to your question.
i don't see anyone yelling, and configuring your IDE is not dumb, its paramount to programming with Unity and C# . . .
ah yes "some dumb thing"
aka the tool you use to write code. that's certainly not important at all, especially since it definitely doesn't do useful things like help you fix errors and even provide autocomplete /s
You asked:
why arent my line numbers showing
The answer to which is: you don't have the ide configured properly.
then you don't want to make games π€·ββοΈ
how would I do that? I'm still kinda new to unityπ
which part?
using either input or magnitude of my CC's velocity
those are two different options that would achieve the same thing. which one would you like to do?
magnitude
alternatively you could just grab the magnitude of your moveDir vector. since it is normalized it will either be 1 or 0
or rather your direction vector, in fact you are already checking its magnitude. throw the Play in there and just stick an else on it to call Stop
something like this?
i would only call Play if it isn't already playing, but yes.
and how would I add an "else if" if I want it to stop
surely you know how to type else
Hello! I was wondering why my VS code is not code hitting? I have some stuff I am using from other packages and everything compiles but nothing is code hitting/stuff like I cannot right click and go to definition
make sure it is configured π !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
well I meant in the parenthesis after if
just use else
ah damn i forgot I installed a new version of unity...that might be why ty
you do not need an else if there because if direction.magnitude is not greater than or equal to 0.01 then it is going to be 0 because direction is normalized so it's magnitude is going to be either 0 or 1 with no in between
worked, ty for that. You saved me from having to type out everything 
I got it working! thank you, but I have another thing. When i first hold a button to move the character, how do i have the particle play right when I hit the button instead of it playing after its pressed?
it's likely that you need to prewarm your particle system or some setting you have set wrong on it
Hi box friend my name is Ghassan Im currently working in a game project with 3 people and were having a problem with make a checkpoint in which when the player hits it they respond from that point
Do you have any suggestions for that
don't ping people into your questions
Excuse me Im new
The reason I did that is because you seemed knowledgable
But Ill meep that in mind
you also didn't say what the problem actually is
so its just I wanted recommendation to how to do a script that makes the player hit the object and then whenever the player dies they respond from it
there are plenty of tutorials for setting up respawn points/checkpoints
Not a code question.
Use #1180170818983051344 I guess
This is a few problems in one, you'll need to specify what you actually struggle with.
Like do you have a way for the player to hit something, a way for the player to die?
Ok so i want to make a game object that has the ability to save the game whenever its hit I hope what I said isnβt confusing
Just add a saver
what is a "saver"
Save spot
be specific that can mean many things
A collider in which whenever it get touched the game gets saved and the player respawns from there
well have you got a system to save the game yet?
No thats what I need help with
have you bothered googling how to set up a save system in unity? because there are plenty of tutorials for that
Tbf, there are many ways data can be saved, and some tutorials may use BinaryFormatter to save, which is no longer a safe way of saving, any other type of saving tutorial may be useful though
can't prewarm it because i have looping set to off
well i don't know a whole lot about setting up particle systems, but i'm sure the folks who hang out in #β¨βvfx-and-particles do π€·ββοΈ
Thank you for all ur help dude
I rlly appreciate it
Okay, I'm confused. I'm getting a CS0414 warning for 36,18 but I referenced isWallSliding in my WallSlide() method. Why isn't Unity seeing that? https://gdl.space/utusijexap.cs
show the warning specifically, people dont remember the codes. I assume thats one about it being unused
It is, I'll post a screenshot.
well it is unused basically, you are never actually doing anything with the value
it is private, no methods or properties return it as a value, you dont use it to check anything, you could remove it and your code would function the exact same
Removing private and just leaving it as void WallSlide() returns the same error. :/
i was specifically referring to isWallSliding, nothing uses it
your WallSlide() method is used
What about line 150?
Yes you are setting it to false, but what affect does that have in your program? What line of code checks the value of isWallSliding and does something based on it
Well that part hasn't been written yet. But at this point in the tutorial I'm following he's still able to go back into the editor to assign values to public Transform wallCheck;
and public LayerMask wallLayer; and it's not updating those fields for me because it's returning this error. Is he just on an older build or something that lets him bypass that?
this is a warning as you said, not an error. you likely have another error then if you code isnt updated, look at your console
the warning is not a problem
Ah okay, that makes sense. I had some spelling issues that needed fixed, now it's updating. I appreciate the help.
how do you check if something is on your screen?
I saw OnVisible but that's not entirely it
I need to be able to check from an empty game object aswell
OnBecameVisible for renderers, but for empty game objects you would need your own function the check if its on screen or not
void CheckIfOnScreen()
{
Vector3 screenPoint = mainCamera.WorldToViewportPoint(transform.position);
bool onScreen = screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1 && screenPoint.z > 0;
if (onScreen)
{
Debug.Log("Object is on screen!");
}
else
{
Debug.Log("Object is off screen!");
}
}
sth like that
I have an NPC which I explicitly assigned this gameObject. Is there a way from my GameObject to know who owns him without explicitely putting the npc in its public variables?
You can create some Initialize function on your GameObject that gets called and you pass in the NPC to store as a reference
Hi. How can I use an object by its name in a script?
Thanks
Don't u have intellisense suggesting it to you? 
if not, it's probably not configured properly.
May be
Yeah, with intellisense it takes extra effort to type it wrong
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
(Thats vs right?)
How to make a system that when the user points mouse to a certain gameobject then there will be a text pop-up on the screen
This sounds like a google search lol
You guys are better than internet
I can give u hints, but i won't give u code.
The items should have colliders.
If you don't want those colliders to hit with other objects, there's a layer matrix that lets you set if those colliders can contact with each other.
You raycast from your mouse point to the gamespace.
You retrieve the result and do stuff that involves the text pop-up you want.
You should google it first, there's going to be tutorials that should already demo this.
What am I writing wrong?
Not learning C# basics.
Real. 
Yes, that too
Damn, I though the question was"what am I doing wrong".
Then do it.
why would you think a string has a property called Door ?
I'm learning C# by writing code
That's the thing, he doesn't know what a string or property is.
Well, it doesn't seem to work then.
I want to use the object by its name: "Door"
then do that
When you get hit by stuff like this, you gotta know what you're recieving, using, and the types.
English is difficult for me, that's why I suffer
There are plenty of learning resources for most languages.
Aye.
pretty sure C# documentation is in Russian as well
I know for sure there are resources for your language.
Programming itself is difficult for me
Welp, basically, hit.collider.gameObject.name gives you a string, which is a set of letters.
So what you want here is the compare the values of the string to Door.
So it should be hit.collider.gameObject.name == "Door".
Thanks π
Well, that's why you need to learn it.
Isn't there any Russian youtubers or something?

Cause damn, starting out with docs can be a pain.
There are plenty
Docs is the best place to learn the basics

I just didn't know what to write next:(
That's because you didn't learn it..?
Woah, any tutorial should be telling you what something does no?
Unless it's like the first parts where you only really focus on variables and making Console.WriteLine();
I thought it worked differently with names (I tried it: "", (), <>, etc.
You don't try. You need to learn the syntax.
Ok
Plenty of people seem to think that learning unity and c# are different. They are, but unity literally use C# and it's what you code in.
If you did find some C# tutorials, try to learn as much as you can before you go to unity again.
It does work differently, those symbols have different meanings depending on where they are used, if C# confuses you I would suggest maybe going through the C# courses on w3schools, most of them are interactable on their site, they also break down the language into various subjects, which may help as keywords when searching up what things do, or if you prefer, you could find a "beginner C#" playlist on YouTube and follow along their (likely Console) examples on various topics like functions, properties, classes, etc
"" - string notations.
<> - generic parameters.
() - argument parameters.
Docs wouldn't say this out loud i think, except for the brackets where youtubers, for some reason, explain functions as calling through a telephone or something. 
Anyways, you're kinda just expected to understand what these are after a while. 
Seeing them in context helps as well over time, for example SomeFunc() is different from if(condition), they both use the same symbols but mean different things to the compiler
Yeah () is used really often. But they're always used as parameters, always.
Even more so with {}, I could call them as code blocks but can do more than that such as in pattern matching.
Hi, people. In game manager in Update method i have a whle(gameIsOn) loop where i update score. By deafult it is set to false. I have a method StartSession(), where i change gameIsOn to true. By some reason editor just freezes on that while loop. Can someone explain why?
Because it loops over and over and never stops
you realistically just need an if statement not a while loop
but by default gameIsOn is false, it shouldt loop at all, no?
i initialized it with false
There's not a lot of ways to freeze.
A while statement will keep executing what is inside until untrue. It won't allow rendering or anything else. while is dangerous and will lock your game
correct, but once it does start looping it cannot stop because loops run to completion. which means if you never change the value of your bool inside the loop then it never ends. this also means the frame cannot progress so the editor freezes
also Update is called every frame. so just swap your loop for an if statement since it's something you want to happen per frame rather than all in one frame
the code should work as a timed score, when every 3 sec it adds up 3 * multiplier, so i think it sould all be completed in one frame
looks like this
if (timer > 3)
{
if (score > 120)
scoreMultiplier = 2f;
score += (int)(3 * scoreMultiplier);
scoreText.text = "Score: " + score;
timer = 0;
}
timer = Time.deltaTime
yes so you do not want a loop for that. just the if statement
also you do not want that to complete all in one frame. imagine getting 3 seconds worth of points in 0.016 seconds
timer += Time.deltaTime
oh yeah that too
yeah, finally works! thanks
Its literally just
float maxSeconds = 3f;
float timer += Time.deltatime;
if (timer >= maxSeconds) {
// do your logic here
timer = 0;
}
no it's not
Bc you want to add up Time.deltatime (its 0.00something, a really low number) and if your timer is always = time.deltatime, it'll never be 3
Why not?
float timer += Time.deltatime;
this is not valid
because you've made timer a local variable
hey im trying to make a 2d game, but iv a problem with my game cam, anyone know how to fix this?
