#💻┃code-beginner
1 messages · Page 535 of 1
Define "everything"
I mean I can define other game objects that I need via [SerializeField] and stuff, so I Don't even need to make different scripts for "Game Manager" or whatever
Your question is a bit weird
If it's a game manager, then it should contain what a GameManager needs. No less, no more.
Serialization lets you tell one object about another object
so that when the game runs, the first object can find the second object
[SerializeField] only exposes a field to the inspector so that you can drag and drop it, it has nothing to do with defining other logic in the same file/class
Yeah, If I tell one object where the other object is - I don't need to make different scripts for those different objects.
Idk, I just never stumbled upon a problem doing every math stuff and events in 1 script.
So I'm asking if that how it is supposed to be
Your conclusion doesn't make any sense to me
🤩
If you have 10 scripts with 100 lines each, it's easier to find something than if you had 1 script of 1000 lines.
public class Enemy : MonoBehaviour {
[SerializeField] List<Weapon> weapons;
}
public class Weapon : MonoBehaviour {
public void Shoot() {
}
}
I don't see how giving an Enemy a list of Weapon means that you no longer need the Weapon class!
(that seems self-defeating..)
There could be many issues. It might've worked with a very simple project, but when it gets more complex, you'll start to run into issues, like execution order and such and even just bad unreadable code.
What if you have hundreds of scripts with 500 lines on average? Are you gonna put them all in one file?
Yeah, I guess my project is just too simple for multiple scripts.
but it has 250 lines already idk
I hope not.
Besides, if you're saying that it's hard to find something, then you probably don't know how to use your ide to the fullest.
Yeah, like
Everything has it's name and number most of the time
Are you asking about breaking one specific thing into many classes (and thus, many script files?)
I'm very confused by what you're proposing here
Well, if it's simple like that, then perhaps one script is good enough. As I said, it depends.
you wouldn't do this
Nah, that was just an example. If you can always use the search. And if it's an error, the console will tell you what line to look at.
public class Game : MonoBehaviour {
// The entire game
}
yandere_dev.png
Man
A lot of the criticisms of that game are completely bogus
but the game is also still bogus
I was just learning through unity official beginner sessions and in the videos he was making like 5 scripts with 5-20 lines each and it didn't make any sense to me.
It feels like you're just creating more files with no purpose at all
Yeah that's the thing. It's still uniquely bad even when you consider how much jank the average game already has in it
I can't watch those "yandere sim code sucks!!!" videos because they immediately make several dozen technical blunders
It's called organization.
Well, what did those scripts represent?
Maybe I should elaborate on this
Character, game manager, camera controller and other stuff If i remember right
Did those scripts do different things?
I am working on a game that is a lot like Alien Isolation.
Yeah, those all seem like different things. Why would you have them all in one script?
In the beginning, I had two absolutely enormous script files:
- Player
- Monster
Some of it is preference, but there's also planning for future. It's very likely that these scripts will grow to have more code in the future. Then there's also a thing called single responsibility principle. It makes your code more clear and readable.
Do you want an all-in-one toothbrush, spatula, toilet brush, shaving razor, and rice cooker?
The script files were way too big to deal with, and they made lots of assumptions about how the player and monster should work
Well yeah, but still
Why wouldnt you just do it in a singular script
It just feels like lottering tbh
Because they do different things
Now, I have Entities. Entities have lots of little Modules that add specific features to the Entity.
If I want the monster to be able to do something, I add a little module that adds that feature
the player and the monster can share lots of logic (walking, seeing, hearing)
Because it would be crude, unreadable and hard to make modifications that don't break your entire game.
and also not share things (murdering the player)
huh
imagine a library that only has one book
it's a very big book
🤔
You want your scripts to be as single-purpose as possible. If you have a script for ducks and you want to change the rate at which ducks quack, you go to that specific script and change that specific thing. Rather than going on an archaeological dig through your monolithic Thing class that every single script uses and now you've also affected the rate at which trucks honk, guns reload, and enemies call for backup
it would be a nightmare to read, because it'd be enormous -- and editing the book would require a lot of work
Well yeah, but every big book has that thing with page numbers in the beggining so what's the difference anyway
the metaphor is getting stretched to the breaking point, but imagine trying to insert a page into the book
Imagine a library that just has a Dictionary, and a little post it that says "Feel free to read these words in whatever order you want to make up your book of choice"
now you have to renumber the entire book (which is the entire library)
and god help you if page 3496 says "see page 97455 for more details!"
You know I think the best way to answer this question is to just let you do it
We're bumping into a big concept in "object oriented programming"
Encapsulation
Don't visual studio have ctrl + F?
To find stuff by word
If you don't name your variables bsadg - it's easy to find them
One way to find out is to try and make a slightly bigger project.
Go ahead and try doing everything in a single file, you'll soon know why it's a bad idea
You'll understand when you face a complex enough project. If it works for you now, just keep it as you like.
You've obviously decided you know more about it and won't heed any warnings anyway
So go ahead and try it
yeah, I think you just need to try it and see, haha
But perhaps I can give one more example to convince you
A game might have:
- Many characters
- 4 cameras (it's split-screen!)
- One game manager
If words aren't enough then practice will teach you
you have different numbers of different things
Even if you have 5 little books - it's still hard to insert a page while keeping it all connected.
Like if you inserted a fourth friend into Harry Potter
If your Character class also deals with cameras and with managing the game, it'll be a complete nightmare to add a second Character
coming back to my game: an Entity can be many things:
- The player
- The monster
- A lever
therefore, I only put things in Entity that every Entity must have. Everything else goes into other components.
Well yeah, cause the character is the core
Nobody uses 2 atomic reactors lol
what if I want to do co-op? add an extra AI-controlled party member? add an enemy that gains levels like a player?
Literally just try it. Everyone here is speaking from experience, but it seems you just aren't convinced. Go make an entire game in one script and get back to us when you've finished
Well, multiplayer yeah
But I think it's a different story
I might need to be thawed out by the time you finish though
I'm already into it actually
Month deep
I kind of want to do this sometime tbh
manually rendering everything
A month is barely enough to grasp the basics.
we don't need no stinkin' Renderers!
It's not really something you can call an experience
12 hours * 30 days is an experience I would say.
If you actuallly put in hours every day
Okay 6 hours
if thats really the effort you put to only have 250 lines #💻┃code-beginner message
you really struggled somewhere
It's still not much time. Especially if you spent it on the same simple type of project.
Well I certainly didn't do that 🙂
I'm just saying that a month can be a month
And still, it's not my first project after all
And I did everything in 1 script before as well
And how much prior programming knowledge do you have?
so whatever
Just give up.
you can code for a year, if you're making bad code then all you've learned is bad code. ive skimmed through the chat above and it really seems like you're nit picking these comparisions (like library/book) instead of just accepting the answer. Theres literally no reason to make all your game in 1 script. If you wanna do it, go ahead and learn the downsides when you come across them. Or when you try to show off this project and become the next yandere dev of the community if you get that far
Dont give up.
If you want to get a glimpse of a more complex project, look up some game samples or open source projects on GitHub. Browse through it's code and think wether it would make sense to put it all in one script.
You're saying it like i'm trying to prove something
I'm just chatting 🙂
I mean stop trying to convince him. Some people have to learn from experience.
Why did you expect experience in #💻┃code-beginner lol
The thing is, you don't seem willing to listen to those that have experience.
Here's a simple analogy that might help to understand a little bit better.
Imagine you rent an apartment, but that apartment has everything in 1 room: the kitchen, the bed, the toilet, the working space. Everything in one room. Now, imagine your toilet breaks and starts spitting shit all over. Your whole daily life would be ruined. If the toilet was in it's dedicated room, it wouldn't affect you as much.
Why would you say that
I'm listening
I just don't have to accept your point of view like what
I'm thinking of big stuff that actual 3A games have
I think of the code that might actually be behind that stuff and it looks simple to me
I mean people still live in those apartments
And my toiled didnt cough shit yet so whatever
Livable
I have yet to see a toilet in the middle of a living room.
Yeah, I feel like it's just best to let him experience it by himself
then there isnt really a point to this discussion, because you're still just nitpicking analogies. people ask what experience you have not so you realize that you have essentially none and that you're just assuming how the world of CS works.
Anyways, it feels like this conversation doesn't progress anywhere. And this is not a place for social chat. You can look at more complex projects online. Hopefully that would help you understand that your approach is really only feasible for very small and simple projects.
The Unity courses as well as any programming courses are structured the way they are for a reason
Time will show what comes out of this
the first use case you'd see against this is that unity is already structured in a way where your code isnt in one script. There's already a transform, colliders, rigidbody. they exist as their own scripts. Why use unity if you want everything in 1 file?
I'm dying rn 😂
Why not
It's not like I came to Unity willing to use everything in 1 file
well you clearly have decided its the best way to do things. so ask yourself, why doesnt unity put everything in 1 file?
anyways this would be more appropriate in a thread now but i too think its better to just let you experience the flaws in this yourself
Question: I'm trying to setup a system where when a player steps on a tile, it animates to a different tile. In game it will be a flower that dissapears when you step on it. I can't find anything online on how to use tile collisions as triggers for that, and im trying to figure out if anyone knows or if I should scrap it
- Convert the player's position to cell coordinates (WorldToCell on the Tilemap)
- Check which tile is at that position
- if it's the flower tile, do what you need to do
explain it to me like I am a narrative designer that just got put on programming bc our programmer swapped to music and Idk what I'm doing hahha 🙏
I am watching this tutorial and the guy on his screen has the keywords showing for him and I do not. How do I get the keywords like him?
!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
correct me if i'm wrong, but an interface is a collection of variables and methods, right?
not really
Nope, this is an oversimplification, but an Interface is a collection of method names. Essentially any class that extends the interface is promising to have each of those methods
It's a contract that a class or struct can conform to, which contains a list of properties and methods that the struct or class promises to implement.
Alright, that makes sense, but i still have to write each "promised" method's logic per class that implements it, correct?
You got it!!
thats why they are thought as "a contract " , because they have obligation to implement those methods in the class/struct
In that case, why would i use an interface over just writting that logic per class?
It's not that i'm doubting the usefulness of interfaces, i'm genuinely trying to understand the use cases
mostly to have a common method/properties some classes/structs share
and you are ensuring you will always find those methods in those classes
oh boy
they are comparible to abstract methods but they don't need to be in a parent class to inherit from, a class/struct can have multiple interfaces
is there an updated tutorial for the new input system? In junior programmer pathway unity used the old system want now learn how the new one works
Heres an example. You might have an interface called IWheeled which says that there must be a method called SpinWheels.
Then you could have a Car class that extends IWheeled and a motorcycle class that extends IWheeled.
Then you could have some process that goes through all the Classes that extend IWheeled and calls SpinWheels. This class doesn't know or care if it's dealing with a Car or a Motorcycle it just knows that whatever it's dealing with has promised to have a SpinWheels method
on the unity learn website
With interfaces you can abstract away from the implementation and refer to many different object types via the interface. For example you can have an interface that promises "eating" method and all kinds of classes that implement it: dog, human, Godzilla, black hole, etc... you can them refer to all of then by the interface disregarding what they actually are.
i dont find one with unity 6
its not about the unity version but the package version, anything above 1+ is fine
So you could have something like:
List<Interactable> allInteractables;
foreach (Interactable i in allInteractables) {
i.Interact();
}```
And that list could contain all kinds of different things like Switches, Buttons, FOod, Potions, NPCs, whatever
ok
oh, that is actually sounds fiarly usefull for what i'm doing right about now
Can i have an interface inherit from another?
or even just code that raycasts and finds any interactable component on an object and interacts with it
that's a very common use case
yep
you betcha
any class that extends the child Interface must implement the methods of both the child and parent Interfaces
Alright, my eyes have been opened to the magic of telling a bunch of scripts what to do
ah ok thats interested thanks. so this way i used is not the right way?
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
private float movementX;
private float movementY;
public float speed;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void OnMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
private void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
}
looks fine
you could just store movement as a v2 btw
public interface IDamageable
{
int Health { get; set; }
}
public class Enemy : MonoBehaviour, IDamageable
{
public int Health { get; set; }
}
public class Player : MonoBehaviour, IDamageable
{
public int Health { get; set; }
}
public class Projectile : MonoBehaviour
{
int damage = 10;
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.TryGetComponent<IDamageable>(out IDamageable damageable))
{
damageable.Health -= damage;
}
}
}```
Here you don't give a crap what type it is and only the interface... so overall you're doing less comparisons. Another thing about interfaces is you can pass object references around by their interfaces only and exposing only what properties those interfaces include.
And, health here can be implemented completely different between the two
^ one of my favorite things to do is pass Lists around as an IReadOnlyList
Say, you only want player to only ever take 1 damage regardless
that's something else i've kinda been ignoring
why the { get; set;} specification?
Holy Crap, that's genius. I've been passing around copies of lists when I don't want them modified
Does that work with Dictionaries?
That's just a property field which you still need to implement, so for instance on player you want something like this. Properties are just mini-methods after all
private int health;
public int Health
{
get => health;
set
{
health = Mathf.Clamp(value, 0, MaxHealth);
if (health <= 0)
{
Die();
}
}
}
amazing. I have so much code to refactor!
So it's a property. Interfaces can't have fields, only properties (because properties are actually methods)
Instead you could just implement two methods like
public interface IDamageable
{
public void SetHealth(int health);
public int GetHealth();
}
Instead
Still, i don't understand what the get; set; is doing there
It's expressing that the property must have a getter and a setter
(on the interface)
on the classes it's setting up the auto-implemented property
I never thought about the fact that it's doing a slightly different thing for an interface!
this is quite nice, would this set the same damage for each IDamageable?
this is going off the notion that damage never changes
It would pass in the same parameter, yes. But you can have different implementations on both enemy and player
So like think of a game where you only want the player to take 1 damage only ever, but enemies can get 1+ damage like in zelda
^ well depends on the zelda game but some other retro games did similar
Or, maybe in the property implementation of player they also call InvulFrames(); because they get a few frames of invulnerability (enemies dont)
how would you make different implementations?
Hello, does anyone know what IDE stand for?
Integrated Development Environment
Integrated development environment
you couldn't just google that?
but you could have googled that...
Hai I'm having issues with a drop down menu. On my player.cs script, I have a function:
Public void DropdownMenu(int index)
{
Switch(index)
{
Case 0: playerStatus = PlayerStatus.walking
Debug.log(playerStatus);
Break;
Case 1: playerStatus = PlayerStatus.shooting
Debug.log(playerStatus);
Break;
}
}
I have this script attached to a player prefab since it's instantianted. On the ui drop down menu, under the "ON VALUE CHANGED", I have that prefab's script with the Player.DropdownMenu function on it, and the proper index for each. But when I run the game, and click on each drop down, it looks like the console prints out both Switch statements for index 0 and 1, so it's like the Break is not working for some reason. Also, I can see the index cha going on the actual drop down item in the inspector
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm on mooobile
you can google on a phone
What
oops
diff person
Show a screenshot of the inspector
So this would be Enemy let's say then for player:
private bool isInvulnerable = false;
private int health;
public int Health
{
get => health;
set
{
if (isInvulnerable) return;
if (newHealth < health)
{
StartCoroutine(InvulFrames());
}
health = newHealth;
if (health <= 0)
{
Die();
}
}
}
😅
Who really cares lol
don't waste peoples time for something you could've easily googled
Sry yall I'm hoping it's clear enough
There's 3 actually, but the issue is the same, all 3 run on the console for some reason
you have the function being called with 0 1 and 2
every time you change the dropdown, it's going to call it 3 times
once with each of those values
Oh I thought it would run the function with that index in mind
You need to remove all three of those, and add the function again
but this time from the dynamic parameters list
not from the static parameters list
And just FYI - life is easier when you use discord on your PC
What's the dynamic parameters list? The value up above that picture ?
I know I'm at my job rn waiting till 1030 then I can access wifi again
{
if (inputs.FindAction("Escape").ReadValue<float>() == 1)
{
if (!pauseMenu.activeSelf == true)
{
Time.timeScale = 0f;
//Freezes time ingame
pauseMenu.SetActive(true);
Cursor.visible = true;
Debug.Log("Esc activating pause menu");
}
else {
resume();
Debug.Log("Esc Deactivating pause menu");
}
Debug.Log("Esc has been tapped");
}
}```
for some reason, the menu only appears if it isn't there. When I hit escape, it also only debugs "esc has been tapped" when it activates the pausemenu and also says "Esc activating pause menu".
would you just add or subtract the damage in the health property for the enemy or player class or would you do such when you apply damage?
I see dynamic int bit it's grayed out when I put the player.cs (per the prefab) on it... and without it the "no function" doesn't let me click on anything
void resume is:
{
Time.timeScale = 1.0f;
pauseMenu.SetActive(false);
Cursor.visible = false;
}```
When you set timescale to 0 FixedUpdate won't even run.
You really should not be handling input in FixedUpdate.
does timescale not affect update
Pause the game at runtime and investigate the hierarchy. Is the object that you expect to see and it's renderer is enabled?
alsocs inputs.FindAction("Escape").ReadValue<float>() == 1 this is not the way to check for a button press
You want cs inputs.FindAction("Escape").WasPressedThisFrame(), which will work reliably when you handle input in Upate
So for properties if you do like an addition assignment/subtraction assignment, ect. You're actually invoking the Getter first before Setting. If it's confusing to you, you could always split it up a bit more and make like
public void DamageHealth(int damage);
public void HealHealth(int healing);
public int GetHealth();
methods
sorry if I'm asking very juvenile questions, I'm just curious
Then your function is not public or it's not on that script
Click your function name
its not a thing to click
yeah it's just a section header
Alright, so
i made an interface
i implemented that interface in something
now, how do i tell a ray to look for something that implements said interface?
Tell the ray to look wherever you want. Then, if there's a hit, try to get the component as an interface. If it's not null, you got it.
So here is my code
I haven't used getcomponent to refer to the script inside m_gc to use its IncrementScore function. How come I can still use it if I just use FindFIrstObjectByType ?
You specify the component when you searched for it
Where did I specify it ?
Not that I would consider using this method, but you did a search by the component itself. It's not like you've got a GameObject returned instead, and if you did then you'd probably want to use GetComponent to find the GameController on it.
When you declared the variable. GameController m_gc; that means the type of m_gc is GameController
that's why you can call IncrementScore on m_gc
FindFirstObjectByType is actually completely irrelevant to why you can call the function on m_gc
That is how you assigned the variable
but it's not why you can access the members of the GameController type
I always thought you have to find the object first to find the component inside it.
You could eliminate the Find entirely and it'd still compile. You'd get a Null Reference Exception, but that'd be perfectly cromulent code
The GameObject? No.
You don't have to Find anything ever
GetComponent gets you a component from a GameObject but there's no rule you have to start with a GameObject reference.
Majority of the time you'll be using GetComponent when doing some raycast query or through physics and collision contacts
as most of this stuff can be serialized on the editor or some other explicit way
This is my code for the Ball gameobject
I tested the collision in and out of the if loop and I find no collision at all when they hit the platform(player) (Check the console for Debug.log lines but I find nothing ). What might be the reason for this ?
Show the inspectors of the two objects that are colliding
ok never mind I foudn the problem. I forgot to add the script into the ball gameobeject -_-
That'll do it
Let's say i have an ISelectable Interface, if i get a reference to that interface then do, let's say, iSelectableReference.Disselect();
is it going to perform that method on every single script implementing that interface?
no, it would only call that method on the instance you have referenced
Nope just that reference
someReference.Something() always just calls Something on the particular reference you have there
that's what the reference is for
Alright, this is weird
This code is giving me an Use of unassigned local variable on line 70
even though i believe i'm setting said variable on like 59
line 59 is inside an if statement
o h .
So it's possible it's not assigned there
i tried adding a && selectableFurniture != null on the following if statements
but that didn't seem to solve it
if i'm checking if a variable isn't null beforehand, shouldn't that solve it?
you can assign null to it on the line you declare it if you want to keep this structure. otherwise consider restructuring this code so that these lines are only running if that variable is assigned
also since it is a local variable, it can never be anything other than unassigned or null in that last else if you have
Your line 75 honestly doesn't make sense with a local variable anyway
You need to store the object in a member variable so you can access it next frame
When I've written code like this in the past I've structured it like:
Target oldTarget;
void Update() {
Target target = null;
if (Physics.Raycast(..., out HitInfo hit) && hit.TryGetComponent(out target)) {
// Something to do every frame while hovering the target here...
}
if (oldTarget != target) {
if (oldTarget != null) oldTarget.OnLostFocus();
if (target != null) target.OnGainedFocus();
}
oldTarget = target;
}```
Also:
rayOrigin.transform.TransformDirection(Vector3.forward)```
This can just be:
```cs
rayOrigin.forward;```
Wondering if I could get some guidance; I'm trying to write it to where when my character's rb (2d) collides with triggers, that those trigger objects show a white outline (I have the material already and it works fine when I apply it manually). I then want the option to press E to show unique dialogue for each item
I was beginning to try using an interface for the interaction system, but before that, I cant get the outlines right. Last night I had it to where the outline was applied but didnt go away, and now its not even being applied at all haha, and cgpt is NOT helping. If anyone could give me some pointers, that would be awesome .I only started learning C# a couple weeks ago hence why I'm struggling with such a seemingly simple script. Not necessarily looking for someone to SOLVE this for me as I'm trying to learn, but i could use some pointers lol
This is my current player script that has both my player's movements and the non-working outline interaction system 
(https://paste.ofcode.org/PWZ629VNWABdnXr8FDbH2B)
(edited since text was longer than i expected)
What part(s) specifically are not working and in what way is the failure manifesting?
The main thing I notice off the bat is that this code will not properly handle the case of multiple overlapping colliders simultenously.
When my character collides with any object, there is no outline or any visual change; but the sprite preview window shows this square box when she gets in range
Well the code you have wouldn't be applying any kind of outline
it's changing the material on your SpriteRenderer
Which will change how the player is rendered (based on those materials)
I have a material from a shader that applies an outline called outlineMaterial; how would I apply that?
I have a material from a shader that applies an outline called outlineMaterial;
From where did you get this shader?
Is the shader for 3D objects or sprites?
And how is the shader intended to be used?
Most outline shaders I know of are for MeshRenderer and usually they are intended to be added as a second material (i.e. they render the object a second time, as an outline), not to replace the main material
https://paste.ofcode.org/ukEWJ3VB7f3qFtQRbTc5WA (<- the shader)
i simply found it on the interwebs
it worked when manually applying it so I assumed it would be smooth sailing 
So I need to add it TO a material rather than replace it (also, my original objects are just PSDs and dont have materials)
well how did you apply it when you manually applied it
was it a replacement, or did you add it as a second material?
I made a material from the shader and just dragged it on top of objects in my scene
Ok - that replaces it
btw that's equivalent to replacing the material on the SpriteRenderer
Ok so the next part here is you need to debug your code
make sure the part that changes the material is actually running
ok! So the basic concept of the code is alright and it just needs to be debugged?
Well like I said structurally it's not going to handle multiple overlaps simulteously but that's a problem for later
right now you should get the basic part working
right
thank you :)
i tried getting something like this going on
and well
i can't get to the unHovered state now
and it's way too late for me to understand what i'm doing wrong
it's way too late for me to understand
Why do you say that 🤔
because it's literally too late
like, it's 5 AM
the old synapser is fried at this point
Then go to sleep and revisit it tomorrow
i tried redoing this three different ways and no shot in the past two hours
Is there any chance it's an obvious little silly mistake i'm making? because my guess is i'm never getting some shuteye before i fix this
You should be using localSelectableFurniture and checkerSelectableFurniture, not selectableFurniture
that's a horrible mentality. if it was a tiny mistake, you aren't gonna find it in this state. go rest and come back to it when you're refreshed
if (localSelectableFurniture != checkerSelectableFurniture)
{
if (localSelectableFurniture != null)
{
Debug.Log("Stopped Hovering");
localSelectableFurniture.onUnselected();
}
if (checkerSelectableFurniture != null)
{
Debug.Log("Hovering");
checkerSelectableFurniture.onHovered();
}
}``` This not what you've got
those variable names are 😵💫 though
especially at 5am
jesus christ
that works
and it makes sense
and it's so obvious
@naive pawn is right
i probably should've gone to sleep three hours ago
oaidjhf;laqkjf;liarf;lkaJF;LAdf;ljDFA;LJKADKJFL
Translation: often the act of typing out and checking your details is what lets you solve a problem, even as you are in the middle of reaching out for help. I fixed this after 3 hours. So obvious. @nocturne kayak right there with you.
lol the rubber duck method? What is that?
"Put down the duckie to play the Saxaphone"?
explain your code to a rubber duck
it's a debugging method
it forces you to slow down and go step-by-step
that's what asking a (good) question here also does
I have class called Pathwinder I am using for pathfinding. I have a parent GameObject of a ship for a twin-stick shooter, and an abstract class called HelperShip. I have two helper ships who follow distinct paths in formation near the parent ship. One was working as expected, the other was not.
In the end: my prefabs were configured incorrectly. Pop the information into the prefab, boom. It works.
Hey guys, I'm a little bit confused by Cinemachine in Unity 6. It seems to have had a large update. What would be the best way to add camera sway now?
{
// [SerializeField] int[] numeroTaulukko = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
for (int i = 0; i < numeroTaulukko.Length; i++)
{
if ( numeroTaulukko[i] == original)
{
numeroTaulukko[i] = replacement;
}
}
}
how can i make script to replace all 5 with -1
Where is the problem with your current script?
why is the method declaring a int return and you are not returning anything. This will not compile
change it to int[] and return the numeroTaulukko at the end, it shoudl work
But I don't think there is any point in doing so, it is already a field which is available outside the method. I thought the return value represents the index at which the replacement was made although if it replaces many, returning only one doesn't make much sense either
logically you would return bool to indicate one or more replacements have been made or int to show the number of replacements made or void
well he never told us what he really is trying to do so i assumed
oh yeah, number of replacements makes sense
while generating runtime navmesh surface, everytime it lags a lot, what can I do to reduce lag?
I have optimized the voxel and tile size to the maximum possible amount
How are you generating it?
Did you try profiling and analyzing the lag?
using BiuldNavMesh();
yea the lag just comes from that, but I was wondering if its possible to only generate new newly needed nav meshes (which would save a lot of processing)
what does "analyzing" the lag mean?
right now it just generates a volume around the player every time it moves a few chunks
What unity version are you using?
unity 6
BuildNavMesh seems to be an obsolete api in unity 6. Why are you not using https://docs.unity3d.com/ScriptReference/AI.NavMeshBuilder.UpdateNavMeshDataAsync.html?
ah, im not aware of that, i just followed a tutorial.
That should run async(probably on a back thread) and not stall the main thread.
Well, if you want to use up to date api, you'll need to read the documentation. There's not gonna be a tutorial on everything.
Code runs once(incorrently) and then throws a "NullReferenceException: Object reference not set to an instance of an object"
{
skipper = !skipper;
if (skipper == false)
{
reportsGO[index].SetActive(true);
reports[index].UpdateStats();
index++;
}
}```
onPrimaryButtonEvent has no issue and works fine until I add the updatestats line.
updatestats is in another script, assigned to a group of objects which are accessed by the index.
``` public void UpdateStats()
{
S.text = Convert.ToString(patient.eyeStats.x);
C.text = Convert.ToString(patient.eyeStats.y);
}
S and C are TMPtext
where does the stacktrace point to?
The console tells you which line has the null reference... don't make us guess
Show an image of the actual error + stack trace from the console window
It is a code that works fine otherwise
This is hard to explain
It points to this code:
{
bool tempState = false;
foreach (var device in devicesWithPrimaryButton)
{
bool primaryButtonState = false;
tempState = device.TryGetFeatureValue(CommonUsages.primary2DAxisClick, out primaryButtonState) // did get a value, also it used to be "primaryButton"
&& primaryButtonState // the value we got
|| tempState; // cumulative result from other controllers
}
if (tempState != lastButtonState) // Button state changed since last frame
{
primaryButtonPress.Invoke(tempState);///////////////////////////////////////////
lastButtonState = tempState;
}
}```
On the line I added the //////// in
No it doesn't
hold on
question, does async just mean it won't finish the frame it was ran? (to reduce lag)
reports[index].UpdateStats();
reports or the element at index is empty, it hasn't been assigned - or the object has been destroyed
and by point I mean if I double click on it
It means that it would run in the background while the program execution continues without waiting for it to finish. The details depend on the context.
assigned in the editor
is that at run time? after you've got the error?
the computer knows better than you 😉
Always confirm the setup at runtime.
hold on lemme check
Debug your code so instead of assuming you will know
then find where you're doing that
Sorry for being annoying, thanks again
Yo im completely new to unity and know nothing abt coding. I just finished the 2d tutorial template yesterday, was wondering if it’s a good idea to just copy and paste the demo’s script, but tweak it a bit to my liking?
As long as you understand what each line does, it's fine.
Bet
Though, you might not ever get used to writing your own code from scratch like that.
It's a transition issue that some people have.
Do you think it’s a good starting point tho, because I do want to eventually learn it
What’s ur “meta” for learning stuff like this
Rn my goal is to make a game with very basic mechanics like fancy pants or like the old flash games
Yes, it's fine.
Awesome, ty🙏
There is absolutely nowhere that I unassign or even reassign the references in the code
but the scripts I am targeting are part of a prefab
could that cause the issue?
yes, you are probably using a reference to the prefab rather than the instantiated gameobject
Thanks, fixed it
reports[index].GetComponent<Report>().UpdateStats();
Works now
How might one create a 2d character controller in Unity 6?
(im new to Unity and coding as a whole)
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I create a text slot in my UIManager to put in the text "ScoreText" component , but I can't, what is the reason for this ?
It works now , thank you
is that normal closing takes time?
non-code questions like this belong in #💻┃unity-talk
It can take time, but usually if it's getting that long then check task manager to see if it's still responding.
ah ok sry
btw since reading the documentation would take ages(at least from what I see), is there any specific part that serves as a dictionary of sorts?
Or is there somewhere to start first like the scripting api?
The whole documentation is like a dictionary. There's a search bar you can use to search it.
You can start reading whatever you're interested in.
But if it's for general learning purposes, just reading it in order would do. Or you might want to consider taking the pathways/courses on unity !learn.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello! I have this coin collection script, but I have to make it so that the coins are saved and can be used throughout the game. I found the playerprefs system but I don't understand it very well, could someone explain to me how would I use it with this script?
PlayerPrefs lets you read and write simple values (numbers and strings). The values don't go away when you restart the game.
There are some examples in the documentation.
If you just want to remember a value within a single game session, consider using a static field.
public static class PlayerData {
public static int coins;
}
Could be as simple as that.
PlayerData.coins += 10;
This will reset every time the game starts (as does basically everything else!)
static means that the field is not part of a specific object
it's attached to the class itself
Okay
Got it :)
Hi, please configure your !ide before continuing development
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
But really, thanks! I was so stuck on that
Also useful for @swift crag to point people to configure it when you see this
I don't see anything obviously wrong in the screenshot
I use Visual Studio
intellisense is missing
And it has autocompletion enabled and stuff
For some reason it stopped highlighting some things while I code, is that Intellisense?
You seem to be missing syntax highlighting, which means you probably also miss out on editor warnings and such
If it says "Miscellaneous files" in the top left instead of "Assembly-CSharp", it's busted
Hello, I just updated unity from 6000.0.24f1 to 6000.0.29f1. When opening the project, unity asked me to enter safe mode. Then, I saw errors in console, it said that strings like TMPro, UI does not exist (??) but I didn't change anything?
Yeah, and I can't activate it again... what should I do?
It happened yesterday but I just left it that way and have been working with that so far
If it was working and then blew up, I'd just restart the IDE
I suggest you follow the steps listed if restarting does not help
If it's still messed up, go to Preferences > External Tools and regenerate the project files, then restart the IDE
and if it's still borked, then yeah, follow the steps from the bot message
Rider randomly throws up and completely breaks for me
Are you using assembly definitions? If not, delete your library folder and have Unity regenerate it, then try again
Okay, will do! Thank you guys 👍
I'm not, I'll try deleting library folder then
btw this error only occurs in the newest unity version, on the one I was using there are no issues
It could be a lot of things. I'd assume it simply hasn't downloaded the DLLs now so removing the lib folder regenerates this
I've seen this happen a couple of times. It's kind of mysterious
Sometimes Unity will be adamant that a specific assembly does not exist, even after nuking the Library
I've seen it be caused by corruption in the global package cache
It could also be due to compiler errors but this is usually only related to DLLs from user code
I honestly think it's just drunk
Otherwise uninstalling/reinstalling TMP might help here. I have had to do this A LOT back in .NET Framework days even though it changed nothing
nothing, still same issue. Maybe it could be a solution trying to install back again the editor?
even reinstalling editor, won't fix issue
Hey, could somebody explain me what .isGrounded is exactly for the character controller? I have the following Code and I've run into some issues:
bool isGrounded = _controler.isGrounded;
if (!isGrounded)
{
moveVelocity.y -= -moveVelocity.y + gravity * Time.deltaTime;
}
As you can see, I've got an boolean isGrounded what is the same as the .isGrounded from the character controller.
However, this boolean is almost every time at false. The only time it is on true, is when I move the character (even if it is mid air).
Because of that the player could just fly by moving the character without falling, what shouldn't be possible, so how can I fix it?
why are you doing gravity manually instead of letting physics handle it?
that aside, you're subtracting a negative number, so that code is actually making you go up
.isGrounded is pretty self explanatory ... it's a bool to tell you if the CC is grounded or not (ie: in the air). It sounds like you may not have it setup correctly - though I've never used the CC so don't know.
That bool declaration is also pointless, just do
if (!_controller.isGrounded)
actually no that code just doesn't make sense
moveVelocity.y = 2 * moveVelocity.y - gravity * Time.deltaTime;
```that statement is equivalent to this
so.. yeah that just doesn't make sense
Have you checked the docs? https://docs.unity3d.com/ScriptReference/CharacterController-isGrounded.html
if you were to implement gravity it'd be like this
moveVelocity.y += gravity * Time.deltaTime;
(but still, just do it with physics)
Usign a CharacterController you don't get gravity automatically
it's not a Rigidbody
How to acess the Cinemachine Target with code, to use it on a prefab? If i try to google it all i find is group target (Its a Camera 2D btw)
merci
Thank you guys for your answers.
@naive pawn
Like @wintry quarry said, character controller doesn't get gravity automaticly, thats why I do it in Code. Also my current code does work, because I did-= -moveVelocity.yand thats why the character doesn't move up, but down.
@wintry quarry
Yes, I've read the documentation, and what I've got from that was that "If it is on ground, it sets the value to true" but it didn't do that. Thats why I've got confused.
However. My Problem stays the same. I still don't know why it is only true when I move the character, and not when I am on ground
what I've got from that was that "If it is on ground, it sets the value to true" but it didn't do that
That's not what the documentation says.
Read it again
very carefully
Was the CharacterController touching the ground during the last move
why would you do it in code instead of doing it via physics though?
a rigidbody would handle gravity automatically, along with collisions with the ground or other objects
Because Character Controler and rigidbody doesn't work together. My character just glitches around then
ah.
anyways, your code works in the sense of going down, but not because of gravity. it works because you're doubling the velocity, and then adding gravity on top of that (which i suspect is positive as a serialized field instead of negative, then?)
Yeah I know, but it still doesn't make sense. If my Character is on ground then the last move also should have been on ground to (not the first time its on ground of course) so it should be true then right?
And also this doesn't make any sense that grounded is true when it is mid air
Yes that is correct
doubling the velocity is not how acceleration works
My Problem is not that the gravity doesn't work btw. I just wanna now why my isGrounded boolean stays on false when it touches the ground, but goes on true when I move the character
I don't really care on how the acceleration works right now
Hi I have a question about Visual Scripting.
How can I set number value of the component?
Is anyone here now who can explain to me why the CharacterController.isGrounded stays at false even if my character is one ground and goes on true when I move the character midair or on ground? Or did you guys just wanna tell me the same things again
CC.isGrounded is basically shit and nobody uses it.
But the gist of how it works is "did the last call to Move() attempt to push the CC into the ground?"
Okay, so you wanna tell me that I understood it right in the first place, and it should work the way I do it, but its shitty and that's why the things I have are happening?
Well the way it works is going to depend heavily on how the rest of your code is set up
it's just very finicky/sensitive
Okay, but why didn't you say that in the first place and just told to read the same sentence over and over again, when I have no way of getting that from this sentence 🤦♂️
I am needing help:
I currently am trying to make a toggle that invert's the y-axis for looking around. I am saving whether the toggle is inverted or not in PlayerPrefs. For some reason, it saves when I toggle it on, but when I:
- turn it off,
- save,
- go to a different scene,
- then go back to the options scene that has the toggle, the toggle is on.
Anyone have any ideas why it refuses to turn off?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class OptionsMenu : MonoBehaviour
{
bool isOn;
public Toggle invertToggle;
// Start is called before the first frame update
void Start()
{
PlayerPrefs.SetInt("InvertYAxis", 0);
PlayerPrefs.Save();
}
void Awake()
{
if (!PlayerPrefs.HasKey("InvertYAxis"))
{
Debug.Log("Creating InvertYAxis");
PlayerPrefs.SetInt("InvertYAxis", 0);
PlayerPrefs.Save();
}
isOn = PlayerPrefs.GetInt("InvertYAxis") == 1;
if (invertToggle != null)
{
invertToggle.isOn = isOn;
}
}
// Update is called once per frame
void Update()
{
}
public void InvertYAxis()
{
isOn = !isOn;
PlayerPrefs.SetInt("InvertYAxis", isOn ? 1: 0);
Debug.Log("Toggling InvertedYAxis");
Debug.Log("InvertYAxis: " + PlayerPrefs.GetInt("InvertYAxis"));
}
public void Apply()
{
Debug.Log("Saved Preferences!");
PlayerPrefs.Save();
}
public void Back()
{
SceneManager.LoadScene("MainMenu");
}
}
it's pretty obvious, you are overwriting the pref in Start
So, every time an object with this script is created, you're setting the InvertYAxis pref to 0
Meaning every time you start the game, it's 0
PlayerPrefs.SetInt("InvertYAxis", 0); <<<<<<
but that should forcibly turn it off, no?
i added that bit after i noticed this issue was occurring
when and where do you call InvertYAxis()?
Yes, after you've already set the checkbox
I have the toggle set up in the inspector to call it. That's the only thing that calls it:
I commented out the start method and the problem persists
invertToggle.isOn = isOn;```
One thing to be careful of is that this^ is going to call the OnValueChanged function
you should be using invertToggle.SetValueWithoutNotify
the other problem you have is that instead of reading the actual bool value from the toggle, you're simply blindly inverting it
SO yeah that's what's happening
you're doing invertToggle.isOn = isOn; and that's calling the callback function, which inverts it again.
Two changes I would make:
- Switch that to SetValueWithoutNotify
- Make the callback function actually accept a bool parameter and use that, instead of blindly inverting the current value
The first change alone should fix things but doing both would be more robust in general.
So, I did try to make the callback take a bool before, but I couldn't figure out how to pass the toggle's state to the bool
It will happen automatically as long as you select your function from under the Dynamic bool header in the dropdown list for the on changed event, rather than from under the Static Parameters header
I was just discussing this similar thing with someone yesterday: #💻┃code-beginner message
Thank yall for your help!
I am having a problem with checking if a key is pressed, I used Input.getkeydown and it only happens sometimes, and if i use Input.getkey it happens multiple times per key pressed. i think it is frame related?
You don't want to use GetKeyDown inside of a physics callback
Those only get invoked 50 times per second (not once per frame)
You might completely miss the single frame where GetKeyDown returns true
OnTriggerStay is physics-bound, inputs are frame-bound.
you need to poll on frames
Consider using GetKey and then setting a variable
if (Input.GetKey(KeyCode.Q) && !pressed)) {
pressed = true;
}
you could reset pressed to false when the key isn't being pressed
(shouldn't it be GetKeyDown so it only triggers once)
ahh okay, thanks for the responses guys! that makes sense, i'll do this, or is it bad to be doing this in OnTriggerStay()? should it be in the update or somewhere instead?
You could also use GetKeyDown in the Update method.
Perhaps you could do this
bool pressed = false;
void Update() {
pressed = GetKeyDown(KeyCode.Q);
}
void OnTriggerStay(Collider other) {
if (pressed && other.tag == "Whatever") {
// ...
}
}
Actually, no, this is wrong!
If two frames render before OnTriggerStay gets called, the input gets lost
this is actually just as bad as the original code lmao
I'd just do this.
bool pressed = false;
void Update() {
if(GetKeyDown(KeyCode.Q)) pressed=true;
}
void OnTriggerStay(Collider other) {
if (pressed && other.tag == "Whatever") {
pressed = false;
// ...
}
}
isnt it better to set a bool to true on trigger enter and set it to false on trigger exit and then in update check that bool and getkeydown together?
It'd be roughly equivalent.
no, it'd be better;
if 2 frames pass where the key is pressed before a physics tick happens, it'd only trigger once with your method
with your method, the physics tick rate is the constraint for the rate of action
doing it in update lets the framerate be the constraint
(cc @cosmic quail ^)
well, 2 frames where the key goes down, but yeah -- it'll be more accurate at very high framerates
definitely an improvement
yeah, that's what i mean. kinda ambiguous 😅
bruh why is vs not working properly
!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
You need intellisense to show you auto complete code. And it has to be Sprite insdtead sprite
so, I can't really afford Visual Studio to use performance wise
would Visual Studio Code or Vim with that server codecheck thingie work way better?
vsc code would definitely work
vim.. can't guarantee all the features, but you should probably be able to get c# set up?
God no, don't use Vim
they say so but I am not sure it's feasible
why would you use Vim outside of a command line interface
why should I not
I used to use Visual Studio Code until I switched to Rider
wdym gimmicky lol
Vim is good if you're the kind of person that likes Vim 😄
vim is just, a more barebones text editor
i don't know a lot of coding people but i do know one who uses vim as his main ide
one of my professors in college was all-in on emacs
I used it for a bit but didn't really like it
we have mouse pointers and nice displays now , haha
and that's not uncommon; vscode (i think maybe monaco itself?) has support for emulating vim
and yeah emacs is on the same level but that's about as far as i know
sometimes it's more convenient to not have to move your hand to a separate device to get stuff done
the close arrow keys on some keyboard layouts helps a lot with doing home/end/pgup/pgdown maneuvers
even on a laptop i use my thumb for the trackpad sometimes so i don't have to move my hand lol
I ve basically watch a funny yt dude who said that using Vim's customizable hotkeys and cursor movement saves alot of time so
Visual Studio also has hotkeys
pretty much every viable ide has hotkeys
that's like, one of the things making them viable
yeah he said most IDEs can emulate that
(I mean vim-motions)
we pulling out the kinetoglyphs with this one (ref)
it used to work before now it doenst for some reason
what IDE is that
Visual studio the blue one
that's called Visual Studio Code
isnt that the one i have
and the one that the bot reccomends
i get this error btw
try restarting the language server
ctrl+shift+p, search for .net, choose the restart language server option
Go back and follow all of the steps for VS Code here.
ok
keep in mind Visual Studio Code and Visual Studio are 2 different things.
Ensure that you are not attempting to follow instructions for Visual Studio.
you are using Visual Studio Code.
(i know, the names are great)
agreed 😉
!vscode
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i followed read them and everything was already done
is this 'proccessing workspace information in the background...' something i should worry about
Okay. Show me your installed extensions in VSCode and your package manager window in Unity
vscode extentions
Okay, so the Unity extension is installed properly
Package Manager
That all looks good
Kill VSCode, then go to Preferences -> External Tools and regenerate the project files
then reopen VSCode by double clicking a script asset
alt f4?
just quit VSCode
alt-f4 is actually the same as clicking the X button in the corner
so that does work 😛
do i check all the stuff above regenerate project files
No, you can leave it as-is
still nothing happens
hi
i am having serious trouble
{
for(int i = 0; i < RigBase.transform.childCount; i++)
{
Transform child = RigBase.transform.GetChild(i);
Debug.Log(child.gameObject.name);
if(child.gameObject.name == name)
{
Debug.Log(child.gameObject.name);
return child;
}
}
Debug.Log("ReturnedNull");
return null;
}```
whenever i run a loop for children inside a gameobject
it returns me the child
but it displays the same name
anyone can explain why?
or is it an engine error?
ok i understand my problem
you're only printing the name if it matches name
it didnt show me the nested children
only the children that were actually inside it
not the the childrens that were inside the other childrens
so i took a shortcut
return obj.transform;```
Well there's nothing in this code that would recursively check for children of children
it can cause errors
any ideas how to?
you would need to either use recursion or a stack
ok
private Transform FindBoneWithName(Transform root, string name)
{
for(int i = 0; i < root.childCount; i++)
{
Transform child = root.GetChild(i);
Debug.Log(child.name);
if(child.name == name)
{
Debug.Log(child.name);
return child;
}
Transform recursiveResult = FindBoneWithName(child, name);
if (recursiveResult != null) return recursiveResult;
}
Debug.Log("ReturnedNull");
return null;
}``` A simple recursive approach
you will need to initially call this with FindBoneWithName(RigBase.transform, "whatevername");
thanks
let me try this one out
should be
Transform recursiveResult = FindBoneWithName(child, name);
ah yes, you're correct
@snow warren fixed the code as per Steve's suggestion
isnt it the same thing?
no
very important difference
this will work, the other way would not work (it would result in a stack overflow error)
yea it resulted
I changed FindBoneWithName(root, name); to FindBoneWithName(child, name);
hii guys im trying to make it so that damage gets taken away from the players health every 5 seconds , but after the first time the damage gets taken away without the 5 second wait, can anyone tell me what im doing wrong?
you start the coroutine every frame that the condition is true. starting a new instance of the coroutine does not wait for the previous instances to finish, so you end up starting hundreds of completely separate instances of that coroutine
also don't crosspost. delete the post in #archived-code-general and #💻┃unity-talk
Is this message correct Physics2D.BoxCastNonAlloc is deprecated. Use Physics2D.BoxCast instead. since BoxCastNonAlloc allows you to get multiple hits and BoxCast only gives one, I am confused?
did you look at the documentation for Physics2D.BoxCast?
No, from my editor code insight
i understand that is where the error message is coming from. i'm asking if you've even bothered looking at the documentation for BoxCast considering you've stated that it only gives one. but you can check the documentation to see that isn't the only case
yes, that was the point i was making
ooh ok how do i only make one? also ty for the answer
well for starters, you don't even need a coroutine. simply incrementing a timer in the existing if statement in Update and only removing the health at set intervals would be sufficient. otherwise you need to track when the coroutine has started and ended
ty ill use a timer
sorry to bother you again may u please send me a time documentation i cant find anything
"unity timer"
float time = 10.0f;
time -= Time.deltaTime;
like this?
How would you guys recommend best for learning Unity and C# programming for someone who just started?
I've done Microsoft's C# learning paths, but a lot of whats needed in Unity isn't taught in those beginner paths.
So should I just keep following tutorials for my first couple games until I get a hang of it? Should I mainly try and learn from just Unity documentation/other online forums and manuals?
there are beginner c# courses pinned in this channel. after completing them the pathways on the unity !learn site will help you learn how to use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you 📦 friend 
@slender nymph wat am i doing wrong lol
Time is underlined for a reason
sorry im not very good with unity do u know wat the reason is , id be very grateful
What does the IDE say bout that variable?
wat does ide mean sry
the thing you type code in
(Visual Studios helper pop-up things)
Private member 'PlayerHealth.time' can be removed as the value assigned to it is never read
Yep. That does seem to be the case
You never use the variable, so it might as well not exist
so either actually use the value for something, or remove it
oh ok im using it in the if statement
Where?
No, where are you using it
Where does it matter what value that variable has

i dont even know myself i just want it to pause can u help?
If you don't even know what you want the variable for how am I supposed to explain what you want to use the variable for
no point in defining time if youre gonna set it to Time.deltatime
Thats like saying i=3 and then saying i=24 in the next line. Setting it to 3 is redundant
(i think)
There's no point in having a variable at all if you never use it for anything
At no point does this code do anything differently no matter what timee is
ahhh just using deltatime in the first place then? 
It could be 3, it could be 24, it could be -525,600 and it doesn't matter
Nothing uses it
The code would be literally identical if the variable were just deleted entirely
(srry ik this isnt my code im just siphoning ur knowledge)
AH, so bc his code either isnt finished yet or just doesnt use time in it at all ,thats why it isnt working 
ooh its meant to make a pause in between every time the player takes damage
So, you have a variable that you're subtracting the time each frame took to render from it each frame. So, you have a variable that counts down in real time.
What do you want to do with it
float renderCoolGraphics = 3;
no amount of wishful thinking will cause this to do anything on its own
@mental palm are you sure you are looking at the right messages? #💻┃unity-talk message
Hey guys weird questions
Im making a CookieClicker knock off (lol) and i need to check if the cookieAmount ist bigger than a certain variable (milestone)
that works perfetcly until you reach 1000 cookies... I tried
Debug.Log(CookieCount > 1000) ```
wich prints: 1,045 and false wich is ridiculous
my CookieCount is stored as a double and in the inspector it shows 1045 and in other scripts it behaves like its 1045 but i feel like this if statement in particular is reading the 1045 as 1,045(decimal)
Does anyone know anything about that?
notably -- make sure that "Collapse" is disabled in the console
that could cause very misleading results
it combines duplicate messages together
yes so i thought of that too but no im definitely looking at the right message
its in update function so it prints false once per frame XD
If CookieCount contains a value of 1045, then there is absolutely no way for CookieCount > 1000 to return false
yes, please
Ik 😭 thats why im so confused
ok wait a seconf
can someone explain how i get my e click to stop playing sound ive been trying all day
Can you send that using a paste site? !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You want to set it to false..?
Why are you checking the name of this object? Don't you already know what object it's on by virtue of putting the script on that object?
yep
nice
I do not see any lines that match the code you posted. Are you talking about lines 92-94?
yes
i set to false that didnt worrrk
92-94
Let me repeat my question from earlier: How do you know your code is running at all?
I bet you have several of these scripts in the scene, or looking at the wrong message.
in the same script whenever i press left on the box it plays music
so i know part of it work
So what?
How do you know that this code is running?
if disabled all the other debugs so theres only this one and the script exists only once
de bug with console log im sure
the weird thing about it is that everything works consistent up until 1000
You can find out if it is by adding some debug statements, yes
Put some log statements inside of both if statements
as well as before that entire block of code
find out what, exactly, is happening
ok
notably, there are three debug statements in the actual code
the second one could saying "True" while the third one is saying "False"
they both say false
Show a screenshot of your console
aight
(the entire console window)
are you French, by any chance
german
hm, maybe..
because that would cause a number between 2 and 3 to render as 2,5
Oh yeah
??? wut
The German decimal separator is a comma
Your number is actually very small
yeah so it does read the 2000 as 2.0 right?
but i dont understand why cause in the inspector of my Game mananger script (holding the cookie Count variable) it says 2000
to sanity check, actually type in 2000 into the inspector
This will have no effect on how comparison works
It'd strictly be how the number gets turned into a string
If you typed in 2,000 into the inspector, it's possible that you'll get a value of 2
I'm not sure how that works out
Could cast it to an int before printing
as a debug?
Debug.Log(2000) ?
ah ok
don't type 2,000 or 2.000 or anything else
gimme one sec
so it says 2000 in the inspector but 2 in the console
wtf
as soon as i tap a little it goes to 2, something
Your inspector is in debug mode. You should put back into the normal mode
click the little three-dots button in the very top right
the cookieCount is hidden in the inspector
ah
yeah yeah ik
what is "unformatted cookie count"?
It sounds like you're doing something very weird here...
im not a complete beginner i have like 2 years of unity but im a little stupid sometimes
share the entire script for the cookie manager
ah, yes
this is your problem
you are dividing the cookie count by 1000 here, then calling CheckSlider
2000 has become 2
You were seeing 2,123 or whatever because that's your decimal separator
so as you see in update cookie text the 1000 is formatted into 1a so i thought that might affect the cookieCount so i initialized a variable called unformated cookies 💀 for debug but its not used i think
if you used an American culture to turn that double into a string, you'd see 2.123
ah i see
so thats what i thought the formating of the numbers affects the value, but why does it still show 2000 in the inspector
Because the original number isn't getting changed
OH BECAUSE THE DOUBLE cant show decimals
oh wait
cookieCount is an argument to the method I screenshotted here
It's getting divided by 1000
The original number (which lives over in the "cookie manager" class) is not being changed
ahhh but i pas the argument instead of refering back to the original value
yeah well thats wuite stupid
comma decimal separator jumpscare
😭
If you got up to a cookie count of 1234567, you'd see 1,234567
your code would divide by 1000 twice
yeah just realized
@swift crag IT WORKS
thanks for helping me
also wtf you are smart fucking detective moment when you asked if i was french lol
I've seen this kind of thing once or twice haha
i see
(although, mostly with problems parsing data)
this was the opposite
definitely a funny connection to make, haha
If just recently seen a video telling me to pay close attention to the difference between copies and refernces but because it said cookieCount ( and i wasnt in this project for a longer time) i thought that was the original value i didnt even question it
I'm getting a null reference exception when I start the game on line 40 of CircularSpawner.cs https://hatebin.com/ecvydozvpw. This could be because of currentSheep being null instead of the newly instantiated sheep, or it could be an issue with setting the currentSheep spawner to this instance. The public method being called is in line 179 SheepMovement.cs https://hatebin.com/yfosmotlzd. Please let me know if you need more info.
if the NRE occurs on line 40 and not within the method called on line 40, then currentSheep is null which means the instantiated object does not have a SheepMovement component on it
but also, if you use the actual component you care about as the type for your prefab variable (in this case objectToSpawn) then Instantiate will return the correct component so you won't need the GetComponent call. it will also prevent you from adding the wrong kind of object in the inspector
Okay that must be it. But the object does have a SheepMovement component
not according to the error
I have the type as transform because I use CircularSpawner for other things
like grass
then why does the spawn method depend on a specific kind of component? obviously that will throw an exception when used with literally any other object
i'd recommend instead defining an interface that has this SetSpawner method then using TryGetComponent to get that interface on the instantiated objects so you can then pass this to it. Then just have SheepMovement implement the interface. you can also completely remove the if statement inside of the loop, the overload that accepts a parent just calls the one that doesn't if the parent parameter is null
so then the contents of the loop just ends up becoming:
var instance = Instantiate(objectToSpawn,
(Random.insideUnitCircle * spawnRadius) + origin,
Quaternion.identity,
objectContainer);
if(instance.TryGetComponent(out ISetSpawnerInterface setSpawner))
{
setSpawner.SetSpawner(this);
}
👍 I'll give it a try. thank you
also make sure to choose a better name for the interface, that was just an example since i don't know what the actual purpose of calling that method is (other than what is hinted at by the name)
I named it ISpawnable
If I have the line the line of code
If (Input.GetMouseButtonDown(0))
Is there something that lets me activate code when the player clicks and then a separate set of code that activates when the player releases the mouse button if they are holding it down?
GetMouseButtonUp will be the one you want to check for releasing the button
For context I am making a weapon that fires a laser the laser is just a cylinder that I want to become active when the player starts the click and becomes inactive when they release the mouse button
Ah thank you
then why not just use GetButton instead of GetButtonDown? otherwise, i already told you what you can use to check when the button is released
Not on the best wifi rn didn’t see it
But still thank you
Ok that works perfectly thank you
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I keep getting object reference errors for the slider, what am I doing wrong here?
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using UnityEngine.UI;
using VRC.Utility;
public class Slider_Cube : MonoBehaviour
{
private Slider slider;
public Transform anchor_1;
public Transform control_1;
public Transform control_2;
public Transform anchor_2;
public GameObject cube;
void Start()
{
slider = transform.GetComponent<Slider>();
cube.transform.position = anchor_1.position;
}
void OnEnable()
{
slider = transform.GetComponent<Slider>();
}
// Update the cube's position
public void SlideUpdate() {
Debug.Log(slider.value);
cube.transform.position = BezierPoint(slider.value);
}
// Calculate the vector at the point along the line
private Vector3 BezierPoint(float t) { ... }
// Draws white line showing the bezier's path
void OnDrawGizmos(){ ... }
}
The error points to first line in SlideUpdate
You've the idea with the logging. There's only a few other things that can be null so keep trying
Well, here's some more advice. Make sure you log the object before trying to dot access its values
I'm confused on what the lifecycle is, when it comes to editor and runtime event invokations.
I thought Start(), Awake() or OnEnable() would allow setting some fields before any events began firing.
The simplest solution is just to reference the slider in the inspector
you mean just use public/serialized fields?
Yes
I suppose so; I was trying to keep things encapsulated. But it seems it's not possible, or not in a clean way
slider is null
did you ever remove and readd the script
idk about onenable but awake isn't called on domain reload
oh u used start
yeah use awak
then readd the script
otherwise the reference won't be there except in runtime
Awake is for initialization and setting values, Start is for actual behaviour
why is my 2d game looking all weird like this, is my text too small in text mesh pro?
I'm getting a UnityEventFilter error, telling me events on Slider were removed because one of them targeted a prohibited type. What does this even mean?
Show the whole error, including the stack trace?
So everything you see in the bottom of the console with that error selected
Probably more of a #📲┃ui-ux question
[UnityEventFilter] Events on 'Slider' were removed because one of them targeted a prohibited type 'SliderCube', method 'SlideUpdate' or object 'Slider'.
UnityEngine.Debug:LogWarning (object,UnityEngine.Object)
VRC.Core.Logger:LogWarning (string,int,UnityEngine.Object)
VRC.Core.UnityEventFilter:LogRemoval (string,UnityEngine.Object) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:442)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.HashSet`1<object>,VRC.Core.UnityEventFilter/TypeInfo,object,UnityEngine.Component) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:360)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.ICollection`1<UnityEngine.Component>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:322)
VRC.Core.UnityEventFilter:FilterUnityEvents (System.Collections.Generic.List`1<UnityEngine.GameObject>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:278)
VRC.Core.UnityEventFilter:FilterEvents (System.Collections.Generic.List`1<UnityEngine.GameObject>) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:254)
VRC.Core.UnityEventFilter:RunFilteringOnPlayModeEntry (UnityEditor.PlayModeStateChange) (at ./Packages/com.vrchat.worlds/Runtime/VRCSDK/SDK3/UnityEventFilter.cs:125)
UnityEditor.EditorApplication:Internal_PlayModeStateChanged (UnityEditor.PlayModeStateChange)
Seems specific to VRChat. Ask in !vrchat and/or search this error online
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
I'm trying to add force only to the x axis but it doesnt work. when i check in the RigidBody2D component of the object im trying to move it shows the attached video when i click the mouse button. this is my script, please help.
private void FixedUpdate()
{
_mode = _wheelScript.CurrentMode;
WaterControl(_mode);
WindControl(_mode);
}
private void WindControl(Mode curMode)
{
if (curMode != Mode.Wind) return;
if (Input.GetMouseButton(0))
{
Debug.Log("Click");
_rb2dBoat.AddForceX(windSpeed);
}
else if (Input.GetMouseButton(1))
{
Debug.Log("Click");
_rb2dBoat.AddForceX(-windSpeed);
}
}
It prints out the "Click" message so it isnt something with the inputs
Do not read Input in FixedUpdate
istg it was in update and didnt work, so i changed it to FixedUpdate and it still didnt work, and now it works
when i set the windSpeed variable to something smaller than 8, it stops moving the object
because it's not enough force
Probably a combo of missed input(due to fixed update) and friction.
its now just a regular Update
Then friction.
Also, add force should be in fixed update.
but @languid spire told me to not read input in FixedUpdate
you can read it a bit up the thread
You read Input in Update you consume it in FixedUpdate in your case
and how do i do that? this feels like a dumb question but i actually dont know how
And that's correct. Input in regular update. Physics in fixed update.
Class fields
something like
bool pressed = false;
void Update() {
if (Input.GetKeyDown(KeyCode.space)) pressed = true;
}
void FixedUpdate() {
if (pressed) {
pressed = false;
//DO STUFF
}
}
so this?
bool pressedLeft = false;
bool pressedRight = false;
private void Update()
{
_mode = _wheelScript.CurrentMode;
if (Input.GetMouseButton(0)) pressedLeft = true;
if (Input.GetMouseButton(1)) pressedRight = true;
}
void FixedUpdate()
{
WaterControl(_mode);
WindControl(_mode);
}
private void WindControl(Mode curMode)
{
if (curMode != Mode.Wind) return;
if (pressedLeft)
{
Debug.Log("Click");
_rb2dBoat.AddForceX(windSpeed);
pressedLeft = false;
}
else if (pressedRight)
{
Debug.Log("Click");
_rb2dBoat.AddForceX(-windSpeed);
pressedRight = false;
}
}
it doesnt move at all now
even if the windSpeed is 8(what worked before)
GetMouseButton is perfectly fine in FixedUpdate. GetMouseButtonDown is not
I guess the issue is that it is possible your input is not registered if you somehow press your mouse between the frames where FixedUpdate is not invoked
It is technically fine, but it can not register input if you are the Flash
i changed the code like you recommended:
private void FixedUpdate()
{
_mode = _wheelScript.CurrentMode;
WaterControl(_mode);
WindControl(_mode);
}
private void WindControl(Mode curMode)
{
if (curMode != Mode.Wind) return;
if (Input.GetMouseButton(0))
{
Debug.Log("Click");
_rb2dBoat.AddForceX(windSpeed);
}
else if (Input.GetMouseButton(1))
{
Debug.Log("Click");
_rb2dBoat.AddForceX(-windSpeed);
}
}
and it still doesnt work
why not log _mode
it still prints out "Click" so it runs
What is windSpeed here?
Log that
Especially since none of your code has any context around this variable, it is entirely possible you changed this by accident
it doesnt change. i only set the value of it in the editor
Wdym exactly, something like this?
-Update: pressed true
-Update: pressed false
-FixedUpdate: pressed false
I mean more or less when you press the mouse between FixedUpdate invokes.
Say x is a FixedUpdate call, o is me pressing the mouse down, m pressing it back up, and - is a frame.
---x---o----m----x----
Very, very unlikely
In that scenario, caching the mouse press state in updates o and m would still result in the mouse press being false in the second x
I don't think there's a difference between caching the value in Update or just using GetMouseButton in FixedUpdate
Since fixedupdate always has the most recent frame's input
@burnt vapor if it helps, i found that the linear velocity values change on the rigidbody of the object but the X position doesnt change.
not got constraints enabled have you ?
If my testing methology is correct, you might event get one frame old inputs if you cache them in Update and use in FixedUpdate```cs
int frame => Time.frameCount;
bool pressedUpdate = false;
bool pressedFixed = false;
void Update()
{
var p = Input.GetMouseButton(0);
if (p && !pressedUpdate)
Debug.Log($"Mouse press detected Update {frame}");
pressedUpdate = p;
}
void FixedUpdate()
{
var p = Input.GetMouseButton(0);
if (p && !pressedFixed)
Debug.Log($"Mouse press detected FixedUpdate {frame}");
pressedFixed = p;
if (pressedFixed != pressedUpdate)
Debug.LogError($"Most recent mouse state from Update was incorrect {frame}");
}```
Because in some fixedupdates the cached update value is not up to date
(This is specifically for the scenario where you only use the inputs in FixedUpdate)
your logic is wrong. If you press and release before FixedUpdate you will miss the press
Now in that scenario, if i cache the value in the Updates, what is the cached value in FixedUpdate?
It would be false, no? So you miss it anyway?
If the bool is used like a trigger, then it would make sense
Like keep it true until used
no, you cache only when pressed.
Read in Input. Consume in FixedUpdate
So you don't set it to false when you release the mouse in Update?
Note that I'm talking about GetMouseButton, not GetMouseButtonDown
no, only when you have used it in Fixed
Talking continuous input here
What you are saying is perfectly valid for this^
for continuous input in theory you are correct but, because of potential hardware buffering on the device, it is much better to clear the input buffer on a frame by frame basis
now i have no context but why would this be false
it would be set to false in the next update
We were talking two updates happening between the fixed updates
Like this #💻┃code-beginner message
So pressing and also releasing the mouse between fixed updates
Which is a valid concern yeah. Easily reproducible if you set fixed time step to 0.1+ seconds
I think the most robust way would be to use a combination of fixedupdate and update input
To solve both the "press and release between fixedupdates" issue and the potential one frame delay
Well there's the edge case issue that we were discussing 🤷♂️
Yeah. More of an issue if your fixed timestep is higher
@languid spire maybe the problem is in my rigidbody settings?