#💻┃code-beginner
1 messages · Page 629 of 1
spawning an object
and how do i do it?
Instantiate(prefab)
thanks
hi i am still a beginner in unity can someone help me make a save system?
If anyone can help please contact me privately!
hey guys
i am stuck in a bug for around two or three weeks
i can't wall jump after another wall jump
here you can see that i can't jump after colliding with the other wall
idk why
show relevant !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
with this link?
https://paste.mod.gg/
A tool for sharing your source code with the world!
that is one of the sites you can use, yes
and how can i share it with you?
i don't see any share thing
Strange! Maybe double check if you have any unused using statements, I would expect code stripping to strip out parts you don't use. Or set it to high ( Project Settings --> Player --> Optimization). See image for reference. If this doens't help I would suggest #🌐┃web
@slender nymph here you are
https://scriptbin.xyz/rizuwovazu.cs
Use Scriptbin to share your code with others quickly and easily.
hi i am still a beginner in unity can someone help me make a save system?
If anyone can help please contact me privately!
can someone help me with this
there is a lot of spaghetti to go through here, have you done any debugging?
Guys i need help fixing this bug:
What I'm trying to do in details:
So i made the script Ball_mover which moves the ball directly towards the player, and it did work well at first without any bugs but later on when i add physics to the ball (aka Rigidbody) it started bugging
Anyhow to fix that?
yes A LOT
with chat gpt
with myself
i told you that I'm stuck in this for around 3 weeks!
okay so what debugging have you done? or are you just saying that you've just tried random shit and expected to find a fix?
Your WallJumpingTime is set to 0.4 seconds, so after 0.4 seconds you cannot wall jump anymore?
just a second let me check it please
no no that's the duration
i mean how much time the player can wall jump
There's a lot to debug. Check if all the booleans are correct in the first place. But I would suggest just re-write it a bit simpler so you understand it again.
okay fine i will try that
but i checked my code now
should i delete the stopWallJumping private void?
or no?
There's code that says: canWallJump = false in your wallJump() method. So very likely that has something to do with it.
nevermind let me try it
If you always want to wall jump, just remove the boolean canWallJump 😄
Could any of you guys help me fixing this error?
you need to show code if you want help with your code
you should show code, but based on your description, you're moving via the transform and then also added a rigidbody. You need to choose either one as a movement method
okay here's my code
using UnityEngine.UIElements;
public class Ball_Mover : MonoBehaviour
{
[SerializeField] Transform player;
[SerializeField] float moveSpeed = 1f;
Vector3 playerPosition;
void Start()
{
playerPosition = player.transform.position;
}
// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, playerPosition, Time.deltaTime*moveSpeed);
}
}```
yeah, it also appears that everything by the Y for both position and rotation is constrained on the rigidbody
well i want to add physics to the object and also make it moves towards the player, i guessed messed it up
so you are still moving via the Transform which means it does not have correct physics, in fact what is happening is that it is penetrating into the ground because it is moving in a way that doesn't respect collisions then on FixedUpdates it is attempting to depenetrate because the rigidbody is allowed to move on the Y axis
if you want physics, you have to move via physics too. Use the rigidbody and AddForce in the direction that you want
FixedUpdates?
that is when physics is updated
wow thats a lot of information
so what i need in order to fix it is to make it move via both rigidbogy and transform.position? or i should be using one of them?
okay i found a thing
when I'm colliding with the other wall
IF I press the arrow key of that direction(left OR right) the player WILL jump
Only move via the rigidbody if you want physics. you can think of setting the transform.position as teleporting the object, even if its in extremely small steps. Physics will try to respect collisions along the way
So I make my object moves towards the player through using Rigidbody and i'll have to delete transform.position? I'll try to do this immediately
set a varible to accest you rigid body, and access it velocity in your code witha vector3
make sure when you switch to rigidbody movement that you also switch to using FixedUpdate rather than Update, you want to apply physics in time with physics updates
I downloaded it and imported it and now i imediatly i got 3 Errors:
@rocky canyon
Thx! I appreciate your help
ya, i fell off into a rabbit hole,
i'm actually still working on it.. i figured it'd be nice to wire up my character controller and pause menu stuff to the rest of my UI and have it ready..
wdym?
i just added the confined bit.. to demonstrate it beter
ive downloaded a movement script on unity from 2019 that comes with an example player prefab, but when i use the prefab it just falls through any objects i put it on top of and the controls dont work, or if i put the movement script on an object with a rigidbody, it just floats while still not being controlable, my input keys seem to be correct, im not sure what i need to do to get this to work
perhaps check the asset's documentation to see what setup is required to make it work
all it has is a readme that says you can either use the prefab or use put the movement script on an object to do the camera control yourself
i checked the issues tab on github and none of the solves for similar issues worked for me
then either link it so someone can look at it since nobody here is psychic so we cannot possibly know what you're using or what its requirements are or post an issue on the github or anywhere else the asset author accepts support requests
heres the github
are the objects that you put the prefab above on the default layer or are they on a different layer?
i did not ask about the objects in the prefab
yeah i misinterperated it but everything is on the default layer'
then you probably need to look at the layer mask on SurfPhysics to make sure it isn't set to None or something
otherwise you should be asking the asset author for help
yeah its on default
ill put an issue request
When is an Abstract class useful in c# nowadays? I previously thought they were useful for standard implementation but you can do that with interfaces, so any methods without implementation are just the same as "abstract" methods in an abstract class right?
Are they only good for having inheritable variables?
depending on your needs an abstract class can possibly be interchanged with an interface instead, but abstract classes are strictly for inheritance and can contain variables as well as properties and methods, can have non-virtual/non-abstract methods that contain behavior.
interfaces can only define properties and methods, and while you technically can add default behavior to an interface method in most cases you really shouldn't
i see so its just better practice to not use interfaces for "is-a" relationships
and overall more troublesome
there are many tutorials on youtube for a save system
hey where/how did you learn about MoveTowards? Just curious.
imo its better not to think of anything in terms of these relationships anyways. It quickly falls apart. interfaces simply guarantee that a class implements a method, it is required.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface
Yeah it's just a medium of classifying a group of scripts so they can be accessed as a group
does this code mean 'yield return null' is stepped into once per frame?
public IEnumerator Test()
{
while (true)
{
yield return null;
}
}
thats the end of the frame
yield return null; means "pause here for one frame"
I see. Thanks both
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
• :question: Other/None
You have to do all the steps in the instructions.
If that's one of them, you have to do it, yes.
do i need all .net ones too?
you need whatever are in the instructions I linked above
don't ask me, read the instructions
here's the same instructions but also some troubleshooting steps for when you have completed all of them
https://unity.huh.how/ide-configuration/visual-studio
at this point all packages are being downloaded
sounds like a waste of space, but alright
if (hit.distance <= Mathf.Abs(velocity.y) + skinWidth)
This if statement is coming back false, even though the debug says otherwise? any idea how I can fix this?
wait I'm dumb, I was comparing the debug in reverse!
well, now I have a different problem
I'll try doing < || Mathf.Approx
but if anyone knows a better solution, I'd welcome it!
Any way to make logs not stack up like this?
This took me too long to figure out. Anyone else happen to figure this out?
public bool isEmpty() {
return !( amount == 0);
not a code question. turn off Collapse in the console window
float _compVelocityY = Mathf.Abs(velocity.y) + skinWidth;
if (hit.distance < _compVelocityY ||
Mathf.Approximately(hit.distance, _compVelocityY))```
hmm, this did not work, its still coming back false... anyone know how I can fix this?
hi just coded smth for a bullet that makes it move torwards the player
and flip the sprite depending on its x velocity
but is there a way for me to just make it point straight at the player?
i know the vector pointing to the player im just not sure how to turn that into a direction for the gameobject
Quaternion.Lookrotation to get a rotation, transform.lookat(playerpos) to make it just look at player
oh alright
ty
That would probably make it look on the z axis, which is not what you want in 2d.
using it rn, how can i keep it from rotating the Y axis? im making a 2d game and its making it go flat lol
yeah lmao
im now trying to figure out how to fix that
That's not gonna work. You could keep the bullet sprite orientation with it's x axis and assign the direction to transform.right
Actually, nevermind that. It might flip the sprite to the back face.
You could keep flipping the sprite and assign the transform.right toPlayerDir or -toPlayerDit depending on the flip state.
LookAt should work, no? Just use z as world up
what would that look like i know absolutely nothing about how quaternions work 😭
i should prolly start learning more abt those
oh wait is this topdown or sidescroller
For 2d, setting transform.right to the direction of the target should make it look at the target, if right is forward.
sidescroller
how do i do that 😭
i think learning how rotations work is gonna kill me
You can actually just assign a value to transform.right like it was any other direction variable and the object will point in that direction
how do i assign a value to transform.right tho my mind is empty and ive been trying to understand anything being said here for the past 8 minutes 😭
With =
oh i forgot i dont need weird lines of text for that 😭
oh my gosh
it was that easy
im trying to open a script but it does this can someone help
😭
That's typically what "assignment" means. Just =.
my mind is going to kill itself now but thanks for the help
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
• :question: Other/None
maybe get visual studio and then use that to open it
hey guys, im working on a 2D game for a project, and i wanna add an ability where the character shoots and when the bullet collides, the character transform position = collision transform position. However this only works when the prefab is added to the hierarchy, and not when i instantiate the bullet. Can someone help me with this
it made me install it but where do i find it?
<= would be sufficient here.
thats how it was before, but it was having floating point value related problems
my solution was to do a check with + or - a small amount from hit.distance
and that seems to work ok, gonna do some playtesting with it
then just add a 0.0001f epsilon to skin width
eg
velocity.y <= Mathf.Abs(velocity.y) + skinWidth + 0.0001f
I'll try that, that seems less messy than what I did
the <= should not always be false due to imprecision issues though
ok so it was the installer it gave me, which one do i choose there is a bunch
usually imprecision issues is for == more so than <=
unless you're dealing with very small velocities and skin widths
what visual studio is best for unity?
those are the same editor but different licenses
read the description
you need the Unity Workload
ok
how do i fix this?
did you read the message ?
you can't put Non-Components on gameobjects
then how do i get the script to work on the camera?
make it a monobehavior ?
same problem 😂
you need to get your !IDE configured 👇
you likely have compile error
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
• :question: Other/None
also this ^
this page has troubleshooting steps for when you've completed all of the steps in the relevant article: https://unity.huh.how/ide-configuration/visual-studio
did you not go through the page i linked to you earlier?
if you had gone through all of the troubleshooting steps then your visual studio is working
what module are u supposed to install?
In the Add modules to your install step, select Done.
why not read the instructions and find out?
actually wait, those are part of the instructions for installing unity. are you just not comprehending the instructions you are reading?
no, you're just not bothering to pay attention to the actual instructions
vsc on the other hand
ive done everything there is to do
prove it. open visual studio and screenshot the entire window with the solution explorer visible
so that was a lie
how
or did you mean that as "yep, i did not bother going through the page you linked to me"
why wouldnt i
you clearly did not.
#💻┃code-beginner message
did that too
no you didn't. i can very clearly see in your screenshot that you did not complete the troubleshooting steps
can u be a little bit more clear
what exactly did i not do
why don't you bother reading the fucking instructions instead of lying and saying you did
because i can tell u exactly what ive done
i have read the instructions and ive done them the ones that apply to me..
and i can tell you exactly what you didn't bother doing, and that is to read the troubleshooting instructions that i linked to you
https://unity.huh.how/ide-configuration/visual-studio
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#install-unity-support-for-visual-studio
these 2 right?
specifically the first one, yes. because that also links to the second but also the first one has troubleshooting instructions for if it is still not working after completing the typical setup steps
so fucking read them
step 1 for you should apparently be "learn to read"
ive followed both of these and complete them yet ive still got a problem
bullshit
its like i actually did the steps its nuts
then what was the first troubleshooting step it told you to do
here, you clearly need this: https://www.youtube.com/watch?v=PdtJyKyZB4k
the US is changing alphabet
u need it more
New Alphabet Song?? #lawyer #court #law #attorney #personalinjurylawyer
everyone notice how they never answered this because they didn't actually bother reading the troubleshooting instructions
then what was the first troubleshooting step i told you to do
is what i read
my bad man
b for monkey
If you did all of the steps, can you list them?
install unity hub get unity edit preferences select visual studio 2022
some shit like that
then download visual studio, with all the packages ez
That's not all the steps. There are steps specifically for when you've set it up, but it still doesn't work.
You even linked the pages yourself. Yet you didn't read them all apparently:
#💻┃code-beginner message
i know thats not 10/10 compared to the fucking configuration
what am i missing
packages are pre installed
true or false
oh yeah i did that one 55 times
you do realize that your screenshot earlier proved you didn't even do step 1 there, right?
Did you regenerate project files? Via unity? Did you regenerate project files via VS?
no i clicked on the button that says regenerate files
or something like that
no visual anything after being clicked
still restarted 69 times
Wtf is even "something like that"? That makes it sound like you didn't do it at all or did not do it correctly.
And yes, it seems like you don't have the unity workload either.
Follow all the steps and take a screenshot at every one of them.
im not going to reinstall
You don't need to reinstall. If it's installed already just take a screenshot
does this also apply as steps?
Did you do the solution explorer part?
obviously not since that would actually fix it
that will tell you for sure if you do or dont have the Workload
Yes. But start with the other link that talks about workload.
the other link that talks about workload?
Yes. You linked them both. Did your forget already?
It's mentioned on that page. Are you sure you read it?
its not even in the title why would it be relevant
Is everything relevant supposed to be in the title..?
maybe
Here's a quote from the page. Now go read it properly
Select the Workloads tab, then select the Game development with Unity workload.
You wont last long in development with this attitude
all packages are installed workloads*
Take a screenshot then
the FULL window
Checkbox selected doesnt mean much if it shows Install size rather than gained space size or 0
alr so time to do the other steps
You don't need all of them, but ok. now the next screenshot. The correct VS selected in the external tools in unity.
also never a good idea to configure IDE with Errors in the compiling. As mentioned in the troubleshooting steps
Great, now follow the "if you are experiencing issues" steps. All of them. In order. No skipping.
Hey there, I was wondering how one might go about rotating this "beak" object around the beakPivot parent? Currently it's rotating fine, but I haven't managed to get it to rotate as a pivot to the parent if that makes sense. If you need me to elaborate on anything further just lemme know, thanks!
BeakPivot is positioned at the opposite end to where the BeakTip is on the cylinder btw
done
even restarted
kinda confused on what ur trying to do exactly lol
done what exactly?
If you have compiler errors, if possible comment out those files so Unity can compile code.
Ensure the Visual Studio Editor package is installed and updated in UPM (com.unity.ide.visualstudio).
Regenerate project files via Unity.
Close VS.
Select regenerate project files in EditPreferencesExternal Tools.
Reopen VS via AssetsOpen C# Project.
Regenerate project files via VS.
If an assembly in the Solution Explorer is marked as (incompatible), right-click it and select reload with dependencies.
Restart your computer.
so did you comment out the compile error first of all ?
ye
ok show its not erroring anymore
I'll give that a go, cheers 👍
no
thats the 1 thing i didnt do
didnt think it applies to me
pleaase dont say such stupid things, you were specifically instructed to follow ALL the Steps
if you here to just troll find another server..
yeah bro im having the time of my life trolling rn
it would be lot less frustrating to you and everyone involved if you actually learned how to follow a step by step instruction without claiming "it doesnt apply to you" when its part of Troubleshooting
i did it man
congrats, it is configured after that
if only you'd followed the instructions earlier when i told you to you would have been done a long time ago
ya you didnt check solution explorer again after you did that..
but is configured
i don't even understand how they thought that step didn't apply to them since it was clear from their earlier screenshot that the project was marked (Incompatible) and that is like the main thing mentioned for that specific troubleshooting step
ya I always think troll but there is that Hanlon's razor part
do i have to do it again
why would you if its configured
i have no idea what im doing man
instead of making assumptions about everything you should read the information presented to you
It should be working now. Are there any specific issues that you're worried about?
yeah so instead of feeding a man for the day how about teaching me how to fish, i wanna learn how to fix errors or the red line code type shit, also isnt this supposed to be a different colour?
It should be indeed. What does it say if you hover over it?
Also sharing the whole !code could be helpful
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
idk what that is
i was trying to copy a tutorial
Time to learn then.
That code at the very top doesn't look very good even if you don't know anything about coding.
well you copied it wrong
the guy did it flawlessly
its not good to copy code when you dont even know the basics of formatting
and if you look real closely, you'll see you have something different than the tutorial has
yeah its been tampered with recently, fuck the code isnt the whole configuration of IDE supposed to fix MonoBehaviour?
your errors on previous lines are causing that error
It did. But the problem is not with it.
ye u was right
Even if you have a perfectly working chair, when break it's legs, you can't use it properly, can you?
Or if you put it upside down
u can still use just not how it was meant to
Well, code is not as forgiving as reality. If you're not using it as intended, you're not using it at all
trueing
is what it was meant to look like
thx for helping man im really grateful
Last advice go learn C# basics and follow the unity beginner pathways on unity !learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ideally right now, before continuing with whatever you're doing.
would u recommend school or college?
None. There are plenty of learning materials online.
You can get this done in a week or two.
what about unemployed
Not sure what you mean by that?
Yes. Essentials and junior programmer would do. The rest is if you want.
@rich adder I realise I was a bit weird in my wording but it's all sorted now, thanks for getting my brain to work though 😁
anyone know how to format numbers so if the number would be 1000 then its 1K or if its 1000000 1M and so on and stuff preferably would be able to just keep going and stuff
You could set your own threshold then return the suffix for it, iirc you can also use Log10, or use something like Humanizer maybe?
Why doesnt my mesh stick to my ragdoll?
cheers
so i was actually able to get chatgpt to do it for me partially sadly it still wont be endless but it should be basically endless because unless someone finds a way to edit the save data no one will get enough money to get more then it has rn
but my issue im having is the way it rounds up and stuff so i have it once it starts using abreiveations to display for example 9.8K but it displays that when your at 9750 so i dont think that is the right aproach since it will not give the most acurate numbers
got any ideas
should i add another number at the end so it would be 9.87k or change it to only switch to 9.8K when it reaches 9800
or smth else
This is more of a design question, but I think the latter would be more natural.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
before u do coding, i strongly recommend u to download rider
its a very very useful coding tool
and its completely free
only for non-commercial *
if he wanna start a company he can switch back to visual studio💩
having fun doing the educational course
you realize commercial means if you make profits on your project/game/code regardless if you're in a company or not
welp if ur college students and learning, ofc
Develop .NET, ASP.NET, .NET Core, Xamarin or Unity applications on Windows, Mac, Linux
yeah plz tell me ur still a student and under learning
no im actually a retired wizard
"its not the tools that make an artist"
🤔
fun fact, you can be a student and still work on a commercial project which means you would be required to purchase a license for rider
🤓 👍
are you getting a commission from jetbrains lmao
nah, but its useful lmao
its better than visual studio and vsc in my opinion , anyway i dont have commission nor financially supported by jetbrain
while it might make some things faster in some sense, its not the tool that makes an artist
they can use rider and struggle with the same lack of basics regardless, the editor doesnt mean anything in your learning
ofc, but after they learnt the basic and wanna get their hands dirty, thats the moment it gone useful
oh thats cinemachine
does it have any functions
you're jumping way ahead of yourself
its a better camera with more function than the old one, but its way more advanced topic
if u really wanna have a learning step or learning curve , in a very simple manner
C# basics > unity editor basics (QWERTY / creating objects) > intermediate C# skills > advanced unity skills > extensions
colliders, rigidbody or any stuff like that is around basics
the unity pathways are the best to get foot in the door, they cover most of those
yeah
u know what, ignore that little icon first unless the lectures teaching it, follow the path in unity learn
if u encounter some more mysterious icons u can ask here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
is there a way to always use wasd in scene view instead of mouse controls
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
Super quick question, how come when creating a new rigidbody variable, you have to specify that "rb" is getting the rigid body component when you've already specified "Rigidbody rb;" at the top??
or just any component variable for that matter
declaring a variable doesn't automatically get any component. it just declares that you're going to store something of type Rigidbody in rb. this is how any reference type works, rb is null when you only declare it. value types, like int, have default values
declaring something isn't the same as assigning a value , even outside of unity
so, you have to be very specific when declaring a variable, but floats, bools, integers, etc all have their own places to store values??
you still assign a value, but the difference is those are value types so their default isn't a null object unlike reference types, like rigidbody
an int is still stored in a variable, and these value types default to 0 so unless you want 0 you need to specify what value it should be anyways. reference types are just null, you need to assign it to something
0 is null?
no 0 is 0
you should really look into c# basics then first and follow an actual tutorial, plus do examples to wrap your head around it
null is default for reference types
if you want more understanding , look up Reference Types vs Value Types
thats what ive been doing atm 👍 i just like to ask questions to make sure that im retaining information and dont get anything mixed up
i think i understood that last part pretty well
saying "Rigidbody rb;" doesnt assign the component to rb, it just tells unity that thats where the variable is being stored??
it tells the computer, I want to do something with a rigidbody, the computer doesn't know WHICH rigidbody to run those on until its assigned one
okay that makes a lot more sense now thank you
Hello! Quick question, const means that a variable can only be changed when its first created
private const int = 3;```
yes , u can only give it a value here, when u created it
only on the initializer
after that u cant change
Thanks
btw always check the documentation https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const
Thx
if u wanna distinguish null and 0 quick , heres the rule , 0 is something and null means nothing
0 is a number right? no matter how u understand it, it is a number/value, so its related to number types, lets say int(eger), or float, or double, yeah it can also be a char/string , but u need to know it is a value, it is NOT nothing
0 or 0.0f is the default value of number types , because of special reasons, in C# those simple types cannot be nulled, they must always have a value , so if u dont do anything to integers/floats, they will still get a 0 , and it means they have a value
as for reference types, like those rigidbody, they dont need to have something at first, they can be empty, because u can "reference nothing" and C# allows it
u will get null reference tho if u try to use the value 💩
well string is reference type
(basically an array of chars)
string is quite special here, because C# allows string to have nothing
oh that make up the whole thing lol
but yeah they have value semantics
aka they are immutable, can be compared by value with ==
i would really avoid just dumping information like this, to just let them learn from an actual resource. Even just bringing up int? to say we can ignore it is going to confuse them more. Plus I don't think char[]{0}; is even valid syntax
Ive never really seen these kind of teachings benefit the person more than just letting them go and learn properly. Strings werent even the topic of discussion
anyone know where i can find some scenes to fuck around in maybe environmental or something
check the asset store, this isn't a code question
Unity provides templates

Hello, what code can I use to reverse the direction of movement when an object collides with a second object (it may be a bit unclear because I'm using a translator)
just invert the number ?
Vector3 direction = new Vector3(1, 0, 0);
direction = -direction;
or multply by -1 etc
Oh,thanks
do you actually want to reverse the movement? or have it bounce and reflect off?
there is a reflect method and you would plug in the direction, plus the normal of what you hit https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.Reflect.html
I want to reverse
incorrect?
string str = null;
string str = default;
both work like any other ref types. unless you do string.Empty, it won't be an empty string, just null
the difference is that string in a lot of contexts is treated more like a standard value non nullable type rather than an object
can trip people up
im trying to make a 2.5D Platformer but my jump button doesnt work when i play the game on my phone but when i try it in the phone simulator on my pc it works. The right and left movement works on my phone as well just the jump button doesnt. The problem doesnt occur because of the onGround variable not being true, I tried removing the onGround variable from the jump if statement and it still only works in the simulator not on a real mobile device. It may have something to do with the way I made the jump button I just put an image on the canvas and gave it a touch button component and mapped it to the south gamepad button and in the input system manager I added the south gamepad button to the jump action is there maybe something wrong with doing it that way or is there a better way to do it? https://paste.mod.gg/basic/viewer/cbeznexattvf/0
A tool for sharing your source code with the world!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
private Queue<ICommand> GatherCommandsAsQueueInOrder()
{
var commandsQueue = new Queue<ICommand>();
foreach (Transform commandEntry in _commandsParent)
{
var commandEntryComponent = commandEntry.GetComponent<CommandEntry>();
commandsQueue.Enqueue(commandEntryComponent.Command);
}
return commandsQueue;
}
could someone explain to me, why this throws error The non-generic type 'Queue' cannot be used with type arguments?
it's not possible to return a Queue of ICommands?
public interface ICommand
{
Task Execute(Rigidbody rb);
}
ah lol, i wass missing a namespace
nevermind
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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, need some help, i am using a function for player movement that addforce , i want to keep the momentum and velocity constant, what is the library function in unity for that
hey guys, I am having trouble using the new input system
basically, I can't make a click action work
this is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class MeleeAttack : MonoBehaviour
{
[Header("References")]
public Animator animator;
public InputActionReference fire;
[Header("Parameters")]
public int numberOfAttacks;
public float cooldown;
private float timer = 0f;
private float cooldownTime = 0f;
private int attack = 0;
private void OnEnable()
{
Debug.Log("enabled");
fire.action.started += PerformAttack;
}
private void OnDisable()
{
fire.action.started -= PerformAttack;
}
private void PerformAttack(InputAction.CallbackContext obj)
{
Debug.Log("Cooldown = "+cooldownTime + " timer = "+timer+" attack = "+attack);
if (timer > cooldownTime) {
if (attack >= 3) {
cooldownTime = timer + 2 * cooldown;
attack = 0;
} else {
attack++;
cooldownTime = timer + cooldown;
}
animator.SetInteger("Attack", attack);
}
}
void Update()
{
timer += Time.deltaTime;
}
}
these are the settings
what am I doing wrong?
It is not calling the perform attack function (the debug is not appearing on console)
may need to call fire.enable. I forget
Was just gonna say the same
Do you mean Rigidbody.AddForce() ?
protected override void EnableInputs()
{
click.Enable();
}
protected override void RegisterActions(bool register)
{
click.performed -= Click;
if (register == false) { return; }
click.performed += Click;
}
how can i make a button do 1 thing when i just click it once and do another thing when i hold click on it for like more then a second
(i need a button to do 2 things for a mobile game so i cant just do right click)
Off the top of my head, I can't remember if they work with touch though.. so, test
You may also need, Up: https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.EventSystems.IPointerUpHandler.html
DownHandler might just fire once, and not constantly. So set a bool/ coroutine/ something true in down, and set it false/ stop in Up
public void OnPointerDown()
{
isHolding = true;
holdTimer = 0f;
}
public void OnPointerUp()
{
if (holdTimer < holdTime)
{
StartCooking(); // If released quickly, cook instead
}
isHolding = false;
}
so like this?
No
Nothing (other than two vars being set) will happen while it is down, and start when you release
The below informs you how to share !code correctly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
ooohh it was 3 of those things i thought it was 2 i was super confused lol thanks
Click will happen every time, unless you put in some check if you don't want it too
Also is there a better way of doing what I’m trying to do because I have a button that i need to click to start it but also click to open upgrade menu
Would it be better to add another button above it to open the upgrade menu
With that amount of info.. I'd say yes
How do i make that the button needs to be played to the end and only then can get played again?
You have two options:
-
Don't use
PlayOneShotbut instead assign the buttonClip to the audioSource directly and.Play()it. That will let you check if the audioSource isPlaying in yourPlaySound()function's if statement. -
If you want to use
PlayOneShot, then you need to also have abool IsSoundPlayingthat is set to true when you play the sound, and then set back to false by using something like a coroutine that waits the length of the AudioClip buttonClip
whats the problem and where can i set it to single or smthing
and where can i set active input handling to single?
The settings window has a search bar in the top right
i already searched that there
It's under the Other Settings tab
what other settings tab
In the player settings.
found it thaks
using UnityEngine;
using TMPro;
public class ProjectileGun : MonoBehaviour
{
public GameObject bullets;
public float shootForce, upwardForce;
public float timebetweenShooting, spread, reloadTime, timeBetweenShots;
public int magazineSize, bulletsPerTap;
public bool allowButtonHold;
int bulletsLeft, bulletsShot;
bool shooting, readyToShoot, reloading;
public Camera fpsCam;
public Transform attackPoint;
public GameObject muzzleFlash;
public TextMeshProUGUI ammunitionDisplay;
public bool allowInvoke = true;
private void Awake(){
bulletsLeft = magazineSize;
readyToShoot = true;
}
private void update(){
MyInput();
if (ammunitionDisplay != null){
ammunitionDisplay.setText(bulletsLeft / bulletsPerTap + " / " + magazineSize / bulletsPerTap);
}
}
private void MyInput(){
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
else shooting = Input.GetKeyDown(KeyCode.Mouse0);
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();
if (readyToShoot && shooting && !reloading && bulletsLeft > 0){
bulletsShot = 0;
Shoot();
}
}
private void Shoot(){
readyToShoot = false;
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
Vector3 targetPoint;
if(Physics.Raycast(ray, out hit)){
targetPoint = hit.point;
}
else{
targetPoint = ray.GetPoint(75);
}
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
//spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0);
//make bullet
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
currentBullet.transform.forward = directionWithSpread.normalized;
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * shootForce, ForceMode.Impulse);
if (muzzleFlash != null){
Instantiate(muzzleFlash, attackPoint.position, Quaternion.identity);
}
bulletsLeft--;
bulletsShot++;;
if(allowInvoke){
Invoke("ResetShot", timeBetweenShooting);
allowInvoke = false;
}
}
private void ResetShot{
readyToShoot = true;
allowInvoke = true;
}
private void Reload(){
reloading = true;
Invoke("ReloadFinished", reloadTime);
}
private void ReloadFinished(){
bulletsLeft = magazineSize;
reloading = false;
}
}
getting these errors what do i do
how do i fix this
What lines do those errors point to?
nvm im stupid lol
yes
You can just modify the velocity directly
make sure all packages are up to date, if the error persists after updating packages then close unity, delete the Library folder from within your project, and open unity again so it regenerates the Library folder (this will also cause a full reimport of all your assets)
tysm i fixed it
make sure your !IDE is configured so you can't make these mistakes. also so it helps prevent the spelling mistake you made 😉
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
• :question: Other/None
Hello once again here for a question 😅
So I am creating a fp horror game in which there is a line xRotation -= mouseY;
So someone please help me to understand this line plz !
Hope someone will respond
you already received an answer in #💻┃unity-talk
if you need further information then clarify what you still do not understand
There's always an error like this how do I fix it, thanks
that is neither a code issue nor an error
so how do i get rid of it or its meant to be there
Hi, the (Lightbulp) Quick actions and refractories is not working for me. It's the very first time I'm scripting.
After I write "update" then press Tab on the keyboard, it should automatically write "private void update()"
But it just goes a few spaces forward instead. I tried CTRL+. and by right clicking it, nothing happened. The lightbulp is also not showing on the left side.
Photo for reference:
!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
• :question: Other/None
Thanks!
I have this treatmentImage.sprite = Resources.Load<Sprite>("Assets/Art/hospital"); and the asset exists but it doesnt load, do i have to do somethign special to turn an asset into a resource?
ooooh okay
Hey y'all, having some trouble atm with my coding. Currently, I want to have a random chance to have a special card pop up so the player can play it. However, this would have to be in a specific area and I don't really know how to do that. (Can y'all tell Im a beginner beginner?) Anyway lol, here's my code.
https://paste.ofcode.org/32QSFc2xZbGYFHuZwgUDziw
What I basically want is the clones of these cards (which have the buttons to do stuff attached to them) to pop up, with a random chance to be any one of them.
How would yall go about it? I cant really find any good videos to watch on going about this. Thanks. (Please @ me if you respond, thank you so much!!!)
What does "specific area" mean? If you want the list to be ordered in a special way, use a horizontal layout group and set its child index to order it.
Sorry, weird wording. Basically just meant that it would have to be in the places the cards are already in. I don’t know what the horizontal layout group means sadly, I’ll go research it rq! 👍
I would throw all the cards in an array of the type GameObject then get the card in the array at an index that’s a random number between 0 and the end of the array
ideally your cards are spawned dynamically or re used and with a horizontal layout group on their container parent. With that they get positioned for you so you dont need to fiddle with that manually.
private void AttachButtonToCard(GameObject cardObj, GameObject cardButtonPrefab)
{
GameObject buttonObj = Instantiate(cardButtonPrefab, cardObj.transform);
buttonObj.transform.SetParent(cardObj.transform, false);
buttonObj.transform.SetAsLastSibling();
Button buttonComponent = buttonObj.GetComponent<Button>();
if (buttonComponent != null)
{
Debug.Log($"Button added for: {cardObj.name}");
Button buttonCheck = buttonObj.GetComponent<Button>();
Debug.LogWarning($"Button still there? {buttonCheck != null}");
buttonComponent.onClick.RemoveAllListeners();
buttonComponent.onClick.AddListener(() => OnButtonClick(buttonObj));
Debug.Log($"Number of listerners {cardObj.name}: {buttonComponent.onClick.GetPersistentEventCount()}");
Button buttonCheck2 = buttonObj.GetComponent<Button>();
Debug.LogWarning($"Button still there? {buttonCheck2 != null}");
}
}
produces these logs:
-
Button added for: Card_Air Boost
-
Button still there? True
-
Number of listerners Card_Air Boost: 0
-
Button still there? True
What am i doing wrong?
GetPersistentEventCount() does not count listeners added via AddListener. a PersistentListener is one added via the inspector
How would I turn it on though? Usually whenever I try that it gives me a Null Object reference error
well even if the log is wrong... The CardButton still has no listeners
They are presuming you say have 5 card objects already created and added to this serialized list
you will not see listeners added via code in the inspector. only persistent listeners will be there (as in ones specifically added via the inspector)
ahh
btw you are setting the parent twice as you already gave the parent transform in Instantiate()
it should also be set as the last sibling by default
private void AttachButtonToCard(GameObject cardObj, GameObject cardButtonPrefab)
{
GameObject buttonObj = Instantiate(cardButtonPrefab, cardObj.transform);
buttonObj.transform.SetAsLastSibling();
Button buttonComponent = buttonObj.GetComponent<Button>();
if (buttonComponent != null)
{
Debug.Log($"Button added for: {cardObj.name}");
buttonComponent.onClick.RemoveAllListeners();
buttonComponent.onClick.AddListener(() => OnButtonClick());
}
}
// Die Methode, die aufgerufen wird, wenn der Button geklickt wird
private void OnButtonClick()
{
Debug.Log($"Button auf der Karte {this.name} wurde geklickt!");
}
So this should produce a log, right?
when the button is clicked, yes
well it doesnt^^*
have you confirmed that the button actually works?
im gonna guess its not sized or positioned correctly to ACTUALLY be clickable
How would i do that?
The raycast target is active, there is nothing infront, event system is there,...
(The Button image is the black thing)
click the event system and check it's preview window when you try to click the button (click the button multiple times to be sure since clicking out of the game view makes it lose focus so the first click in it again will be the one to give focus back)
you can also check this for troubleshooting steps to take to ensure the button works: https://unity.huh.how/ugui/input-issues
Ahh, i found my Problem... I am building the Card Objects here:
private void Start()
{
_getUnits = FindObjectOfType<GetUnits>();
_getUnitDecks = FindObjectOfType<GetUnitDecks>();
_getCardObjects = FindObjectOfType<GetCardObjects>();
// Lade alle Karten:
allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);
// Lade alle Units und ihre Decks:
allUnits = _getUnits.Load();
// Lade die Decks der Units:
unitDecks = _getUnitDecks.Load(allUnits);
// Sorge dafür das Units im Dropdown auswählbar sind:
PopulateUnitDropdown();
// Event-Listener hinzufügen:
unitDropdown.onValueChanged.AddListener(OnUnitSelected);
// Alle verfügbaren Einheiten:
PopulateAllCardScrollView();
}
(In the line: allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);)
And "clone" theme here:
private void PopulateAllCardScrollView()
{
// 1. Vorherige Karten aus der Anzeige entfernen
foreach (Transform child in cardScrollViewContent)
{
Destroy(child.gameObject);
}
// 2. Falls keine Karten geladen wurden, Debug-Warnung ausgeben
if (allCards == null || allCards.Count == 0)
{
Debug.LogWarning(":warning: Keine Karten zum Anzeigen gefunden.");
return;
}
// 3. Alle geladenen Karten im cardScrollViewContent platzieren
foreach (GameObject card in allCards)
{
GameObject cardItem = Instantiate(card, cardScrollViewContent);
// Optional: Name für Debugging setzen
cardItem.name = "Card_" + card.name;
}
}
That somehow removes the button Click component... how do I clone an Object with an working Button?
not gonna lie i cannot understand this code
^^*
make sure you dont modify your prefab
somehow removes the button Click component
what does that even mean? because if it has a Button component then it has an onClick event. it's not a separate thing
OH, maybe they think the listener added in code would be copied?
this is what you get when you blindly copy&paste chat-gpt generated code
without even understanding it
Okay, when im loading my scene I wanna load all Cards that exist.
Those are stored here: (Normaly not part of the UI)
When i use a Filter or smth, i wanna scan all the cards there and only use "some cards"
this Code:
private void PopulateAllCardScrollView()
{
// 1. Vorherige Karten aus der Anzeige entfernen
foreach (Transform child in cardScrollViewContent)
{
Destroy(child.gameObject);
}
// 2. Falls keine Karten geladen wurden, Debug-Warnung ausgeben
if (allCards == null || allCards.Count == 0)
{
Debug.LogWarning("⚠️ Keine Karten zum Anzeigen gefunden.");
return;
}
// 3. Alle geladenen Karten im cardScrollViewContent platzieren
foreach (GameObject card in allCards)
{
GameObject cardItem = Instantiate(card, cardScrollViewContent);
// Optional: Name für Debugging setzen
cardItem.name = "Card_" + card.name;
}
}
- Clears all Child Objects in the UI content container here:
here as in this element
do you even understand this code? or do you just want someone to tell you directly how to fix it and/or do the code for you
fair critique
like 40-60%?
im trying to learn
it is against server rules to not disclose AI generated code. #📖┃code-of-conduct
uh, mb
then go learn with proper sources, dont learn via chat-gpt where you just copy&paste stuff without even understanding it
whats the point
If you destroy and re instantiate card then you will need to subscribe to the click event on the new instance.
there are beginner courses pinned in this channel and the pathways on the unity !learn site are a good place to learn the engine. don't let yourself learn bullshit from a bullshit generator
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Those dont destroy the Objects attached in the scene manager*
it's a nice tool when you are somewhat experienced and know how to use it and why
helping you at this point is pointless, as you won't even understand the provided help, and noone will just re-write you the code
Look i understand what you are saying.
Im pretty good with python and i know how i want my game to work. Im using Chatgpt as a bridge
just go and learn via proper sources and you'll figure it out yourself
jesus
yea this isnt helping anymore
I will help if you can correctly describe the problem but it helps no one if you generate code with AI and even you dont know what its doing...
I can.
Let me write it out
My first Problem:
- Im adding a listener manually per Code, but it didnt show up
- Fixed (its just not visible in the inspector, sry i didnt knew that)
My second Problem:
- im generating (UI) CardObjects from a json. These Objects get the mentionend listener.
- I store them outside the UI Canvas (i know that doesnt make sense and I will defenitly change that later)
- I use this TEMPORARY Code snippet:
private void PopulateAllCardScrollView()
{
foreach (GameObject card in allCards)
{
GameObject cardItem = Instantiate(card, cardScrollViewContent);
}
}
- To copy them into the UI Canvas.
The Problem:
The copying seems to delete the Button component.
s
private void Start()
{
// _getUnits = FindObjectOfType<GetUnits>();
// _getUnitDecks = FindObjectOfType<GetUnitDecks>();
_getCardObjects = FindObjectOfType<GetCardObjects>();
// Lade alle Karten:
allCards = _getCardObjects.Load(cardPrefab , cardButtonPrefab);
// Lade alle Units und ihre Decks:
// allUnits = _getUnits.Load();
// Lade die Decks der Units:
// unitDecks = _getUnitDecks.Load(allUnits);
// Sorge dafür das Units im Dropdown auswählbar sind:
// PopulateUnitDropdown();
// Event-Listener hinzufügen:
// unitDropdown.onValueChanged.AddListener(OnUnitSelected);
// Alle verfügbaren Einheiten:
PopulateAllCardScrollView();
}
Instantiate() will only copy some variables and state to the new version (serialized stuff). Code added listeners will NOT be copied (as these are not serialized).
Therefore the new copy of "card" will require event subscriptions to be added once again. It was not "deleted" but the whole state was not copied as you expected.
sorry but this doesnt even make sense what you're saying: The copying seems to delete the Button component.
English isnt my first langugae, you know what im trying to say
No, the Connection between the Function
private void OnButtonClick()
{
Debug.Log($"Button auf der Karte {this.name} wurde geklickt!");
}
and the button is lost
thank you!
listeners?
unless you've added some listeners to the onClick in the prefab
you never add them in code after you create new instance
but since it's a private function, then you didn't add it via inspector
so you just need to add the listeners to the spawned instances
yeah i know
I just dont know random stuff like that
it's not random at all, it's all explained in the docs
Thats fair
Unity could technically copy the whole managed object (c# stuff) state (so other variables) but that could quickly cause problems.
So as long as you remember that serialized stuff gets copied and the rest is back to "default" you will be fine
Say I have two lists, one is {15, 25, 10, 50} and the other is {a, b, c, d} I want to order the first list in ascending value so it would be {10, 15, 25, 50} and I want the second list to match that reordering {c, a, b, d} How do I do this?
yeah, thanks!
as in alphabetically?
is there a reason you have two separate lists instead of a Dictionary or a list of some object that contains the data you wanted to store in the separate lists?
I want to swap the positions equally but based on one list
Example where we pair the 2 variables together and sort them with the int.
List<(int, char)> toSort = new() { (1, 'a'), (2, 'z') };
toSort.Sort((a, b) => a.Item1.CompareTo(b.Item1));
Is there ever a time where you don't want the lists to be paired to one another?
Its a spawning system that I wrote that uses two lists in a scriptable object. I'm rethinking it already based on what I am seeing here.
but why does it use two lists instead of a single list of some data structure
thats a great question
This may be boneheaded but how do I access specific values in a multiple item list like List<(int, char)> foo
if I wanted only the int
scriptable object is needed
my example used a Tuple but you can use a custom class or struct or whatever
or serizeable class
public struct MatchingIntChar
{
public int myInt;
public char myChar;
}
public List<MatchingIntChar> foo;
why do you really want to keep it separated in 2 lists
when you need it combined/matching
Its not a well informed decision, its just what I did to make it work. Its for a spawn table for various things.
Now that I need to order the one list by the other im looking for solutions
just make the int/char inside 1 class/struct
yea its not hard. we sort the list using a value we can easily compare in the type.
thanks for the help!
If only this worked ```public struct SpawnChance<T>
{
public T type;
public int chance;
}
[CreateAssetMenu(fileName = "SpawnTable", menuName = "Scriptable Objects/SpawnTable")]
public class SpawnTable<T> : ScriptableObject
{
public List<SpawnChance<T>> spawnChances;
}```
I'm realizing the solutions that were offered wont work because the way I implemented the spawner requires two lists newDoodad = GameObject.Instantiate(Spawner<GameObject>.RollType(levelSettings.doodadSpawnTable.chance, levelSettings.doodadSpawnTable.prefabs)); because of the generic type.
this could work if you don't mind inheriting from that type to specify the generic type parameter. like
[CreateAssetMenu(fileName = "GameObjectSpawnTable", menuName = "Scriptable Objects/GameObjectSpawnTable")]
public class GameObjectSpawnTable : SpawnTable<GameObject> {}
would work. though it would get kind of tedious
I feel like at that point its the same as my current setup of having every spawn table being its own scriptable object of two lists.
but I could be wrong.
i mean, there would still be just a single list so you aren't attempting to sort one list then rearrange the other to match the new order of the first list
Im using a CinemachineCamera and wanna make a zoom in function using a script, but cant seem to find out how to access the lens part of the component?
iirc its inside a struct now
If no worky you are on V2 and not v3
ya if you're on 2 its just a public field 🤮
i assumed 3 because CinemachineCamera
used to be called CinemachineVirtualCamera
I guess "virtual" was confusing ppl :p
im still kinda confused, how would I modify it then? I started with [Serializable]
public struct LensSettings and got told primary constructors arent available in C# 9.0
uhh why are you declaring it insted of accessing it from the CinemachineCamera
perhaps Im more lost than I realized 💀
probably, which property you want to change exactly
eg if you want to change fov
cinemachineCamera.Lens.FieldOfView = 40;
etc
if i wanted to increase a sprites size without increasing the size of its other components, would i have to have it on a sepret object child on the gameObject? spriteRenderer.size doesent seem to work with 'multiple' sprites properly/I am not understanding it
I see, I tried that earlier and once again just now but it didn't seem to change anything
Not sure if it makes a difference (or if theres a better way to go about it other than changing fov) but the game's in 2D and I have it set to follow an empty located between the player and the cursor
well if its 2D and you tried that its wrong because 2D would be Orthographic which uses Size not FOV
if after that, its not working then you need to debug if the line runs at all
ah I see, I was mixing up camera terms and kept referring to my Lens as FOV and trying to edit it as such without even realizing it haha
All works now, ty!
Hey would anyone know how to prevent the player from sliding down on edges of platform like this?
I want to keep the capsule collider because I like how it interacts with all other aspects of my game but this small issue caused by the shape of the collider is getting in the way.
what do you want to do instead?
push it down ? or prevent from reaching that far into edge completely ? etc.
Hmm you could blend in a box collider when you stop moving
I would like the bottom half to act more like box collider but keep the rounded edges of the capsule collider on the top. Is it wise to use two separate colliders?
what aspects do you need from the top being rounded?
nothing prevents you from using 2 colliders
It's also possible to make a "rounded box" using boxes and a couple of capsules or circles
hell you can even make the bottom a skinny rectangle
When it comes to jumping I found that a box collider would clip a lot of edgers above and cause for a frustrating moments.
You should enable continuous collision detection on the rigidbody too
To avoid most clipping issues
Using a flat bottom collider will cause issues when moving on seams, and other places like walking up ramps. You can consider shrinking the collider when detecting it's over "air" (raycast), and then gradually increasing it back to its former size, this would let the player fall expectedly, and then also push them away from the wall if they try to go against it.
Alternatively, you could also add force upwards to keep the player afloat, by the offset that is the bottom of the collider and the contact point?
not sure if you use tilemap, but if you do make sure you also use compound collider for it to prevent tiny gaps
show that you have colliders setup?
Which composite operation would be best for that? Merge?
in the scene with gizmos showing
yeah iirc thats the default
forgot they changed it into an enum now lol
make sure the rigidbody it put on it is set to Static
and you u have used by composite in the collider
I have code set up for slopes. I might try disabling the flat bottom when the game registers the player is on a slope.
Hi, I dont have any idea on how to code so I'm in need of a script that supports vr and pc walk OR two seperate scripts if possible. ty
this isn't a place to ask for scripts, thats what google is for
here you get help with specific problem in your code
there are beginner c# courses pinned in this channel, you can get started there. then when you've finished learning the basics of c# you can do the pathways on the unity !learn site which will teach you how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
alright ty
i need help on why isn't my cam following the player and why is it so zoomed, thanks
Target
Main Camera
it's following itself
you also need to get vs code 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
• :question: Other/None
Anyone know why my camera is doing this? (it's probably something due to framerate, but it does this even without the blood particles (which shouldn't even be that demanding) sometimes) What can I try to fix this? Or is it only inside unity that the camera jitters so intensely?
show relevant !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Thanks for suggesting the compound collider. It fixed a boat load of issues I was running into.
Here the camera code: https://paste.mod.gg/uclyynvqmrao/0
A tool for sharing your source code with the world!
rigid body is interpolated
the using DG.Tweening; is for rotating camera movement while doing a wallrun (it works as intended)
don't multiply mouse input by delta time
https://unity.huh.how/mouse-input-and-deltatime
Thanks!!! Super logical solution.
You likely need to fix all compiler errors
If you are expecting to see something in the CameraFollow inpector
Otherwise, show your code
Start with configuring your !IDE 👇 so you actually see errors highlighted there
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
• :question: Other/None
Hello! I've got a PlayerController, and in this I've got my basic movement stuff like inputs, locomotion etc. I've also added swimming. Now, because it was possible for my character to keep jumping while holding spacebar, I added a coyote timer and jump buffer. Which then in turn caused my character to jump endlessly when jumping out of the water. Except, now my character cannot jump out of the water.
I was hoping that anybody could have a look into the code and advice me on how to solve this issue.
I've put all relevant code in the pastebin with descriptions.
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.
from first glance i'd say check jumpBufferCounter
make sure its resetting properly when exiting water
could possibly add a cooldown before allowing jumps after leaving the water
controller code is alot for someone to have to sift thru to find ur issue.. i'd suggest to do what i just mentioned.. debug those values.. find more specific of a problem and return if u can't solve it
Might be worth looking into the state design pattern
^ def should consider some sort of state-machine type pattern if ur getting into so many conditionals
i'd suggest a basic Enum state machine to start w/
break up ur code into states and use a switch statement to run each logic block respectively
it helps break down the responsibilities of your code into manageable chunks. You can also handle transitional moments easily with an OnEnter and OnExit method for each state
Interfaces will help this functionality if you fancy the above behaviour. Otherwise any state machine will be a helpful refactor
That makes sense, it does sound a lot more managable than having everything in one huge chunk.
enum PlayerState { Idle, Walking, Jumping, Swimming }
PlayerState currentState = PlayerState.Idle;
void HandleStateTransitions()
{
}
void HandleStateLogic()
{
}```
💯
I will make a backup of my current code (as it sort of functions) and get started on that, thanks @rocky canyon @bright osprey
ya, whats crazy is how Exponential it seems..
if u have 3 states ur characters in.. thats not too bad..
if u add 4.. well it just got a bit dicey
if u add 5.. well.. holy crap, hold onto ur cap
goodluck 👍
no worries - are you using any version control?
Not at the moment, I just back up in Notepad++ and sort the code with versions.
i like just duplicating entire projects..
renaming them and going onto to PrototypeVersion<insertnumber>
😂
I guess everyone has their own sorting systems. xD
yessir.. i still use Github too tho
for my main projects
sometimes its not worth having an entire repo.. if i just wanna try something out
the ^ master project of those duplicates does have a repo
just not none of the spin-off projects i call em
when ur developing i find that alot of the times its useful to expose as many variables as i can.. and then watch the inspector closely while i play-test
sometimes soemthing will catch ur eye that doesn't look or feel right..
i wouldnt make them public though 🙂 [SerializeField] is your friend for this
I noticed the same thing. I'm somewhat following a tutorial to clone World of Warcraft movement, but also adding my own code and experimenting with changing some stuff (which is for example the jump function)
ofc ofc, 😉
when im finally done developing i'll just get rid of the serializefields and go on my way
i like to make little clips like this and go back and re-watch them
i also tend to notice more after the fact.. than i do when im right there looking 👀
lol
don't stress urself out tho.. character controllers are no joke..
and they don't just fall out the sky..
to make a really good one (which is the backbone of most games) it can take a while
multiple iterations thru-out the projects life-time
Well. I've tried asking chat GPT to help me with converting everything to a state design pattern because I wasn't sure how to go about it. And it looks awefully complicated for the movement I'm going for, so it doesn't look like it's worth it. It would basically be starting from scratch all over again and throwing a week worth of work in the gutter. 😦 @rocky canyon @bright osprey
If your current design works I wouldn't sweat it
No worries! i didnt mean to tell you to throw all your work away 😂 might be worth creating a small side project and following a state pattern tutorial? if you want to take a break from the project 🙂
oh lord no.. dont do that
if u want to start using statemachines.. gradually step into them...
learn urself.. chatgpt gonna try to fk u over
hello
Oh yeah don't do chatgpt
I will try that. It looks a lot more versatile way to code. But for now I just wanna fix my current code so it functions first. xD
im kinda new to using unity
good plan..
don't sell ur car to buy gasoline.. yaknow?
i've never scuba dived
ChatGPT will give you one of these:
- a somewhat good answer, if the request is simple
- a bad answer that works
- a horrible answer that doesn't work
- way too complicated of an answer that may or may not work
the problem with chatgpt is over-reliance..
That too
not really it's fault.. but if it makes a mistake.. it needs u to point it out to it
b4 it runs off on a tangent
Never really understood the appeal of state machines for stuff like character controllers. It just seems like you're intentionally impeding yourself but maybe I'm just being shortsighted
Why limit yourself to very specific states
State machines have their place and time, if there's a lot of states to work with then it's absolutely useful
if u dont have a statemachine.. if u go and add functionallity.. u need to go and add it EVERYWHERE in the script..
if u have a good statemachine.. u could add it w/o worrying.. b/c the rest of the class could care less if that state is there or not..
I've used chatGPT to debug in the past for this code. But I learnt to back up my code a lot because it often sends me around in circles. That's what's happening right now with the code I got too.. because the code itself works right now, except the ability to jump out of water. Because I've got a jumpbuffertimer and coyotetimer and I've had to switch the way the game handles spacebar presses while swimming.
don't be scared to tell it how stupid its being..
because it doesn't "think" it just regurgitates what seems to be plausible answers to your prompts
Hah, that's the lite version?
XD
That's amazing 👏
yes! lol...
the regular version has sliding, crouching, climbing, and hurdling
the lite version can walk, sprint, and jump
thinking of 86in the jump eventualy
and to be honest..
i've been working in Unity for going on 4 years now..
my Character controller took about 14-16 months to perfect..
about 2 years ago i attempted to convert it into a state machine..
I failed pretty hard..
last year I got a state machine working that only had 3 states and a debug...
i'm still learning about state machines..
i finally figured out the bare-bones basic Enum type statemachine.. and then everyones like..
Ohh have u heard of State-less state machines.. u should try those... or better yet.. what about Behaviour Tree's?
point being.. they're not the simplest things imo.. and i definately wouldn't start out my journey by using chatgpt
-# disclaimer: ChatGPT
not sure how true all this is.. but since im here.. figured i'd see what it had to say about them
Fair enough. xD And well. I'm using a little bit of chatGPT to fill in the gaps I don't know, but the deeper I go, the more I don't know. Lol
thats totally fine imo.. just be weary.. and take everything w/ a grain of salt
https://github.com/SpawnCampGames/Resources/blob/main/101/ChatGPT_AI.md i wrote up a little doc last year about how I use it..
its mostly to refactor.. and to write boilerplate code now-a-days
but if ur smart about it.. its just a tool like anything else
I know the basics of C# so far, I've also done some stuff in Python. But these scripts for my game are my first time writing scripts that are this big.
yea i feel ya.. my first CC was enormous..
went from 1500 lines of code or so down to 7-800 after a few refactors..
ever heard of the SOLID principles?
I haven't before, no 😮
Code Structure / Fundamentals
- 📄 S.O.L.I.D.
- 📄 S.O.L.I.D. Unity E-book (Design Pattern)
- 📺 Unite Austin 2017 - S.O.L.I.D. Unity
heres a few sources.. the reason i ask b/c the first one.. and probably the most important for beginners is.
Single Responsibility
you want ur classes to stick to doing (1) thing.. thats MY job
if ur classes are doing more than (1) thing.. or are referencing many different scripts/systems..
it may be too much for a single class
That actually makes sense. I feel like the current script actually has a few things scattered around a bit too much.
if u keep it in ur mind while u code.. its a bit easier..
like here.. you can see that i have many different components all technically on my character controller..
each one doing its own thing... that way i don't have to worry about every little mechanic I have falling apart say i accidently break (1) or more of the other scripts
Composition is what its called i believe.. (when u have multiple classes on a single object)
each doing a single thing.. but together adding up to the total functionallity
its quite possible..
especially if you start feeling that way w/o being told by someone else lol
but don't take it too seriously at first..
alot of people learn better by having everything right there in a single class in front of them..
as long as u know its fine..
use a transparent image..
I try not to. And it's normal to be stuck on a problem for a few hours or even days with coding I've been told.
i typically use an Image component.. stretched to fill the canvas
and transparent.. (then i'll use the canvas sort order to put it on top of w/e im trying to block off)
I did the same as you showed way before
the problem is, it works for other UI
but not for other raycasts
it disables me from using draw card button for example
not sure what that is..
- you can scale it and position it however u want *
if u need it to block some things and not other things.. then change the sorting layer where its above the things u want to block and below the things u dont
but i can still click on chesspieces and cards
hmm.. not sure.. it was just a guess tbh..
what is it that ur trying to do anyway?
do u just need certain things to not be interactable?
It is preview of the card
when active, i want nothing else to be interactable, besides few things that are children
fastest way to do so is to block raycasts
i guess that makes sense
It works for UI butttons like you see on the right, i can't click end turnn
but i can still click on chesspieces
ya, i do not think UI is gonna affect world-space raycasts at all
are you using a raycast or
I'll tell you in the sec, it was a long time since i did this
i mean what allows to move pieces
i'll need to make note of that..
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
clickPosition = hit.point;
OnInputRecieved();
}
}
}
public override void OnInputRecieved()
{
foreach (var handler in inputHandlers)
{
handler.ProcessInput(clickPosition, null, null);
}
}``` I believe it was this
i have a feeling i'll be trying to remember that
or needing to atleast
u just need to toggle off ur 3D/Interactive raycast script
when u have ur cards pulled up or w/e
yea, i can, but isnt there a way to just block all world space by UI?
Lookin at cards -> .enabled = false;
Lookin at chesstable -> .enabled = true;
that'd be a nice easy way that i think i would do
maybe w/ a world-space canvas
sitting in the path of the raycast lol
the image/canvas does work pretty good to block other UI elements tho ^ like something like this
just do something like this:
public GameObject uiPanel; // Assign this in the Inspector
private Vector3 clickPosition;
void Update()
{
if (uiPanel.activeSelf) return; // Prevent detection if UI is open
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
clickPosition = hit.point;
OnInputRecieved();
}
}
}```
i did already, but thanks XD
if that UI panel is Open -> return(skip rest of code)
if that UI panel is Closed -> run the GetButton/Raycast code
private Vector3 clickPosition;
void Update()
{ if (cardWrapper.isPreviewActive)
{
return;
}
else if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
clickPosition = hit.point;
OnInputRecieved();
}
}
}
public override void OnInputRecieved()
{
foreach (var handler in inputHandlers)
{
handler.ProcessInput(clickPosition, null, null);
}
}```
good stuff
that's how i always handle that stuff
Also for some reason i heard that using things like public CardWrapper cardWrapper all over the code isnt good. Why?
its better to have hands-on with the code and know its blocking it
than just hope something will do it
idk, i haven't needed to ever use a wrapper class
ive seen both sides of the argument tho.. (no clue why or whats better)
welcome to OOP
I've used classes as tags/layers...
if (Physics.Raycast(ray, out hit) && hit.collider.TryGetComponent(out MyInteractable interactable))
{
Debug.Log($"Hit interactable: {hit.collider.gameObject.name}");
}```
with `MyInteractable.cs` being just an empty class i attach to gameobjects.
im not 💯 sure thats the same thing tho
I mean, this part is tutorial code that i expanded now to 2x its lenght, i was asking about the refferences, why aren't they good?
OOP?
Object Oriented Programming
yes
the sound u make when someone knee's u in the stomach
Ah, forgot the shortcut
"wrapper class" You're pretty much creating an object for it
never knew it had pillars.. got me something to read! 🌈 🌟
Inheritance < Interfaces
Hey guys, having a problem when switching scenes with cinemachine.
Having three scenes
1. Systems (Persistent with MainCamera and Cinemachine Brain)
2. MainMenu (3 Cinemachine Cameras)
3. Gameplay (1 Cinemachine Camera)
Starting with Systems and MainMenu, everything works fine and I can transition between all 3 Cams.
Loading Gameplay and unloading MainMenu
SceneManager.UnloadSceneAsync("MainMenu");
SceneManager.LoadSceneAsync("Room1", LoadSceneMode.Additive);
and loading back into MainMenu
SceneManager.UnloadSceneAsync("Room1");
SceneManager.LoadSceneAsync("MainMenu", LoadSceneMode.Additive);
I can't transition between the Cameras anymore.
GameObject with Main Camera / Cinemachine Brain stays persistent via DontDestroyOnLoad though.
Thinking over it, this could be more a cinemachien question so I'll ask it there 😄
Probably need to tell cinemachine to search the scene again for those virtual cameras
Hmm they may actually subscribe via a singleton actually when they awake(), or well that would be the more reasonable way
Yoooo how can I configure my 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
• :question: Other/None
Was just an idiot => https://discussions.unity.com/t/cinemachine-live-blend-not-progressing-past-0/937159 😄
Nevermind, timescale got me
I have a Problem with my UI Dropdown Menu clicking on the white menu bar blocks my raycast system from reaching the tiles underneath
But when my dropdown menu is open, no matter where i click, it reaches the tile underneath it
Opening the dropdown works just fine
UI doesnt block raycast
You have to specific check your cursor is on UI
and if it is you return
but when i click on the arrow again to close it i click on the tile beneath
Use the event system to handle your tile clicking stuff instead of your current system
And you'll get the blocking behavior for free
I thought "Raycast" target would be enough?
Only if you're using the event system for clicking tiles
(and it also works always, except when i open the drop down)
yes because UI doesnt block the Physics.Raycast
only if you use a Physics Raycaster on the camera then it uses Event System for ray as with UI and its covering it that way works
public bool IsMouseOverUI()
{
return isMouseOverUI;
}
public void OnPointerEnter(PointerEventData eventData)
{
isMouseOverUI = true;
}
public void OnPointerExit(PointerEventData eventData)
{
isMouseOverUI = false;
}
i tried doing it this way
Yes that's... part of it
oh your tiles are UI?
But this is wrong overall
No
The actual tile handling should use that stuff
My tiles a 3D objects
Not just setting some UI bool
fair
yeah you don't need all that, just slap a physics raycaster on camera
Yes use IPointerClickHandler etc for them
put this component on the camera, then you need to handle the clicks on the Tile itself
but how does he know if i clicked a Gameobject or UI element?
It just naturally works on the first thinkg it hits?
it knows cause of the PhysicsRaycaster uses the same raycast (Event System) as Graphic Raycaster so it will just work ™️
you will handle the Tile logic on the Tile OnPointerClick instead
hover and whatever else
Ah nice thanks!
Hey, this chat usually helps a lot, so I want to ask here first. If i follow this tutorial: https://www.youtube.com/watch?v=IVj7-usBxHo&t=30s Could this be used to create a trail of blood that my player leaves behind? The thing is, I want it to be dynamic so the player not only bleeds but the game sees what asset/what angle the player is standing on so the blood stays on the said asset depending on what part of the player is touching it and what angle the asset is at. Kind of like splatoon paint, but that spawns from the player at all times. Imagine shooting a paintball at something. Or is this too hard of a task for a beginner and I should forget it? Or the trail that Super Meat Boy leaves behind when he touches something but in 3D
Also, this is nothing too realistic, I'll just slap on a super low effort pixel shader on top of everything at the end...
Today we are going to see how to create a procedural Blood effect (no textures). We are going to use VFX Graph to spawn the blood and manipulate it's motion and then we use Shader Graph to create the Blood Shader.
I used this blood effect here in the Toxic Waterfall : https://youtu.be/uOhWT6TxZgE
Enjoy!
Would be awesome if you wishlisted ou...
you can probably achieve something like that with decals..
nav did something like that (paintballs painting across meshes)
Particle system + spawn decals on collision is probably the easiest way
Havent used VFX graph's collisions enough to comment on that one
Thanks for the replies! Are there maybe any guides close to what I am trying to achieve that I can check out?
The unity manual probably gets you started
So that's a 
I dont know how you learn best 🤷♂️
I can't find the help channel in this discord so appologies. I'm wondering how to "unfreeze" time in the editor?
None of my particle systems will play right now
I used to be able to preview my particle systems by clicking "restart" here
but now nothing happens. Playback time stays at zero
(For both of you, #✨┃vfx-and-particles exists)
you can leave a Trail of decal projectors and that will stick to whatever surface you want
you will need to code that in
raycast onto the surface hit then apply the decal projector with a slight offset
you can use particle system too but Decal Projectors can be pushed to GPU unlike particle system (performance boost when spawning a lot)
VFX graph doesnt work well because it runs on the GPU while unity collisions are processed in physics / CPU so they cant interact
yea, probably raycast be ur best bet.. esp w/ all the weird edge-cases u were trying to describe
can get normals and stuff and angle ur projectors how they need
Is there any specific tutorial anyone recommends or has in mind regarding procedural generation with rooms?
Hey guys, I have a grappling gun that has a grapple wire you can physically see. The problem is 2 of them are coming out. I can see the second in the editor so its definitely being executed by script.
Ill send the script, give me a moment
depends
there are some from SunValleyStudios that are ok + others
https://www.youtube.com/playlist?list=PLcRSafycjWFenI87z7uZHFv6cUG2Tzu9v
The one attached is the wire I can see in the editor. The wire offset of the gun is what the script is doing
alright ty, I had that one in mind but wanted to double check before I commit to it in case anyones done it b4 🙏🙏
https://pastecode.io/s/bo9svvd7 grapplegun script
https://pastecode.io/s/x7buatd1 gun rotating with wire script
https://pastecode.io/s/tzu4unx8 gun wire wiggle animation effect script
The wire is being active or shot out in the grapplegun script
anyone know how to use snap points in unity 6 i cant find anything online...
im trying to snap food onto a tray
see "Snapping"
i dont mean how to position objects
i meant stuff like socket interactors
but the using snap points
does SetActive(false) immediately stop the execution of code? if i have a method that returns some data after setting the game object its on to false, will that return still execute?
No to the first question
Basically all it does is skip that object when it comes to calling update on things
awesome, thank you