#💻┃code-beginner
1 messages · Page 640 of 1
Oh sweet thx
!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.
does anyone know whats wrong with my camera script like when i click, it makes my screen move randomly and i cant zoom out or anything https://paste.mod.gg/thgjrmhhxqqh/0
A tool for sharing your source code with the world!
no no i meant by like when i click it shifts my camera to the right and i cant move it back
Well, you're moving it here:
else if(Input.GetMouseButton(0)){
Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
Camera.main.transform.position += direction;
Vector3 clampedPosition = Camera.main.transform.position;
clampedPosition.x = Mathf.Clamp(clampedPosition.x, panLimitMin.x, panLimitMax.x);
clampedPosition.y = Mathf.Clamp(clampedPosition.y, panLimitMin.y, panLimitMax.y);
Camera.main.transform.position = clampedPosition;
}
So it must be a bug in this logic/math
Step through the code or use logs to see all the relevant values at each step
And make sure they're what you expect
oh i have another question btw
for my laser tower i set the color and new material to purple but how come the laser its shooting out is white?
line renderer:
Are you sure that's how the object in the scene at runtime is set up?
Can you pause the game when you see the white laser, select the object in the scene ant take a screenshot of the whole editor
So, you see that the material color is white
whats causing that
Nothing. It's just configured to be white apparently.
is it because its a prefab?
I don't know. That's how you configured it.
should i make a new material then and then replace it?
rb.AddForce(0f, 0f, 0f, ForceMode.VelocityChange);
This code should in theory stop my rigidbody from moving entirely right? My rigidbody is currently only affected by gravity and my movement and jump forces, yet running this line of code doesn't seem to do anything. I want my rigidbody to stop moving entirely when I let go of a key.
hey everyone how do i prevent an action happing in my game through a UI click? I have a UI that's always on during gameplay, but if you click the toolbar, things happen in the game world
AddForce, as the name implies adds force. you're just adding a force of nothing
set the velocity directly if you want
You can. Or modify this material.
It seems like line renderer expects a sprite material/shader by default. Then it's color property should be used properly.
hmm the best idea rn would be to add a new material im asuming
I'm trying to zero out a jump if the player lets go of the jump button. I assume my best bet is to addforce(Of, add -rb.linearVelocity.y, 0f) then?
sure that should work. usually if i need control like this id just directly set the velocity to be what i want
is it possible to change the color of a mobile/additives/particle new material in the inspector?
Add force of nothing seems like it would change nothing. Dunno for sure but the name certainly implies it. Seems like you should instead manually set the velocity
lol i get ya
where is the code question?
nvm
trying to make two ridgid bodies walk through each other if they collide from top, but also turn directions if colliding
do you have to worry about errors unity sends in the console but it doesnt affect your gameplay?
from left to right
{
if (other.gameObject.tag == "Player" && tag == "Stunned")
{
// Destroy(gameObject);
}
if (other.gameObject.tag == "Up" && other.transform.position.y - 1 < transform.position.y)
{
dir = -dir;
rb.linearVelocity = new Vector2(8f * dir, 10f);
//transform.position = new Vector3(transform.position.x, transform.position.y + 1/4, transform.position.z);
tag = "Stunned";
stuncounter = 10f;
}
if (other.gameObject.tag == "Enemy" || other.gameObject.tag == "Stunned")
{
dir = -dir;
rb.linearVelocity = new Vector2(4f * dir, dropspeed);
//other.rb.linearVelocity = new Vector2(movespeed * -dir, dropspeed);
tag = "Stunned";
other.tag = "Stunned";
stuncounter = 10f;
}
//else
{
//Physics2D.IgnoreCollision(other, coll, false);
}
if (IsBelow())
{
//dropspeed = -4f;
}
}```
use !code next time if its big blocks
📃 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.
i wonder how do i use UVS to script
like can i choose UVS script or normal C# script?
i dont know where to enable that
UVS ?
Visual Scripting ?
visual scripting is okay for learning, not very scalable
but if you like learning with graphs it helps
the logic / components are the same
Visual scripting is node scripting. Unless we're misunderstanding you
yeah but i mean how do i get that screen, i dont know where to get the node screen like shader graphs
or theres something i can do to mono behavior scripts?
im sorry im so new to this 😔
You would probably need to install the visual scripting package.
oh thanks
thank you so much now i see theres a visiual scripting there i can create
Is there a way to deform a mesh using Unity Spline tools. I have been trying to code deformation spline mesh use a C# script with Unity's Spline tools but any tutorials covering it are to vague or don't explain well enough for me to understand the system. As well as they are wanting to generate a mesh instead of using a premade mesh to instance and deform along the curve. I wanted this for castles walls. so i can bend them to the towers. I have created something similar in unreal but now that i move over to unity I can't figure it out.
This is a very specific question. The best we can do is help you with interpreting the tutorial correctly.
But you'll need to share the details of the tutorial and your current progress following it.
I was using this tutorial. But it created a mesh inside of useing a premade mesh and hides or changes code in between explanations. Which is very frustrating because it one and the only videos that go over the unity spline code.
https://youtu.be/ZiHH_BvjoGk?si=tZQAL7yUcTnW1mTC
Roads are more common in videogames than you might think so in this episode we'll look at how we can use Unity's new spline package to build out a tool that procedurally creates a road mesh along a spline, and ALSO handles intersections at the same time. While we're at it, we might even decorate it to look pretty using URP Decals too!
Get the p...
How would you implement a system where a bunch of gameobjects move randomly in 2 dimensions within a certain boundary?
My first thought was generating waypoints but I need to also stop the objects from colliding with eachother
soo you want the movement to be like a bee or a fly?
Just straight direction for now
oh ok
Basically if they'd collide, they would pick another random direction
then create an empty game object or a raycast to see if anyone is near then change the direction to the opposite direction
I was testing something like that but it gets messed up if a bunch of them gets very near to each other
I did not do with raycasts though, just colliders
try using a raycast
They are the rotations what I need and what I have I'm trying since last 3 days polish it's rotation but it is too hard for me now...
Sorry for photo but I'm using phone to chat... Can anyone help me out... I tried to fix it my the help of AI bots available there but they are still too dumb I need real human's help...
is this just how small banner ads are?
what is this from?
just a empty untiy project i was using to figure out how to add ads into
Nope it has a fixed area on each screen which should take up one screen width
ty
the size given for ads in ironsource for example are not in pixels but are "dp":
https://developers.is.com/ironsource-mobile/unity/banner-integration-unity/#step-1
so whatever you were reading check again more carefully
just don't use photos of screens
you can use the browser version of discord at https://discord.com/app
see below
!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.
and what are you trying to achieve exactly? make it rotate to point to where the mouse is?
void Update()
{
float moveDelta = moveSpeed * Time.deltaTime;
float rotateDelta = rotateSpeed * Time.deltaTime;
movement = Vector3.zero;
movement += Input.GetAxisRaw("Vertical") * moveDelta * transform.forward;
movement += Input.GetAxisRaw("Horizontal") * moveDelta * transform.right;
if (Input.GetKey(KeyCode.E))
movement += moveDelta * transform.up;
if (Input.GetKey(KeyCode.Q))
movement += moveDelta * -transform.up;
when i press W and E together, the object moves foward and up, and when i press W and D together, the object will move forward and right
but when i press all 3 together, itll only move in 2 directions at a time
anyone know whats causing this?
i put Debug.Log statements and it doesnt even register that E is being pressed when i press W D and E together
when i changed it from KeyCode.E to KeyCode.LeftShift it worked 🤔
This behaviour could be down to your keyboard and how it handles rollover. It might not support x number of keys, or only in certain combinations (eg function keys)
Some keyboards have a limit of simultaneously pressed keys.
oh
thats a shame
thanks tho
oh it actually works for other key combinations too
https://www.mechanical-keyboard.org/key-rollover-test/
just found this 👌
does unity not have splines in 2d?
I am using unity 6 and cant find splines inside package manager nor in components
btw not for animation
I want it in the world
1- Not a code question, shouldn't be in here
2- There is no "2d" version of Unity, opening a 2d template is the same as opening a 3d template, just with 2d packages imported already
In 2D you don’t get the Z-Axis.
You use the same Splines package as for a 3d game.
Z-axis doesn't go anywhere and works the way with 2D and 3D
2D still has access to the Z axis. It doesn't disappear.. and you'll still use it to rotate objects in a top down game
Does advertisment legact still work at the same effectivness as it used to? i could not get levelplay to work for the life of me
This is a code channel, and that is not a code question. You could try in #💻┃unity-talk , but you're unlikely to get an answer for this.. best posting on the Discussion forum
oh frick wrong channel my fault ty
if for mobile ask in #📱┃mobile . level play should be reliable as long as things are installed correctly
how do i give a rigidbody friction? i tried applying a physics material to their collision and setting the friction value to like 1000 and it didnt seem to work
note that for friction to actually take effect you must be moving the rigidbody in a physics friendly way
im using .addforce
show the setup and the code
this good?
well for one, !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.
arent all the code colors and the lines and other info the ide gives important?
syntax highlighting is important, which is why the options listed all offer syntax highlighting.
we soo smart we dont need pretty colours 😎
lol
but also with your giant vs code next to unity your inspector is shrunk down making the information in that harder to read
you also need to show the physics material
okay now show the object it should be colliding with to use that friction
ohhh,,,
i need to settup stuff with the plane?
well without a material it should be using the default values which i believe are 0.6 for both. i wonder if maybe your friction is just way too high because that is a seriously unreasonable number for friction in your physics material
ah yeah, the docs say it is a value from 0 to 1 so 1000 obviously isn't correct
i dont understand why i cant get any sort of response outta it
i did try lower values
negative feels like the wrong way to go
were those lower values also above 1? because 1 is the maximum it uses so anything above that is literally exactly the same
have you tried giving both objects the physics material?
right because there's 0 friction. so what about 1 is not working? like what is it doing that you don't expect it to?
no change.
nah both do that
every value does ice physics
well you've also got 0 drag on the rigidbody which is basically air resistance. and you are giving it a force of 10 which is kind of high for an object with a mass of 1
for the sake of testing, try making a plane at a 30 degree angle, put a rigidbody sphere above the plane, and give both the material. if the sphere slows down, the material is working, and its likely an issue related to your code
if the physics material doesnt do anything in a test like that, then its a physics problem
well i dont want much air resistance
i want floor resistance
for the character to jump and stay moving till they hit the ground
you still need drag
well, ill give it like 0.1 or something but i still wanna increase floor friction
is this what you want?
okay and friction can only do so much with 0 drag and way too much force
okay, okay, if friction like multiplies drag when colliding with stuff then it should still be working
friction value doesnt do anything but drag does
Do I need to use Time.deltaTime for transform.Rotate(Vector3.up, angle) ?
I vaguely remember I won't - I don't know where I got this from though
Do you want it to rotate by angle degrees per frame, or per second
hey does using character controller functions in update instead of fixed update cause any problems?
character controller is based on Update loop so that should be used instead of fixedupdate
oh ok thanks.
Hello, I want to use event Action in a class Ladder to call a method in an another class PlayerController but it doesn't work.
I want to add the method to my Action with the instance of the PlayerController class.
So, this a part of my code :
Ladder :
public event Action<bool> LadderEnter;
private void OnEnable()
{
LadderEnter += PlayerController.Instance.ClimbLadder;
}
PlayerController :
public void ClimbLadder(bool isOnLadder)
{
if (isOnLadder)
{
Debug.Log("On Ladder");
}
else
{
Debug.Log("Off Ladder");
}
}
What does "doesn't work" mean in this case
where do you invoke event?
Unity send me this error when I run my game : ArgumentException: Value does not fall within the expected range. Ladder.OnEnable ()
Here:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
LadderEnter?.Invoke(true);
Debug.Log("Player entered ladder trigger");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
LadderEnter?.Invoke(false);
Debug.Log("Player exit ladder trigger");
}
}
private void OnEnable()
{
LadderEnter += PlayerController.Instance.ClimbLadder;
}```
this should be in the PlayerController script
you did it backwards
private void OnEnable()
{
LadderScript.LadderEnter += ClimbLadder;
}```
if you need to insert PlayerController.Instance that also kind defeats the whole point of Ladder script being independent , why should ladder care about calling any method in other script, it should only care about Invoking the event, how other scripts handle it is a separate matter.
Why it isn't work ? Because, LadderScript.LadderEnter call the event action and PlayerController.Instance.ClimbLadder call ClimbLadder method. So, it will work in both directions no ?
If PlayerController is a singleton, I don't really know why you need an event at all
Seems more like you should just be calling PlayerController.Instance.ClimbLadder() in the OnTrigger methods
Yes, not wrong 😭
So, when are you using Action event ?
Events would be useful when you want this object to be agnostic to what is subscribing to it. Since this object already handles the subscribing, there's no benefit to it
What mean agnostic ?
Like, if you know that something is gonna care when something gets on this ladder, you'd make an event for like PlayerEntersLadder, and then other things can subscribe to it that this object doesn't have to know anything about. Like, if you wanted all your enemies to switch to ranged weapons when the player gets on a ladder, you could have an event that fires, and then whatever enemy script can subscribe to it and know "okay time to change weapons"
If the script with the event on it already has a reference to the thing subscribing to it, you should just call the function on it.
Events should be used for basically "one-way data flow", where managers send data downstream but never need to care about what uses it.
something that isn't tied/depending on something else
"yo just letting anyone who this thing just happened if anyone cares"
a good example of an event might be a wave based game starting a new wave, where the wavemanager might not care who wants to know that a new wave just started but is still open to letting people know that it did happen if people are interested
Yeah, if your object doesn't care who gets the message, you should use an event.
If a specific object is meant to respond to it, you should just reference that object
flashback to my birthday :
Also worth pointing out in some cases it's totally valid for both to happen, where going off my example the wavemanager might have some direct handling of what happens when a new wave starts and informs strangers that it happened if anyones around to listen
So, we can use Action event just to let know other scripts that want to know this information but that's not obligate to get this action event ?
But, if you create an action event, it means you want to an other object get the information that the action happened ?
If you could imagine your object standing up on a pedestal with a megaphone and shouting into your codebase "Hey everyone, this thing happened" and then just leave, you can use an event for it
So, you will often use it if you want to do something to different objects and not a single one ?
You use it so the thing standing up on a pedestal with a megaphone doesn't have to explicitly tell the people listening
events keep both parties relatively seperate from eachother
not necessarily
well except the subscriber always knows about the Invoker / Event raiser
its a 1 way instead of 2 way (bad tight coupling)
Why call a method by instance of an object is a 2 way so ? It just call a method but the object that call the method doesn't really have something in return
Another game related example would be in Minecraft when it's officially "day time" after a night. We don't want the class handling the time of day stuff to mess with:
setting all enemies on fire
making sure beds can't be used
firing off relevant achievements
make bees start leaving their hives
etc.
because all these things aren't really the time of day's scripts responsibility to mess with. Programming wise the sun shouldn't tell bees what to do or set zombies on fire (aztec wise tho idk).
For this reason the time of day script can just have an event saying "hey it's daytime now" and then the enemy class, bed class, hive class, achievement manager class etc. can handle their own responsibilities in response
if you're using a static Instance to call public method, if thats what you mean.. You are still doing a 1 way which is better than 2 way..the
(Player -> Ladder)
(Ladder -> Player)
This creates tight coupling which can be considered bad
if you ever destroyed Ladder, Player would also need to be fixed/modified thats why 2 way is generally bad
The bad practice in that though is why should a Ladder care about the player methods? it should only track its own state and others might want to be on notice about it
Oh okay, I got it
|| Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
engineSFX.Play();
}
else
{
engineSFX.Stop();
}
can someone tell me why this isn't working, I added an audio source to the player, turned off play on wake, and there are no errors, why won't this work?
Where is this code located
you need to think critically about what this snippet is supposed to be doing versus what you've actually written here
I suggest you add a Debug.Log("Play") and "Stop" in those
in my player controller script
If this is in Update, it's going to run every frame, and GetKeyDown is true the frame you press a button and false every other time
this is in update
Put a Debug Log in each condition before you call the functions, you should see what the problem is
ok
you're right, when I press one of the buttons, it says "play" once and goes straight to "stop", what should i do then?
Well, that would make sense. This code is running every frame. GetKeyDown is true for exactly one frame
So, you tell it to play, and then on the next frame, none of those button presses are true, so it stops
ok, so where do I put it then?
When do you want it to stop
when you're not pressing on one of the buttons
so if you're moving, play audio, if you're not, don't
So you'd want to check and make sure every button in your list is not currently held.
This would be significantly easier if you used GetAxis instead of checking each button individually
{
Debug.Log("Play");
engineSFX.Play();
}
else
{
Debug.Log("Stop");
engineSFX.Stop();
}
``` It's not this then
You'll want to make a vector that contains both horizontal and vertical.
If that vector is not zero and the sound is not currently playing, play it.
if that vector is zero and the sound is currently playing, stop it.
Ok, let me try
so this should be the variable?
this will not work
what should I replace it with then?
just remove private
you can't add access modifiers to local variables
(assuming you're adding this in Update)
ok, what's next, becaue I tried to do an if statement saying:
if (movement != 0)
{
Debug.Log("Play");
engineSFX.Play();
}
else
{
Debug.Log("Stop");
engineSFX.Stop();
}
i think i figured it out, the collider is still a sphere, so its actually rolling and not having any friction at all
The vector (0,0) is not the same as the value 0
You can't check if a vector is equal to a float
I don't get it, so I change the 0, to (0,0)
it is, it's red
okay good
You should compare the vector2 to another vector2
vector 2 that is 0?
sure
if thats what you want to check
if(movement != new Vector2(0, 0))
but that silly so we can just use
Vector2.zero property
if(movement != Vector2.zero)
ohhh, that makes much more sense
so like this?
also not generally You don't compare floats with == but here Unity overrides the == to check approximation for you since its inside a struct they made
Now you need to add in the "And the sound isn't already playing" condition to that first if
so I shouldn't usually use ==?
not for floats
right
floats like Vector2?
vector2 is a struct of 2 floats, so unity takes care of it for you
by float meaning
float someValue = 1
someValue -= 1
// this could be 0 but can also be somehow 0.0000001
so doing if(someValue == 0) is might come up false
floating point imprecision
so like this?
ahh ok
Rather than else you are going to want an else if and a specific condition for when to stop
Otherwise it will stop any frame that it did not currently start which means it will only ever play for one frame
ok, let me do that
I was going to use ==, should I use something else instead?
for which ?
for the else if
when comparing floats always use > or < or combined >= <=
or Mathf.Approximately
like i said, this only applies to singular floats.. not a struct like v2
oh right, forgot about that part
Vector2 is already compared with an epsilon when you use ==
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector2.cs#L369C9-L369C64
how do I call it, if it can't be called?
Took me forever I was looking just for this 🫡
You can't call methods in the field initilizer , as it says
create the v2 variable as a member field but assign the values in Update
You could convert it to a property by using => but not sure if that's what you want
Probably better to stick to fields for now
private Vector2 movement;
..
void Update(){
movement = new (Input. etcc.```
https://paste.mod.gg/vazecjnmgson/0 does this make sense?
A tool for sharing your source code with the world!
so like this (I'm not experienced with memberfields)
whats the context?
No, GetKeyDown is true for only one frame
So it's very unlikely that you hit the key exactly the moment you collide
yeah you would need some type of spiderman skill to hit that
im trying to get current velocity so i can give a little boost when theyre at 0 speed
This is also not valid C# cs if playerBody_Ragdoll.GetAccumulatedForce >= 0
and i wanna get jumping to only happen when touching collision
does unity have like >=
its methods need ()
or is there a better way to write it
so it does okay
yup. Although the prefix m_ is generally not needed
if its a camelCase variable its very likely to be a field
oh ok, yes it works, thanks!
i dont really understand it
then why did you use the function lol
well look how you wrote and look at the docs
pertaining to how methods are used.
cause im just trying stuff lol
Hey! New to coding C#, working through the tutorial and asked to replace code. Opening the PlayerController file gives me this (attached). What am I doing wrong, how do I continue? I have no idea if that is even the right thing. I'd greatly appreciate help 🙂
make sure you configure your 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
{
var playerVelocity = playerBody_Ragdoll.GetAccumulatedForce();
if (playerVelocity = UnityEngine.Vector3.Equals(0, 0, 0))
{
playerBody_Ragdoll.AddForce(playerMoveInput * 10, ForceMode.Impulse);
}
else
{
playerBody_Ragdoll.AddForce(playerMoveInput * 10);
}
}``` i think this is better
cant really figure out how vectors are used in ifs tho
in what way ?
= is assignment not comparison
i tried to do vector >= 0, 0, 0, but vector cant be converted to ints
C# beginner courses wouldn't hurt
and if your !IDE is not underlining your errors in red then it needs to be configured 👇 because that first if statement contains a 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
it is dw
yeah this is nonsense as far as the computer is concerned you're comparing vector>0
vector is a struct of floats
but arent vectors defined that way? new vector3 (0, 0, 0)
it sounds like they want to probably compare its magnitude against a single value to determine if it is above a specific speed threshold rather than comparing an entire vector3 to 0
yea but thats not how you wrote it
im saying if its defined that way cant it also be like undefined that way too
i just need to read if the vector3 is a certain value lol
yes then you probably want magnitude
alright,
which is a single number
also there is no type inference that can be done in an if statement, probably because you can override Equals in any type so anything goes
you can do (cat > cat) but if you wanted to can do (cat > dog) if you overrode the equality check for dog to be compatible with cat . The compiler doesn't know the type you want to compare cat with is cat ? or dog ? or something else
(i know its a stretch but I think you get the point lol)
yeah i can tell by your broken code exactly what you want, and that is it.
sorry, im still pretty new to all this.
how different is it from like python?
dynamic language vs statically typed
also incredibly different syntax for many things
i mean, i am learning unity rn but ig ill look at a small c# tutorial
player velocity is the Vector3. So that would be the one that contains such property
your IDE would should you these properties when using the . operator
Hello
Intelissense from Rider suggest me to change float by var in this case : float deceleration = _isGrounded ? stats.groundDeceleration : stats.airDeceleration;
airDecelration and groundDeceleration are float so why use var if I know the type of variable it will be in every case ?
rider will always suggest using var for local variables, it has nothing to do with the type. var is also not a special type, it's just a placeholder for the compiler to add the correct type so you don't have to. it's still a float variable, it's just using shorthand for the type in its declaration
But for the readability, it's better to direct tell which type is the variable no ?
thats pretty funny prioritizing IDE visibility vs clear intent
that is entirely personal preference. you can turn that off in the settings if you don't want it to do that.
I just wanted if it was really a sense behind this suggestion 😭
Imo its mostly better when the type is clear in the part after it, otherwise probably better to communicate the type
sometimes explicitly defining the type can be repetitive/redundant
although IDE does tell you the type
if you look at it without ide it can be confusing
in Vector2 a = new Vector2(); you say Vector2 twice
you can shorten it by inferring the type, var a = new Vector2();
or by inferring the constructor, Vector2 a = new();
groundDeceleration the variable name makes it somewhat clear that its a number. But do we know what type of number it is without IDE ? nope
it could be an int or decimal or double for all we know on assumption (ofc in unity we mostly use float)
but does it matter there, probably not
ClientNetworkManager.LoadMainMenu () (at Assets/Scripts/Client/ClientNetworkManager.cs:279)
ClientNetworkManager.Start () (at Assets/Scripts/Client/ClientNetworkManager.cs:42)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <314938d17f3848e8ac683e11b27f62ee>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <844019a3a067481c8d9cb70c7a2ba447>:0)```
Genuinely wtf 😭 i do not understand why the nullreference happens
ive tried adding more debugging things but just cannot figure this out (yes MainMenu is added to build and all the gameobjects are configured correctly)
[SerializeField] private string mainMenuSceneName = "MainMenu";
``` async void Start()
{
if (SteamAPI.IsSteamRunning())
{
p2pSessionRequestCallback = Callback<P2PSessionRequest_t>.Create(OnP2PSessionRequest);
await ProcessSteamPlayerInfo();
}
else
{
Debug.LogWarning("Steam is not running. Using PlayerPrefs data if available.");
ProcessPlayerPrefs();
}
LoadMainMenu();
Debug.Log("Client Ready");
}```
```private void LoadMainMenu()
{
Debug.Log($"Scene name to load: '{mainMenuSceneName}'");
if (Application.CanStreamedLevelBeLoaded(mainMenuSceneName))
{
string sceneName = mainMenuSceneName;
Debug.Log($"Loading main menu scene: {sceneName}");
SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
}
else
{
Debug.LogError($"Scene '{mainMenuSceneName}' is NOT in build settings or misspelled.");
}
}```
we cant see lines numbers when you post it like this..
nor is it posted in its entirety to be able to paste it and get 1:1 line match
Post !code using any of the links provided. We cannot tell which line the error is on from Discord code blocks . . .
📃 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.
ahh yes sorry hold on
yea mb
wait sorry hold on
so if i initialize my mainmenu scene could the null reference be from something inside that actual scene
its not just saying that the null reference IS the main menu scene like it doesnt exist rather it could be something inside
whatever is on line 279 in ClientNetworkManager.cs is null
other then that we dont know why if we dont even know whats on that line and what to check
oh right, well let me try paste it but here is whats on 279 Debug.LogError($"Scene '{mainMenuSceneName}' is nOT in build settings or misspelled.");
i will see what context is needed
and line 42 is LoadMainMenu();
this shouldnt throw a null reference
it would throw whatever Error you wrote there
NullReferenceException implies something was trying to get accessed on a null object
can i attach as file
or do i need to use
use the links given
ok
a powerful website for storing and sharing text and code snippets. completely free and open source.
That line wouldn't throw a NullReferenceException. It might have changed since you've added or removed code. Try clearing the console, then get the error again and see what the line number is
thats what i mean yea i dont understand how its throwing errors...
just cleared console and its still the same
ClientNetworkManager.LoadMainMenu () (at Assets/Scripts/Client/ClientNetworkManager.cs:279)
ClientNetworkManager.Start () (at Assets/Scripts/Client/ClientNetworkManager.cs:42)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <314938d17f3848e8ac683e11b27f62ee>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <844019a3a067481c8d9cb70c7a2ba447>:0)```
Are you sure the code has been saved and recompiled? Save it again, then restart Unity to ensure it recompiles
In my code, i have a thing that sets an item to the values of another item, then assigns the other item to the original item's ref.
currentitem.setitemvalues(otheritem);
other = currentitem;
other is a item that was passed to the method using a ref keyword. Why does Visual Studio assume this is an unessecary assignment? I am using the item in a ton of places where the other item comes from.
ill do that, it says its saved in vscode but yea let me restart
Are you using it, or just setting it
oo the error changed
ClientNetworkManager.LoadMainMenu () (at Assets/Scripts/Client/ClientNetworkManager.cs:275)
ClientNetworkManager.Start () (at Assets/Scripts/Client/ClientNetworkManager.cs:42)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <314938d17f3848e8ac683e11b27f62ee>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <844019a3a067481c8d9cb70c7a2ba447>:0)
Line 275 now
That also doesn't look like it should be able to throw that error. Does the log the line before print? What sceneName does it give?
275 on ClientNetworkManager
SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
yeah that would not throw a null
what is the name set in the inspector
[SerializeField] private string mainMenuSceneName = "MainMenu";
Pretty sure it doesn't care about the folder, just the actual file name
Logs show it's MainMenu
hmmwth is going on then lol
Are there any other errors in the console before this one?
...huh
using UnityEngine;
using Steamworks;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using System;
using UnityEngine.SceneManagement;
public class Init : MonoBehaviour
{
[SerializeField] private GameObject _serverGo;
[SerializeField] private GameObject _clientGo;
void Start()
{
if(SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
{
Console.WriteLine("Server Build");
Instantiate(_serverGo);
}
else
{
Debug.Log("client_build");
Instantiate(_clientGo);
}
Destroy(gameObject);
}
}
clientgo is a prefab
and attached is clientnetworkmanager
just for init context
Okay, just throwing things at the wall at the moment, comment out the SceneManager.LoadScene line and run it again. Obviously, it won't change scenes, but does it still throw the error?
no errors at all (debug logs still saying loading mainmenu) but it isnt actually loaded
literally
Right, that's what I would expect to see if everything went as expected
but things have not gone as expected so I just wanted to see if it didn't do something wacky just because it's haunted or whatever
just for shits and gigs, could you try loading that scene by Build Index ?
Yeah, for now, hard-code it to load scene 1
alr sec
SceneManager.LoadScene(1, LoadSceneMode.Single);
Keep all the code as-is, just change the LoadScene to load 1 instead of the parsed string
yea cannot int to string
int sceneIndex = 1;
then SceneManager.LoadScene(sceneIndex, LoadSceneMode.Single);
or how does loading by index work
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SceneManagement.SceneManager.LoadScene.html
LoadScene should definitely take an int as the first parameter
Literally just replace your scene load line with this one: #💻┃code-beginner message
Don't change anything else
wut
then if i try to run it ignoring that it asks to fix all compiler errors
is this a custom scenemanager ?
using UnityEngine.SceneManagement; no?
I have no idea what the shortcut key is for VSCode, but go to that LoadScene and see if you can go to implementation
On VS it's F12
just hold Ctrl and click it
yeah thats some custom thing
Ah, so not the Unity SceneManager
i thought ive been using it the whole time 😭
Looks like NetworkManager has a variable named SceneManager, and that variable is null
So rather than calling a static function on the class SceneManager, it's calling a function a variable of that name
and that variable is null, hence the null reference
Because it's not a type ambiguity, like if you had two classes with the same name
one of them is a class, the other one is a variable
AHhh yes that makes sense
and if they have the same name, C# assumes you want the variable
It's so you can do something like public NetworkManager NetworkManager
i have literally been staring at this error for hours 😭 gone through multiple stack overflows
You shouldn't do that
holy
but it can
In the end, one truth prevails 
I have moved to Unity from Godot, I had bigger expectations from Unity, but Unity for me is too slow (building time etc. and is more complex)
yupp
and now you learned about inspecting Definitions lol
Still I'm learning it
learn something new everyday 😭
mainly because of multiplayer
building times are pretty chill but the compile times can be pretty cooked yeah
never ending process lol
because in Godot, I have to setup custom TURN Servers etc. but in Unity I have Unity Relay and other Unity Services
until CoreCLR is released
that will improve compile time greatly
sure but also i heard they we're moving to new shit like 2 years ago
being stuck in such an old implementation of .net doesnt help
i don't doubt it tbh but also im hesitant to lean on the assumption they are on track
until rumours say Unity 8 😛
why Unity has so long compiling time etc.
are you actually experiencing long compile times, or is it the domain reload that happens after compiling is finished that is taking long?
probably domain reloading
I can test for you really quick
yeah i'm willing to bet it is domain reloading that is taking long and not the actual compile. they are separate steps (though domain reloading will always happen after a compile, there is no way around that)
but why it is reloading assets
if you're feeling brave use Assembly definitions to shave a few seconds
Why not only the scripts
your scripts are assets and when you save them it needs to refresh them to recognize changes so that it can compile. but domain reloading is not the same as asset refresh
the entire editor is like scripts lol
make changes -> assets refresh -> compiles so it can be ran
though you can disable domain reloading on entering play mode
yeah the name threw me off in the beginning I thought domain reload was before entering play
but its has both after script change and before play, lucky the before play can be skipped
I have never used lerp before how can I use it when crouching and standing back up again?
https://paste.ofcode.org/CrTyLxABXAeCajEhTgytWw
you can, but it will always reload the domain after compiling
ye
there are literally dozens of tutorials . this shows proper lerp
https://www.youtube.com/watch?v=-XNm7dPVVOQ
Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
Join me and learn your way through the Unity Game Engin...
Instead of capsule.height = newHeight; you would Mathf.Lerp capsule.height towards newHeight
Or MoveTowards
👆 also i'd recommend using MoveTowards if you are changing the scale or whatever rather than Lerp so that you don't have to care about how much time it takes and just need to have the speed you want it to take
You also need to adjust the center offset while you do that
I'm soo loving the new input system, shocking how easy they made it to add controller support.
The exact same shader is applied to the brick wall, the placard, and the telegraph
the telegraph has the unlit shader in the first image and the same Lit shader as everything else in image two
Any idea why it's filled with the Light of God?
or~~ #archived-shaders~~ #archived-urp
def not a code question tho
Oop, right, will move it
lol.. i just happened to discover this same thing yesterday..
for me it was b/c the object was scaled to 0 on one axis
and then it made it turn into w/e that is
hi, my script below shakes the camera by moving it in random spots in a square for a given period of time. however, it shakes more violently if the camera is more zoomed out. how can i fix this so that the camera shakes at the same inputted strength regardless of how zoomed in it is?
https://paste.mod.gg/gykqbtrtpkwk/0
A tool for sharing your source code with the world!
still cant explain what im seeing ^ but atleast i figured out how to replicate it
YES
thank you!
I didn't notice because it was a sprite but the Z scale was zero!
ya, took me a minute to figure out why it was happening myself
thought it had something to do with post processing.. but it seems it happens regardless if u have post processing toggled on or off..
or the skybox and every other combination.. (didn't matter)
Back at Unity: "Hey guys! I got an idea.. Instead of showing a console log or something letting the user know they've accidently scaled their object to zero.. lets instead have the object emit a God Ray that blows out the user's entire screen!"
Probably a division by zero happening somewhere in the shader
Obviously thats a less likely reason.. but its fun to think about 😄
Resulting in a NaN/super bright (or dark) pixels
Ahh! you've cracked it
that's probably correct
Shouldn't this prevent "null reference" error?
I could have sworn I have done it like this before
not if the tile is null
Shouldn't be possible
What line has the error
Ah nevermind I had forgotten the script in some random place in my scene
That was the instance that was giving the error
lol
I've made a very simple test platformer and I've only just noticed that the FPS drops significantly when my player is in motion... is there a usual culprit for this?
How are you moving your character?
Something is probably just getting called way more often than expected
I have an animation event on the last frame of my player's swing animation. Most of the time it fires the FinishSwinging() perfectly, but occasionally it will not call that func. The code looks fine and I can swing like 80 times before the anim parameter isSwinging gets set to true and then never gets updated again. FinishSwinging() is what sets isSwinging back to false.
It seems like the problem has been narrowed down to the anim event function. What can I do about this?
you'd basically just scale ur shake intensity or shakesize or w/e u call it..
that way the more zoomed out you are the more scaled down the shake intensity is..
I think it's the compensation raycasts to stop the player from clipping through geometry at higher speeds. Basically I have the code cast more rays the faster the player is moving
so say u shake the camera 1 unit when ur zoom level is default..
so lets say u then zoom out 2x as far.. to make it look the same you'd shake the camera .5 units
I'm going to try experiment a little
My 2 cents are just stop using animation events, they are a bit outdated and not very reliable
Alternative is StateMachineBehaviour
I'm fine with that, how can I tell programmatically that the anim has finished?
if u have an exit condition that changes states when its finished u can use that..
if not you could always get the clip duration and use a coroutine to wait
Maybe there are different alternatives to those raycasts? Have you looked into rigidbody interpolation, etc.?
I feel your pain with the collision problems
I've not. Are they a better alternative?
Thank you @sharp bloom and @rocky canyon
I've had so much hassle trying to get it to work not only well, but at all. I have no idea how people manage to create simple platformers when collision detection is this arduous
It's bc the math involved in that is quite complicated
But I'm talking about these things here
isnt that for dynamic rigidbodies?
once you perfect ur own system you package that bad-boy up and you re-use it everywhere
i should mention that its a 2d platformer and i'm wanting to have complete control over movement
Oh right, so you're not using physics
https://www.youtube.com/watch?app=desktop&v=3sWTzMsmdx8&ab_channel=Tarodev this guy helped me a ton getting a 2d platformer to feel good
Source & game: https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
Extended source: https://www.patreon.com/tarodev
Learn how to build an amazing player controller.
This Unity character controller is built using custom physics and incorporates all the hidden tricks to make it feel amazing. 2D player controllers can be difficult to get ...
he even shares the project files..
i used it to reverse engineer it..
Maybe set up some raycast masks
So that they only check for certain objects like walls etc.
i'd take a tiny step first before u try to leap..
comment them out or discard them temporarily and test just to see if thats even the issue..
once you have that information in hand.. then continue
aren't we all 💪
One of the dumbest performance issues I had was caused by my mouse's extremely high polling rate
Spent a quite while trying to figure out that
i hate that ur mouse's DPI is independent of the game-engine..
i'll accidently toggle mine to a higher speed and it'll destroy the feel of my platforming
i mean mouse dpi is independent of games 😛
and i tried to write some code to compensate for it.. but apparently you can't get the DPI from ur mouse in unity
I think your trying to fix a problem that doesn’t really exist
I mean don't games just have like "mouse sensitivity" setting
Just a simple multiplier
usually at best it’s handled by mouse sens yeah
nah.. never had an actual problem.. other than my fat finger pressing my mouse button unknowingly..
it was more of me trying to see if i could..
and the experiences along the way
lol
i just never know when to quit lmao
https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller/blob/main/Scripts/PlayerController.cs damn is this really all you need for collision detection and movement?
Ye it uses raycast masks
But honestly they aren't even that expensive (raycasts in general I mean)
theres a million ways to do almost everything game-dev
if you can make it work.. and make it solid.. i say why not
its usually all about how cheeky you can be behind the scenes and what u can get away w/ to keep ur game performant
but also fun and visually engaging
ya, raycasts are dirt cheap! 🤑
i must be doing something horrendeously wrong then to have it lag my game so much 😭
bobs head while imagining a techno beat
you should check out how to use the profiler that way you know exactly what part of ur game is taking the longest amount of time per frame
^ bottom panel.. Find your Hiearachy and after finding a decent spike you can pause/click the spike and investigate
PlayerLoop will show all the scripts that are running and how long they're taking and how much garbage they're creating
I'm actually really confused now
I was just playing the game in-editor, and it was reaching an average of around 14ms main while i was moving around
but then suddenly it dropped down to 4ms
and stayed that way
I stopped the game and restarted and its still only 4ms(???)
interesting
is it the overhead of the editor?
not sure.. the more editor thats exposed the more it'll slow the game..
for example if u test w/ a maximized game view.. it'll play alot faster than if u play in a tiny docked window
trust me i only have an incredible, barebones level right now
im mostly just trying to refine movement
this is what im working with (video from last night)
disable ur movement code or disable the player and then test..
see if its still cooked..
if it is its not the movement code.. but if it clears up.. then u can be sure that it is
like i said the fps is fine right now
i dont know if a game as barebones as this should take up 4.5ms though
idk what the baseline is, with all the overhead considered
no..
i see
thats not right at all..
what is it typically lmao
a smaller scene usually runs at like 500+ fps
oh dear
doesnt really explain why it went up to 13ms while the player was moving earlier though
very strange
when the player is still, its still 4.5ms average also
okay i may have exaggerated a bit
i suppose the 13ms was a freak incident until I catch it happening again but if a game like this should be running at 500fps, I'll have a look to see why
this scene is playing around 100 fps w/ movement, enemy movement, post processing, particle effects, animations, music etc etc
well.. thats not too bad..
it wouldnt be too bad if it was also a fully fleged game lol
but its literally just that barebones scene with no special effects
i can only assume its my poor use of raycasts for collisions
i used to never pay attention to the FPS until it was i started building bigger levels and then i'd notice it was really low.. like 30fps.. and then it was too late to figure out what it was that was causing it..
i would have to restart.. that was years ago.. now i pay attention to teh FPS like everyday
yeah thats how im feeling rn with how much i have in code
after i implement something i'll look
im very beginner so i dont know the proper practices
i wasnt expecting to get very far so i didnt really set any good baseline either
it got soo bad i built my own frame-counter with a little bar that ping-pongs back and forth..
right now i have 2000 lines of code in my PlayerController.cs which is literally the only significant script
if the bar doesn't sync up with the Timer something is wrong.. and i instantly stop and go look thru my code
it handles everything except audio and camera movement
does stacking everything into one script effect fps also
ya, i wouldnt stress too much bout that.. while ur learning u really don't know much about good baselines anyway
its only after a few trial and errors until u start to get the feel for it
it shouldn't thats just more of a structure/organization/scaleability no-no
yeah ive been trying to compartmentalise everything slowly but its been proving quite an issue
im wanting to have enemies and other entities so im going to try move everything that a living entity would have (movement features, collision detection, etc) into a script that the player and enemies can both inherit
somewhere along the line, the player starts to just fall through the floor

i just stopped and restarted the game and now its 9ms
im so confused
thats no beuno.. (make the floor a big cube) j/k thats just a band-aid fix lol
oh i did just enable deep profiler, that probably didnt help with the increase in ms lol
you can get a decent baseline for your PC by running an empty scene (one of the Create New Scene ones) w/ just a camera and a light
and then go from there
Oh.
lmfao
I guess it really was just an incredibly odd coincidence
thats.... annoying
good job im getting a whole new PC on friday
hi, i tried to implement this but i got the same issues so i think im doing it wrong.
the default size of the camera is 5
the scale factor is just the current size of the camera divided by 5 (so if the curr size was 10 the scalefactor would be 0.5)
however, this isn't working for me and the issue still persists. why is this? here is my code:
https://paste.mod.gg/hyyfbyplnzwb/0
A tool for sharing your source code with the world!
another restart and its back to lagging when the player moves
so confusing
-# and its gone again
Yeah massive classes are a nightmare to debug and turn to spaghetti very quickly
A good rule of thumb that I learned in university is you should be able to describe what the class does in one sentence
I have those massive cs files on some of my older projects and I cringe every time I look at my old code
Hey!
I'm looking for tutorials or examples where you create small interactive tasks attached to 3D objects.
For example: dragging the mouse over a surface to "clean" or "scratch" an area, cutting the top off a soil bag and pouring it into a pot, or any mini-tasks where you interact directly with objects using the mouse.
Does anyone know any good tutorials, assets, or tips for building these kinds of simple object-based interactions in Unity?
i got here circle collider 2d and in the cube to and for some reason they wont collide the circle and the cube
You have no rigidbody on either of these objects?
nope
do i need to have one?
Rigidbodies are what actually handle the physics of an object
oh oaky like i just wanted to make a shooting system bc am new and practicing and tried to see if my bullet work and i dont really get it why need rigidbody on it but thanks 🙂
What part of it don't you get?
like why does it need to handle like if just have the box collider
i dont really needed any physic
When two things collide, that is called physics.
oh lol okay yeah am dumb
I'm trying to save game data, but for some reason the folder is being denied
It just means that your app/unity doesn't have right to write to that path.
is there a fix?
i tried to run as administrator
that didnt work
Well, a simpler fix would be to not write to the users folder. Aside from that, I'm not sure.
How are you creating the path? Or is it just hardcoded/selected manually?
honestly idk
i followed a yt tutorial
bc i suck at unity
Well, did you not understand the code?
i think its selected automatically
i didnt hardcode it
its selected automatically
i cant change it or anything
@teal viper
Where? What part of code?
I don't see it in your screenshots
the beginning
Share the !code properly:
📃 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.
That's just assigning it in the class. I'm interested in what you pass into the constructor.
That's not correct way to share code. Check the big !code blocks part.
📃 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.
bruh it does the same thing
when i use pastemyst
this is what i get when i use them
Wdym?
when i use one of the large code block things it makes a text file
like it doesnt do anything different
Your code is pated as a file
If you use a paste service, you'll be able to share a link here.
Great, but it's still the same issue: this is just assigning the value in the class. I want to see where you pass it in.
public FileDataHandler(string dataDirPath, string dataFileName)
{
this.dataDirPath = dataDirPath;
this.dataFileName = dataFileName;
}
Share the code where you create the FileDataHandler instance.
A tool for sharing your source code with the world!
i think this is what ur talking about
@teal viper u still online?
Yes. Okay, so you're using Application.persistentDataPath. Which should work normally.
yes
What do you set the filename to?
hi so i tried to make a script that follow the player like for zombie am testing on a cube with rb and boxcollider and for some reason i can just push it away and it will be gone forever anyone know how to fix
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class ZombieScript : MonoBehaviour
{
public float moveSpeed;
public GameObject go;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(go.transform.position.x > transform.position.x)
{
transform.position = transform.position + (Vector3.right * moveSpeed) * Time.deltaTime;
}
else
{
transform.position = transform.position - (Vector3.right * moveSpeed) * Time.deltaTime;
}
if(go.transform.position.y > transform.position.y)
{
transform.position = transform.position + (Vector3.up * moveSpeed) * Time.deltaTime;
}
else
{
transform.position = transform.position - (Vector3.up * moveSpeed) * Time.deltaTime;
}
}
}
No it doesn't. You need to set it in the script inspector.
how do i do that
Do you know what a script inspector is?
I can't help you much if you don't know the very basics of working with unity.
!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.
yeah i think so
Besides, it should be covered in the tutorial.
they didnt show it
oh okay sry also i thinked i fixed it i put the mass of the "zombie" to 10000
No. I'm talking about the script instances assigned to a GameObject.
Did they not show how to use the script?
no
Then how are you using it? How do you know how to use it?
honestly no
In this video, I show how to make a Save and Load system in Unity that will work for any type of game. We'll save the data to a file in both a JSON format as well as an encrypted format which we'll be able to toggle between in the Unity inspector.
IMPORTANT: For WebGL games, because WebGL can't save directly to a file system, a different meth...
This was the tutorial i used
imma check back in a few mins
They seem to be talking about it on 15:30.
Also, I'd recommend you go learn the unity basics/unity !learn beginner pathways before following somewhat complex tutorials.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im currently learning unity basics lol
ah i see
lemme check
Great. When you're done with the basics you can follow this tutorial again.
why can i not do this?
meshRenderer.material = new Material();
lacks a shader, making the material invalid
how do i add a shader?
no clue 😬 lol
alright
yes
could u not create a mock material and just modify that
Not sure if this the proper place to ask but I'm having an issue where the rotation of my player object is incorrect, wondering if anyone can help?
You'd need to share the details of your issue.
Of course, I'm essentially making a game with objects similiar to diep.io but in 3d, basically a puck with a gun, before clicking on play it sits in the scene just fine like so
you would need to share your code - but off the bat we can see you have oriented this object all wrong. Blue should be "forward". red should be to the right, green should be up.
Is this a custom 3D model? Or made of Unity primitives?
Custom 3d model imported from blender
you need to go back and re-export it with the proper orientations for Unity
Gotcha, thank you
Search for Blender Unity Export settings to see how people do it
Orientation has been fixed, or at least the axis' point in the right direction, but the issue persists
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour{
[SerializeField]
private float movementSpeed;
void Start() {
}
void Update(){
HandleMovementInput();
HandleRotationInput();
}
void HandleMovementInput ()
{
float _horizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
Vector3 _movement = new Vector3(_horizontal, 0, _vertical);
transform.Translate(_movement * movementSpeed * Time.deltaTime, Space.Self);
}
void HandleRotationInput ()
{
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(_ray, out _hit))
{
transform.LookAt(new Vector3(_hit.point.x, transform.position.y, _hit.point.z));
}
}
}
This is my code and the result when I hit play
Have you try asking Chat gpt?
you need to show the new orientation on the object at rest
show me a screenshot like this again
And what does the hierarchy look like?
Is this a singular object, or are there children? Also is your tool handle rotation set to local?
yo i rlly need some help. years ago i wanted to develop a game, so i looked up for lots of tutorials on unity and c#. but i felt like i was learning nothing. i could follow the tutorial and understand it quite well, but when trying to apply it, i blanked. so i laid it off bc it got hella confusing. a week ago i was looking for some old files and i saw my old pixel art assets, so i tought i might as well give coding another go. but again, i feel so frustratad because i really cant see the way trough it. if anyone could please help me, or give some insights or guidance on where to start, how to actually learn to learn, i would be really grateful 🙂
learning is different for each person
I would say... try something different from how you used to do it
It is a singular object and the rotation is set to global
you need to set it to local
If it's set to global you're not actually seeing your object's rotation
you're seeing the world axes
i saw someone on reddit say codewars was an amazing site for it, but i cant really understand nothing of it, not even the easiest of the problems
you need to focus on learning the basics of coding first
Ghanged it to local and the z axis is pointing upwards again, I followed someone's export guide but I'll just try again
i usually say start with c# so you aren't learning both c# and unity at the same time. there is a pinned message with an intro to c# course. Though regardless this isn't something that you can really just do for a week and hope to understand anything. People go to university and get degrees, and still can barely code from my pov
If you just want to learn C# this is a good place to start
yep that means your export is still off
keep trying 👍
how?
should i buy a book or smt
https://dotnet.microsoft.com/en-us/learn/csharp
This is a good place
lemme look for it
you shouldnt need to buy anything for this, even if its an online book or course. most of what ive seen from online courses have been pretty much worse than the free content that exists
yeah, i was always skeptical, seeing how many good stuff is out there
i really felt like i was the problem lol
take it easy, learn step by step, one new thing at the time
Spent hours today trying to figure out what was wrong with my procedural generation when it was integer math 🤦
(Rounding down to zero)
Learning to debug more efficiently can cut those hours down
Yeah I need to remember to start at the source and work backwards to where it goes wrong
you can also use a technique called bisection. Where you start from the beginning and the end, and work your way to the source of the problem by cutting the problem space in half at each step. It's like a binary search for debugging.
Oh smart
So like log at the midpoint (say it’s m), if it’s an expected value log at the midpoint between m and the end, otherwise log at the midpoint between start and m?
yep
anyone know how i can avoid this?
my normal fix is urp lit for rendering, but doesnt work all the time and it becomes white, whats the work around?
You should show the material for the helmet
not the shorts
pink/white by default
I wanted to see the inspector
you don't have any albedo map set
ok yeah im getting the hang of it
How do I create a menu bar in unity's ui toolkit?
I am not talking about a main menu, I am talking about a menubar like in windows, mac and linux
ok I posted it in there
is there something i need to do for it to be recognized?
might be following an outdated tutorial
For starters share whole code.
You're probably using it in a wrong place.
Which is what "does not exist in the current context" usually imply.
made into a field 
think about the logic you'd be doing. if the distance cant go under 0 lets just say its 1 for this case
if ( 1 < -1), will this ever be true?
Oh yeah I just realized, no.
My bad, should of thought more
sometimes i get it mixed up too if im just mindlessly coding. ive been coding for years. i wrote it out in a way to show how you can answer these things for yourself in the future
Can any of you help me with trying to play audio based on a player's location?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
https://dontasktoask.com/ look at the #854851968446365696 for what to include when asking a question
Any Unity experts around who are willing to commit into looking into my problem, whatever that may turn out to be, even if it's not actually related to Unity or if someone who doesn't know anything about Unity could actually answer my question?
Basically im trying to make audio play based on the players location withinthe world, ive looked at numerous tutorials online ajnd can't find anything that will help me, though on paper it seems an easy thing 🙂 sorry, for asking the question poorly the first time.
this is pretty much just the same question as your first. you should specify what you actually struggled with because there is an existing method for it. im sure one tutorial wouldve at least had this
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AudioSource.PlayClipAtPoint.html
this is precisely what i needed, thanks for fidning the link
also im very new to this, so again im very sorry if i've asked poorly or come across the wrong way english isn't my first language !!
do you have any good youtube recomendations for audio? Ive tried a couple and don't think their methods will work the best for my game. 🙂
no need to be sorry. when beginners ask in that way, it's hard to know what the person is struggling with. Could be you can't find the method to do what you want, or if you dont understand the code tutorials use, or any other reason. I did find it online by typing "audio unity play at location" which is mostly what you asked here
if you have the time, i can dsicord call and show and descbbe what i'm tryig to do, as i really am poor when it comes to typing english XD
No tutorial will ever work best for your game, most tutorials are very specific and are hard to extend when your game needs different functions. Audio can be very simple just using the existing methods to play clips when you want
there are no voice channels and people don't really do DM's here #📖┃code-of-conduct. If you are not using a translator, your english seems fine. Maybe just say english isn't your first language when asking a question, so people can use simple words.
okay thank you !!
are you trying to call that method? that's not how or where you call methods
bruh im still stuck
let me try screen record and send over, if that is okay?
I FIXED IT
YESSSSSSS HOLY CRAP
anyone know why i get this sort of burst of sound assigning an audio clip in unity, even with playonawake off, its ruining the experience of the game
is there any better way to do player movement
What kind of question is that?
a stupid one?
Sure is up there. You need to identify what you think you don't like about your character and how you would want to fix it before anyone can even begin to advise on it.
ive got movement now i need to think about crouching stamina ect..
and eliminating bhopping
All you did here was throw up some presumably working code (given that you likely got it online) and expect someone to answer your vague question.
i tried following a tutorial it didnt work and was outdated
well ive got playermovement.cs now i need to fix bhopping
limit the jumping*
okay i apologise i'll rephrase "I want a semi-realistic game how do i make my character jump humanely and not jump infinitly"
sorry if that sounded rude
i want to eliminate bhopping
Create a counter, which increases by 1 everytime you jump. Before allowing a jump, check if it's less than the number of jumps you allow.
Reset the counter to 0 when you are on the ground.
would i put in playermovement or seperate script
thats a silly question...
sorry im being stupid
ill stop
Where you're actually doing your movement.
ok so if i add a recipe i.e for items and the make and canel pops up and i press cancel with my mouse they all go back. but if i use a controller to press cancel the first item does not go back and remains in the first slot of the crafting slots. why would it only work for the mouse ? https://paste.mod.gg/fdmsmlqakmhy/0
A tool for sharing your source code with the world!
with keyboard and mouse
with controller
is this a place where i can ask help, or is there another channel?
anyone can help me for some reason its giving me an error and idk what i did worng
you need assign it.
yeah i did
ls is empty
how would i get this error done? there's no clear place on where i can fix this
its only telling me this, but there is no "settings" in edit
if (ls != null)
{
ls.addexp();
}
i relized what was wrong i had a box that needed the money assigned sorry my bad
you sure? that's where it usually is
i see "project settings" but not "settings", also in there there is no "input" but "input manager"
and in there i see fire1 fire2 and fire3, but thats mouse 1 2 and 3, but they are configed and the error is saying fire with no number
are you using the new input system or the old
im really new to this, all i know is the version, thats why im here asking for help
yeah that's it
ok, so why is there 3 different fire thing but im still getting errors
so either you need to configure just Fire or you need to change your code to use the ones you have configured
because none of them are Fire
my problem is that i dont see a "fire" and i dont know what im supposed to do
or do i change fire to fire1 in the code?
this is what Chris said you should do, yes
see now its like its pressed all the time, its the !thing_i_wanted_to_happen
so like in a better direction, but not the "correct" thing
show your !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.
just ctrl + a + ctrl + v?
eh? read the bot msg.
which one do i do
Which one what?
links to services ig?
just use whichever link you want
that's why there's a list and not a single one, or a big msg saying "use this one"
so, just FYI - for your future reference, the answer to this is the old system
what you currently have, should fire a single bullet when your mouse button is down
yes, but the things i "apparently" have but dont work is mouse detection and following + firing on click
you don't need any mouse detection, fire1 is bound to mouse1
in your input settings in project settings
following + fire on click
explain what this is better
any ideas please?
hey does somebody know why i suddenly cant reference values from my animator even tho it worked perfectly yesterday?
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Wdym "reference values from the animator"?
i cant use the values from the animator like anim.randomValue = 1; just doesnt work as if the value didnt exist
That code alone means nothing so you'd have to show more
but it worked with the parameter i tried it yesterday with
Show code, show error
anim.speed = 1;
anim.idling = true;```
the first line works, but for the second i get the error"animator does not contain definition for ´idling´ " even tho the value exists like this in my animator tab
This never worked. You are confusing this with Animator.SetFloat etc.
where does animator have such a property ?
Animator does not have any variables named idling. You can see them all here:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animator.html
ohhh i made an variable named speed but the code used another animator variable?
that makes sense thanks
anim.speed is changing this variable:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animator-speed.html
can anyone help how do I get the component of light2d intensity in script?
private Light2D globalLight;
void Start()
{
globalLight = GetComponent<Light2D>();
}
IEnumerator TriggerBlackout()
{
yield return new WaitForSeconds(3);
Debug.Log("Blackout Triggered!");
globalLight.intensity = 0;
}
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.
and what's wrong with what you've done?
when i'm starting the game the light intensity doesn't set to zero even the blackout is triggered
Where do you start the coroutine
in the update()
private bool blackoutStarted = false;
if (blackoutTrigger && !blackoutStarted)
{
blackoutStarted = true;
StartCoroutine(TriggerBlackout());
}
Do you get your log
yes this works Debug.Log("Blackout Triggered!");
but it doesnt set the intensity to 0
If you get the log and don't get any errors, then that light's intensity does get set to 0
Whether or not it stays at zero, or if that's the light you're expecting to set, is a different story
Maybe show the full !code of the script
📃 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.
am i allowed to do screenshots with errors?
Use Scriptbin to share your code with others quickly and easily.
That's a warning, not an error, and it's pretty clear. You've made a variable you do nothing with
i reference its value tho in the jump == true
That's not the jump variable you created inside that if statement
Can you show the inspector of this object?
it isnt? i thought only one variable of a name could exist
Only one per scope. Every time you have a { you create a new scope. If you declare a variable with a type, that creates a variable in that scope.
A variable exists until it reaches a } that closes the scope it was created in
So you make a variable inside that if statement that ceases to exist when the if statement ends
doesnt the public make it so it can be found in every scope?
No, it means it can be accessed in other scripts, but it still only exists in the class scope
Every scope inside the class scope can use it
hmm, can i fix that?
unless that scope creates another variable with the same name
which you have done
So, if you don't want to create a new variable inside that scope, don't do that
Change the one that already exists instead
it needs to be changed on the fly, i cant apply jump force to the player inside the raycast script so i thought i could pass that info using a variable
I was wondering how I would add lerp to my handling crouch? right now when I crouch it snaps to the new height same when going back to standing which I don't really like I want it to be smooth. I have never used lerp before so how would I do it in the most "simplest" way?
So why are you creating a new variable inside the if statement? Wouldn't it make more sense to change the one you already have?
Didn't you like, already ask this question
you were sent multiple options yesterday, how are you back with the same question?