#💻┃code-beginner
1 messages · Page 346 of 1
oh yeah putting in the max distance causes an error
it doesnt like that i put in 4 arguments
come on, you ask a silly question, you get a silly answer
hey it was real hard for me to find where to learn programming at first too
those learn pages are decently hidden
You got rid of the mandatory out parameter
oh whoops
i dont really understand why do i have to take a quiz if they taught me nothing
i watched the video but then i when i went to my first mission it gave me a quiz to start off
okay i think i understand how steve smith feels now
@short hazel it gives another error, this time saying that argument 4 may not be passed with the out keyword, i tried to fix it myself since ive already asked so much but i just cant figure it out
i think it wants a quaternion in between the out and the maxdistance
Your arguments seem to be out of order, they must conform to one of the available overloads mentioned in the docs I've linked
When one of the parameters have an equals sign (eg. Quaternion orientation = Quaternion.identity) it can be omitted, it is optional
everything seems to be in order
the error goes away if i put an orientation in
its the wrong rotation but i was just using it to check
I guess it can't determine which overload to use when you don't supply the optional parameters in order
You technically don't need the out variable so you can use the overload that doesn't have it
how can i fix this? when walking my leg does that
like this?
Yeah but put the orientation too, pass Quaternion.identity
It's how the box is rotated, not to be mixed up with where it goes. Best to leave it not rotated by default
i tried using new Quaternion(0,0,0,0) to get that effect but it didnt seem to work
This represents a rotation with no rotation
i thought so
would boxCenter.rotation work
or something
that isnt right
hold on ill figure it out
No you just pass Quaternion.identity directly!!!
BoxCast(..., Quaternion.identity, ...)
Ahh
it uses the "identity rotation"
what is that the rotation of specifically? the Vector3?
cause 0,0,0,0 would make no sense as rotation
yes i realized that after
Identity represents 0 degrees on all 3 axes
got it
Quaternions store rotations on 4 values internally to mitigate some issues, each value ranging from -1 to 1
You don't mess with them directly
thanks for all the help, this is the final bit of code. the players height is at 3, and i wanted a bit of wiggle room to jump in case you hit the spacebar too early
oops let me get rid of that useless vector
and the raycasthit
and i can just make the return true; instead of all that
If you have issues when installing, ask in #💻┃unity-talk as it's not a code issue. It doesn't come from your own programming, at least
is there an easy way to get the side of a hitbox? to test for collision with walls
or should i just tag every wall with a wall tag
You usually make other physics casts for that. I did that for a wall run mechanic once
Raycasts left and right of the player
use the normal from a RaycastHit or ContactPoint
alright i think i can do that without any help
its kinda silly though right now if i run into a wall hard enough its like walking through jelly
That means you're moving in a way that doesn't respect the physics engine, if you can go into it slightly
heres the movement right now, im gonna move it into its own voids soon to get it out of update
transform.Translate is your problem
yeah i know its not a great thing
Yep you should be using the Rigidbody
i should be using rigidbody movement
transform.translate sucks
ive used the rigidbody already for a different test i was doing it looked like this
This looks like an old input system problem
yeah i was following a fairly old tutorial then
Hello guys I have a quick question about musics in my game. I have a playlist of two musics right now and when the second starts my game lag for 2 seconds. Can someone help me with this ?
it wanted to make its own input system instead of using unitys built in one
Yikes
I think your foundation is entirely borked here
dont worry its from a test game that ive already finished
In the inspector there's a Preload Audio Data box when you select audio
yes
I'd recommend taking some time to learn the new input system. Realistically all you need to do is get the direction of the control stick and then translate that information to a Vector3. Then just move the player with that Vector3.
What you have now looks like trying to use an old broken car because it's familiar.
Even with the legacy input system, you can construct a vector from the horizontal and vertical axes
If it's going on android, then switch it to android
but only if it's only going on android
Again ask in #💻┃unity-talk, you're in a code channel!
this code is improved but it doesnt seem to be doing what i want(speed is set to 0.1f)
i think the main issues are the max speed isnt working, and i also slide really far before stopping instead of stopping over 0.1f
what's the problem at hand
wait i think i see the problem for one of those
something like this should stop the player instantly when no WASD keys are being pressed, since it does the opposite velocity force
i just need to multiply it by something to make it slow down over a short period of time
That lerp is returning a number very close to currentSpeed. Is that what you want?
The currentSpeed is slowing down by almost nothing
sorry its from code i had earlier that was making it slow down using some other code that i got rid of
I thought of why you'd need impulse force to move
also uhh what i did did not work
it sent me flying downward at what im assuming was infinite speed
Do you want the player to slowdown when stopping or to stop completely?
Like, still slide a little bit when stopping?
slowdown, but not at the speed it is without any code
Because that if statement is always true, so it keeps adding negative force
yeah
but slowdown over a period of 0.1f seconds
i just thought it would start adding 0,0,0 force since the rb.velocity should go to 0 when you stop moving
but it must have not gone exactly to 0 since i was adding it backward
and then it went back and force
forth
from positive to negative
You could try tuning the friction factor down for 0.1f seconds
But I believe you could try and use something similar to knockback
is that in project settings
Yo guys, how do I replace the last line to use my rigidbody instead of the transform.Translate?
void FixedUpdate()
{
Vector3 forwardDirection = transform.forward;
Vector3 movement = new Vector3(move.x, 0.0f, move.y) * moveSpeed * Time.deltaTime;
// Rotate the movement vector based on the player's forward direction
movement = Quaternion.LookRotation(forwardDirection) * movement;
transform.Translate(movement, Space.World);
}
or should i add a physic material to the player
physic material
There is also something called drag
Rigidbody.Velocity = movement should work
that's slightly pseudocode btw
I've tried, but it doesn't work
Oh, that's a vector3, not a var
Ye
I think ill use drag instead. using friction caused some weird jolty movement when i jumped
more specifically when i landed
I dunno with drag will help actually
actually, are you getting your component properly first and foremost
You could try and set the friction back to normal when landing
Or even when pressing the jump button
Drag messes with your acceleration as well. Everything that moves the player will need to be adjusted for drag
draga works
Oh it did?
yeah
Oh cool
yes
alright
remove your multiplications from your movement vector and put them in the rb.velocity line
i have two gameobject floors here at the same height touching each other. sometimes when i run across it, it gets stuck for a second and makes me lose speed
Ait, like this?
``` void FixedUpdate()
{
Vector3 forwardDirection = transform.forward;
Vector3 movement = new Vector3(move.x, 0.0f, move.y);
// Rotate the movement vector based on the player's forward direction
movement = Quaternion.LookRotation(forwardDirection) * movement;
//transform.Translate(movement, Space.World);
rb.velocity = movement * moveSpeed * Time.deltaTime;
}```
yes
Without seeing how you're moving, it's not really possible to help
I still cannot move though
I do glide every so slightly for some reason (but that is not speed related)
Sounds like an inspector issue
this is from above
ignore the useless if statement i havent removed it yet it was for something else
How so? btw, if you need anymore context/screens lemme know
!code
Ideally just put everything in 1 complete message so it's easy for anyone to help.
For movement I also really suggest adding debug drawray a lot to see where you are even trying to move
📃 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.
code is correct, so unless something else is stopping your velocity, something is going wrong on the editor's end, not the code
Where I find good tutorial which explain how to change UI toolkit uxml layouts to another?
Honestly I dont even see the issue you describe in the video, it looks normal to me but im on mobile.
you can see my camera(connected to player rigidbody) stop moving as the player hitbox hits the side of either of the floor hitboxes for some reason
but only sometimes, which is odd
Anything obviously wrong here? 😕
The code itself looks like it has no care about what the object is on, so it could just be an issue with the setup. Like if you have a physics material on one but not the other. Or maybe if theres a small gap between them
This looks like a bogus collision with the floor. This can happen where two colliders meet.
It's worse with certain collision detection modes https://docs.unity3d.com/Manual/speculative-ccd.html
check your constraints in the rigidbody
there shouldnt be a gap and nothing has a physics material. i used math to calculate the exact transforms and sizes for the floors and it ended with whole numbers or 0.5 plus a whole number
which means if there was a gap id be able to see it
what is the technical name for something like this
i just say
set the Moveinputs value to the move input
Set the drag to what it was before, it was the only thing you changed.
ill try it
but i feel like it might have happened in the past i just didnt notice it till now
translate your control stick's vector2 into a vector3
Are you trying to write comments for your lines of code?
tested, changing drag back to 0 and it still happens
yeah
I wonder if it's happening because gravity gives you a very slight downward velocity
Can you show me the inspector for the rigidbody?
What fen said is likely the cause, but you could honestly just use a terrain or single collider here to solve it.
Any object will have this issue going over a bump though usually it results in a very small difference that you never see
Oh box collider for the player is probably making it worse
its going to be a roadway and a little pre-area floor (like in front of a building)
@plain dagger
i am curious
//Update movement relative to Vertical and Horizontal input axis```
change to capsule?
and yeah, capsule colliders can help smooth out that kind of behavior
thats what people thought i had originally so im assuming thats what i should use
I feel like capsule collider should be more smooth considering its way less area hitting the bump
although they can also allow things to climb on top of each other, which gets annoying
swag
This is an assignment. You are assigning the Vector3 to your moveInput variable.
I'd just asy "read move input" if I had to write a comment
I might note that I'm reading X and Y into X and Z
if its not an inspector issue then somewhere you've got code stopping your object's velocity, or that code isn't running in the first place (just test that with a debug.log)
changing to a capsule collider worked great
Yo since the unity 6 change idk how to check the velocity of a object to see if its moving. Anyone able to help? They changed how rigidbody.velocity works
but i do want to see about combining nearby floors like that to a single collider
if its not too hard to do
Also, check how you're even getting the movement values
gpt came up with this line that works: rb.MovePosition(transform.position + movement);
you approve? haha
no 
hahahaha
It's now linearVelocity. If they did it right, using velocity should report an obsoletion warning/error which tells you what to use instead.
This is really just a matter of having a single collider, and then u can even have 2 objects for the visuals. Nothing complicated about it.
Otherwise you must combine it in a 3d modeling tool if its complicated geometry (I see it's not here) and have some texture png for the visuals
yeah the geometry is really simple right now, its just roadways and soon to be sidewalks, then building floors
Yeah I have tried that but even if the object isnt moving its just going down non stop
I mean if it works it works right. Altough there is still a lot of weird stuff going on
Looks like you've got gravity
is there like a way for the ui image to know that it's still the player that are rescuing muons even if the player dies and new player gameobject appears? because the gameobject script that holds the ui image disappears from the muon UI Controller gameobject in the new player object https://gdl.space/pimefadoma.cs (this is the script in the ui image for the muon images)
Figured it out. I had to use navmesh agent velocity instead. Didnt have to in earlier unity versions but looks like I have to now
Was the clone already present or did it spawn after the first muon's death?
the player object spawned after the current player object's death
So when you spawn it, you'd set up that field:cs var playerClone = Instantiate(playerOne, ..., ...); playerClone.muonUIController = playerOne.muonUIController;assuming the previous muon player spawns the next muon player (semantics)
no, not new muons appear. they are like the ones you need to rescue, like in Kirby's return to dream land you need to collect gears
https://gdl.space/werehedeni.cpp, and this one was what the player have which is holding the Muon Bar ui image
so i set it up somewhere in MuonUiController like SetMuonRescued?
You'd update the controller where you'd instantiate the new player
oh, well the onlt script i know have that like playerOne and playerTwo thing is here https://gdl.space/afaramepiy.cs
The game manager instance can be accessed anywhere (which is convenient in itself) but you'd want to set up the next player when/where you instantiate it.
Maybe show where you're instantiating the new player (likely on the player's death - assuming the next player isn't already in the scene)
https://gdl.space/bacoxonoxi.cs well the only script i know which spawns the new player is this one
Are there multiple muon ui controllers in the scene or only one? @hushed hinge
I've got a joystick script and I'm using unity remote to simulate it on my phone, which is working just fine. However, when using the joystick and having a finger touch anywhere else on the screen, the joystick freezes until this bonus finger input is taken off the screen. To stop this, is there a way to stop unity from even recognizing this extra input if it's not inside a certain area?
there's 3 different muon objects with muon Controller script
while this is the ui image (the screenshots are being slow to take)
If there's only one, when you instantiate the player in the manager, you'd just setup the muon ui controller (assuming the manager really has access to it)cs public PlayerComponents SpawnPlayer(int playerNumber, Vector3 position, Transform parent = null) { if (playerNumber == 1) { playerOne = Instantiate(playerOnePrefab, position, Quaternion.identity, parent); playerOne.muonUIController = muonUIController; return playerOne; } else { playerTwo = Instantiate(playerTwoPrefab, position, Quaternion.identity, parent); playerTwo.muonUIController = muonUIController; return playerTwo; } }
I was referring to the ui controller
oh well. this ui image with 3 different images as children that to know if it shows which muons you have rescued whicht he black face changes to no black face and instead to the face on the muon,
I've got to run, this #💻┃code-beginner message should be the solution. Good luck 
How can I make a shop system but whenever I buy an item it immediately does its effect?
ok, but muonUIController have a red underline even though i have public MuonUIController muonUIController; should i make is static?
Im planning on doing a template for each of the icons but how can I make it possible that when one is pressed, the effect applies immediately
When asking for help with an error, you should post the error 🏃
Can anyone please help me with this? I might be overcomplicating the issue but I've tried everything I can think of
Does PlayerComponents contain a definition for muonUIController
In the video you have sent, the component "Muon Interaction" is missing the reference to the controller. So you should get that component, and set it there.
I recall the purpose of your player components script to be a mediator for all other components on the player object. If the above post is correct and that your necessary reference is from the interaction component (that's hopefully on the player), update your player components script to account for the new component on the player and assign the muon ui controller appropriately through references. cs playerOne.muonInteraction.muonUIController = muonUIController;
right now yeah, but right now in the playermanager
"The effect" is incredibly vague. What effect? This could be literally anything from adding a float or closing the game.
Either way you'll likely need some abstract class or interface which guarantees an item implements an effect method. It also needs parameters for anything an item may need for such effect
What's that error say
Okay, thanks a lot
I won't be able to help you further (I'm quite busy now) but if this is being done in the player manager script, you ought to have a reference to that https://gdl.space/afaramepiy.cs on line 21
there we go
List<FormationPositions> targetPosition;
targetPosition.Add(new FormationPositions());
Why is this not valid?
FormationPositions is a MonoBehaviour.
you should not be manually calling a MonoBehaviour's constructor. which you should be receiving a warning about in the editor console at runtime
unless this is like your exact code, in which case you don't initialize the list and therefore get a NRE
new with MonoBehaviours is not allowed.
Do you have a link describing that in more detail or showing the proper way to do it?
I still dont really understand
MonoBehaviors can only be created by:
- Attaching them manually in the editor
- Calling
AddComponent<FormationPosition>()on a GameObject - Calling Instantiate
but however, when i die and resapwn, and when i tried to rescue the second muon, i get this error line
multiple things are not assigned in this new clone
which is why you get that error probably
but like which ones?
the ones that say none
in the inspector
i can see 3
like that in player component and Muon interaction?
yeah
even if i can assign them in the player gameobject, i can't assign them in the player prefab
public class FormationPositions: MonoBehaviour
{
GameObject markerPrefab;
public GameObject formationTargetPosition; // for the formation overall
public List<GameObject> unitTargetPosition; // for individuals units
public void Start()
{
}
public void SetFormation(int unitCount, int width, int spacing, Transform position)
{
formationTargetPosition = Instantiate(new GameObject(), position);
markerPrefab = Resources.Load<GameObject>("Prefabs/DestinationMarker"); // temporary, loads destination marker type
int _depth = unitCount / width; // calculate formation depth
// offset to be centered
int xOffset = (spacing * width) / 2;
int yOffset = (spacing * _depth) / 2;
Debug.Log($"x offset = {xOffset} y offset ={yOffset}");
//fill list with position gameobjects
for (int index = 0; index < unitCount; index++)
{
//add unit position to list as prefab and as a child
unitTargetPosition.Add(Instantiate(markerPrefab, formationTargetPosition.transform));
}
//set position values for game objects
for (int x = 0; x < width; x++)
{
for (int y = 0; y < _depth; y++)
{
//set each position
int index = width * y + x; // get grid position off one dimensional vector.
unitTargetPosition[index].transform.localPosition = new Vector3(0 + spacing * x - xOffset, 0, 0 - spacing * y);
//Debug.Log($"{gameObject} index {index}: value ({unitTargetPosition[index].transform.position.x} , {unitTargetPosition[index].transform.position.y})");
}
}
}
}
I'm stuck using Monobehaviour due to needing to Instantiate() GameObjects within the class but I feel that the FormationPositions class is inappropriate as a Game Object. Maybe im missing the plot
because what your assigning belongs only in the scene probably
so you cant assign that to a prefab
Instantiate is a static method on the Object class, you do not need to inherit from MonoBehaviour in order to call that method
then idk how, becayse the gameobject is a new gameobject which is the new player
why even create a new player?
whats the difference between them
new GameObject() would create a new GameObject, so you don't need to instantiate it. instantiating a new GameObject doesn't make sense. It would just create 2 empty objects.
if a player dies, then a new one would respawn from the checkpoint
I dont know if anyone ever used the third person template of Unity, but how exactly does this code works? there's no reference to the PlayerInput. So does the OnMove look for a "Move" action in the active map?
yeah of course, but why a new one? whats the difference between new and old
it uses the PlayerInput component which sends the OnXXX messages to this component
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/PlayerInput.html
idk, it's that the player have destroy on exit
so if I create an action named Fly I need to create a function named OnFly?
so if there is no difference, then just keep the same player and change its position
So this formationTargetPosition = Instantiate(new GameObject(), position);, which works to create a new child Object, is wrong?
if your PlayerInput component is set to Send Messages then it will show the different messages it will send in the inspector
idk about that because that would change a lot in scripting that would be too much for to now know how
this creates two empty GameObjects because new GameObject() creates one, then you clone it as a child of whatever position is
just replace destroy and instantiate with changing the position?
and do whatever else you need, wont take longer than 1 hour at the very max
just saw that, and does it send a message only when I press a key or also when I release it?
A child is just an object parented to another object. Parenting is managed via the Transform component that every GameObject has.
it's too much work for me to change that much
then create even more work trying to assign the variables to this new clone
theres a couple ways to do this
how can I create an ID list of scriptable objects, kinda like Minecraft has an ID list for items?
I don't know how i can assign that is from the ui image to that, I did witht he others but i nevere did with ui
just add an int and give a value?
UI vs not UI has absolutely zero difference, they are both game objects and have a Transform component
but then when I want to spawn a scriptable object of ID 5 (example), how do I find the scriptable object matching this ID?
@deft grail
yet I don't know how to assign that if i can't assign it in the prefabs
create an array/list and add all the objects in order, or automatically add them and sort them based of the id
should work
you can have a gameobject which takes the references in the scene
like this, basically?
yet i don't know how even if i tried
var something = player.something;
basic C# really
yeah, then you can sort it automatically or manually if you want, just access the list with an id of the thing you want to use
that? but like in which script should i put like that one in?
new script new game object
How do i have this array remain constant accross all my scenes? Dont destroy on load?
sure
or this can also just be a scriptable object i think
probably by making it a scriptable object
a scriptable object with an array?
yeah the same way you made what you made now
and then i instanciate it in every scene to use it?
no? you just reference it
I think I understand what everyone is saying... so instead of formationTargetPosition = Instantiate(new GameObject(), this.transform); I should use formationTargetPosition.transform.parent = this.transform; correct?
need to do this the long way...
create a variable which will reference your main player thats already in the scene.
create more variables which will hold the variables you want to keep.
then set them from the player
I didn't know I could reference scriptable objects lol, thanks bro, you the man
why would you think that is what you want? didn't you want to create a new empty gameobject as a child of that other object?
Check the inspector for the player manager component (the one in the scene). Is muon ui controller setup properly?
I'm trying to create an object and set it to a transform parent in the script. Formation (Parent), Formation Target Position (Child).
It needs to be a child because setting movement orders in this game (think total war) requires a transform that is relative to the Formation's position overall.
The code I had worked, its just making too many object and was wrong apparently. I thought that replacing it and setting a child using the transform of the parent instead was the proper way?
hmm... let me check
nope, it isn't, aghhh, what is wrong with me not thinking straight?
Drag this object into that field
#💻┃code-beginner message
that one is muon ui controller that already ahve things assigned
If they're not unique per scene (maybe they're a part of the manager) it should work. Else you'll need to tell the manager in some start function which muon ui controller the scene is using.
We are not sure what is your current code, so we can't say if it's correct or not. But does it work as intended?
im learning unity for the first time and im already lost on this tutorial my code of "gameObject.name = "brah"; wont work and im not sure whats causing it
wdym by "won't work"?
be more specific about what happens
it doesnt change the name
📃 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 put it inside of the void start
Show your code
All kinds of things could be wrong
we won't know without seeing it
{
gameObject.name = "brr";
}```
Also you need to make sure your script is actually attached to an active GameObject in the scene
Both my old version which was flagged as incorrect and duplicating GameObjects and the replacement that only uses the tranforms are working.
The full script if you please
yeah its attached
using System.Collections.Generic;
using UnityEngine;
public class BirdScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
gameObject.name = "brr";
}
// Update is called once per frame
void Update()
{
}
}
its just the default code it gives me with the name script
Ok this looks alright, could you show a screenshot of the Unity Editor now with the object this script is attached to selected and the inspector window visible?
this?
The old version was creating duplicate unneeded objects, so you can't say that it was working correctly.
Yeah, drag the selected object into the manager's muon ui controller field or have the muon ui controller tell the manager which muon ui controller it should be referencing in it's start function.cs private void Start() { PlayerManager.instance.muonUIController = this; }
You'd do the second if each scene has their own muon ui controllers - I'm assuming you've got to rescue different muons per scene/stage.
but formationTargetPosition = Instantiate(new GameObject(), this.transform); works to make formationTargetPosition.transform a child of the GameObject the script is attached to, or at least has the appearence of such
in the playmanager script? ph yeah, rescue muons each stage
this also creates two objects
But it also creates one new object in the hierarchy that is not used. Are you saying that it's intended?
this implies that the statement is referring to the muon ui controller script
ok this may be a dumb question but doesn't formationTargetPosition act as a pointer to that new GameObject? Doesn't the garbage collection in C# take care of that duplicate?
or am I really not understanding? (probably 😭 )
GameObjects are not purely C# objects
they halfway live in the Unity Engine itself
as native objects
and thus will not be garbage collected
Also the engine itself maintains a reference to the C# half.
It's really easy to see yourself if you look in the hierarchy that your code creates extra objects that stick around
Game objects will need to be disposed of properly with the destroy function unless a change of scene has occurred or the application has terminated.
this implies that the statement should be called from the muon ui controller script
Meaning this should be placed in the muon ui controller script
Alright I think I understand now. I have a lot of cleanup in this code now haha. Last question on the Instantiate thing:
List<GameObject> units;
units.Add(Instantiate(unitPrefab, this.transform));
is the correct use of of Instantiate because its a List, right?
I've got to run again. Have a good day.
the list is pretty much irrelevant to the Instantiate code here
also if that's the actual code, it's not going to compile
Yeah the list is a public attribute of a class, I'm just smushing it together for brevity.
oh no i deleted a lot from scene one without me thinking that because i thought it was the second stage, how can i brings things back to there how things were and i can skip back?
ctrl z, if that doesnt work then you cant bring it back i think
..................😢
in this unity tutorial im wathcing whenever he writes code he gets this dropdown menu with a list of things but it doesnt show dropdown menus for me, why?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
How is Instantiating into a List irrelevant here?
It's called intellisense. Config your ide correctly for it to work.
but i have this... will it help me?
Because the list is just where you're storing the reference to the created object. It has nothing to do with the actual creation of the object.
Instantiating just creates a new copy of the object. Then you add that new copy(a reference to it actually) to the list, so technically, it's 2 different/irrelevant things.
if its up to date then of course, thats what its for
if it's up to date? then if it can help me, what should i do?
But I'm not creating duplicates when I use Instantiate this way, right? units.Add(Instantiate(unitPrefab, this.transform));
The red ones are things you deleted
No...
Well I mean
It would be up to date if you committed all your changes recently
Duplicating the prefab yeah, but not unintentionally
beyond the fact that Instantiate specifically duplicates an object, no
It looks like you may have NOT been up to date if you deleted more than two things
Add just adds the thing to a list, it doesn't create anything
and the thing it's adding to the list is just a reference
You could do this and it's the same:
var clone = Instantiate(unitPrefab, this.transform);
units.Add(clone);```
i know
I have a Cinemachine brain, virtual camera, and a player game object. All are prefabs. I assign the player prefab to the 'Follow' transform in the virtual camera's inspector. The player prefab loads on start via a script. The camera is in the scene. It wont follow the player.
If I drag the player prefab into the scene manually, then drag it onto the camera's follow, it now works.
NOW...Both player and camera objects are set to don't destroy on load. I load a second scene. The camera is following the player. When I load the first scene back. The camera won't follow the player. The transform isn't missing BUT when I change the camera's Culling Mask to nothing and back to default while still in play mode, IT STARTS WORKING.
So frustrating.
okay you guys rock thanks for the patience 🙏
Well yeah you're trying to have it follow a prefab, which never moves because it's a prefab.
Not sure about the whole culling mask thing
If you know then what are you asking?
You sent a picture of selecting NOT a deleted thing
ok now i have a qustion: why the hell is the counter not going up? it's not being reset anywhere
On mobile there is not enough resolution to read that code. Can you share it properly?
show the full script?
!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 can't find so many deleted things
Thank you for the quick response I did not know that.
I don't know what that means
there is scene stage 1-1 where a lot of things have changed. and what i mean like i can't find which objects have red dots in the github desktop and it's just a tiny few
!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 already explained that. You were not up to date. You are shit out of luck
The point of version control is that you commit changes often
what do you mean by I were not up to date?
I already explained that above
https://gdl.space/otulahuxak.cpp
are dictionaries efficient here, it works and someone suggested enum but dictionaries look neater and easier to control
enums and dictionaries solve completely different problems
they're not comparable
I mean I was told to try an enum but when for a dictionary in the end
...............I don't know what to say...
You could and should use enums as the key to the dictionary instead of strings though
That is an absurd use for a dictionary though
This is XY problem. Don't ask about solutions, ask about the problem; we can provide the solution.
Ok 👍
I mean a Dictioanry<string, bool> is pretty useless though yeah
😢
it looks so neat
this could literally just be 3 bool variables the way you're using it
It looks horrible. All of these could be bools
I agree. The implementation seems largely redundant and difficult to read.
Why do moveType["running"] instead of MoveType.Running which will work just fine as an Enum?
I never used github desktop before... so I don't how it can be up to date if i commited all my chanes recently while this changing so much in stage 1-1 was recently...
yeah that's what it was before but it loooked rough
Your script with bool vars instead
it's the same
just simpler
If you change something, and you do not commit it, it is not "saved"
So you cannot go back to it
If you deleted things and don't see it as a change, then it was not saved
I don't use GH desktop but you can access your remote repo and visibly check if the changes are there, as well as run git status on the command line
I would recommend against bool variables
so uh, any solutions? #💻┃code-beginner message
Bool variables imply a possible state where two bools can be true at the same time, but it's logically not possible
git status?
Just from a quick peak, you have 302 things that were not committed. You should really experiment with git in a small test environment, literally a single text file.
You've basically setup github and made changes but never told github. Now that some changes were deleted, github still thinks nothing of it because it never knew.
so you'd prefer an enum?
That is not relevant
Instead of
bool isWalking;
bool isRunning;
bool isIdle;
An enum would be better because it is a direct switch between one of three states, leaving no ambiguity.
MoveState _moveState;
public enum MoveState
{
Walking,
Running,
Idle
}
indeed
I tried but I really don't understand enums
They're literally just numbers with names
... I lost so much in stage 1-1.....😭
I'm just slow cl
Imagine we made up a fun language between you and I where instead of "zero" we say "Walking", instead of "one" we say "Running" and instead of "two" we say "Idle".
that's all an enum is
Enums are a mapping of strings to numbers.
public Enum ExampleEnum
{
HandyString = 0,
OtherString = 1,
NotReallyString = 2 // The "= intLiteral" is optional
}
Maybe check for a temp file (do not run play mode again before doing this). Otherwise maybe look into if your computer has a recent restore point
It's almost exactly what you're trying to do with movetype["walking"]
temp file? I dont' know what that is
Did you google it?
Google will tell you more than I can, temp scene files are made when you enter play mode
Ohhhh I get you
Behind the scenes, Enums map strings written as if they were variables (e.g. not as "var_name" but as var_name) so you have a consistent way to associate a variable with a number
And if you have a single variable that is of type Enum, then that variable can only switch between one of the enum options
// Define the enum
public Enum Movestate
{
Walking,
Running,
Idle, // Trailing comma optional
}
// Semantically equivalent to:
public Enum Movestate
{
Walking = 0,
Running = 1,
Idle = 2, // Trailing comma optional
}
yeah, right now, but... not so much i can find, only lke moving file, fatal error
You googled "unity temp file"?
Try "unity temp file restore"
So i could set another variable to the enum value and switch case that value?
// Store MoveState enum in our class
public class SomeClass
{
private MoveState _moveState;
// Now, MoveState can either be Walking, Running, or Idle.
private void Awake()
{
// Initialize _moveState as being Idle
_moveState = MoveState.Idle
}
}
Yes, like in the code here ^
yeah I get you, thanks
The class variable in your movement controller can store a data of type Enum so it logically must be one of your defined enum values
No problem!
also is there a way to move the moveInput getter out of the walk
I wanna get it outside the onWalk just for preference
Yeah, when you reference the class variable, there is no get required
That whole if/else is redundant
The variable itself is a "get"
I did googled it but i don't find so much instead it's like how to recover lost uniry project, resoriing crashed scene,
Well, that is it
what?
I meant this line "''"moveInput = context.ReadValue<Vector2>();"""
if (Input.GetKeyDown(KeyCode.Up) || /* walking movement */ )
{
_moveState = MoveState.Walking
}
That is what they were talking about. It's the same thing
Ah, you're going to have to read something
If this is a player controller, I would just read their input keys
It only works if you have NOT hit play since deleting things
it's not compulsery I just don't like it in the onWalk
i did not hit play
but yet i don't know which one is about going back to how stage 1-1 was before
if (Input.GetKey(KeyCode.Up) || Input.GetKey(KeyCode.Left) || Input.GetKey(KeyCode.Right) || Input.GetKey(KeyCode.Down))
{
if (Input.GetKey(KeyCode.Shift)
{
_moveState = MoveState.Running
}
else
{
_moveState = MoveState.Walking
}
}
Your input system is different than the one I typically use but reading Input is typically cheap in Unity
all this is based on the old inputsystem no?
Should that not be GetKey not GetKeyDown? Unless you want to have to press the key each time to move?
Yes, it is.
This is correct
ugh! i just don't know how or where to find it......
so i have a game UI (canvas) and multiple scenes. What would be the best way for me to keep the same UI across all scenes? Don't destroy on load? or?
I'm not familiar with the new input system since the old one suits my needs and I've used it
Oh okay
The guide for recovering tells you how and where
Get that file, move it in..
That or additive scene loading
there's many files that i don't know which one is right
which one is the best for a game with ~10-20 scenes?
Depends.
Are you going to be putting a LOT of stuff in DDOL?
May be more organized to use multiple additive scenes.
I say use DDOL until it gets unwieldy and then switch to additive.
thanks lol
is it going in order?
quaternion.identity is not turning the rotation x y z to zero, it's setting it to different values. i want to change the rotation to 0,0,0
it's changing it to -90, -90, -90
more specifically -89.526, -90, -90
Identity is not 0,0,0 it is the current rotation.
if anyone answer............. because i don't have much time right now..... (and I cann't find anything that says what to do witha file)
If you are instantiating a prefab, then the prefab must be rotated already
you would have to be specific about the code you're using and how you're verifying what it's "changing it to"
yes the same values
Is it a child?
Are you mixing up rotation and localRotation on a Transform?
the thing in the inspector is localRotation
yes it is, and it's parent has a different rotation
likely
ok yes i was mixing up rotation and localrotation
it works now
thank you, that makes sense
Where does everyone learn C# from. Is there a good place to just take free lessons or watch videos and learn C#.
anyone please answer, i am having so much anxiety from this...
and I don't have much time left
Here's a good place:
https://dotnet.microsoft.com/en-us/learn/csharp
Dawg is this a hw assignment or something
ty
no! i accidentally deleted so much from a scene and went over to toehr scene, saved it and came and and i cannot undo things
didnt you setup Version Control last time ?
if there is no _Backupscenes folder, then sorry it is gone
no?
huh? bet I can look back in time and see it was suggested to you multiple times
....😢
this is the main reason vc even exist
and i don't have it
you do have version control setup. that is github
That's a great opportunity to pause you project and go learn the basics finally.
you simply didnt use it
Yes you did. You showed a screenshot of it too. Version control is git
You just didn't USE the version control like you should have.
We even told you that you need to commit multiple times in the past. You apparantly chose not to
Is there a order to take these lessons or waht
Start with the beginner pathways.
From top to bottom
Oh, nvm. I though it was unity learn.
I know, but i don't know which one like in stage 1-1 is that holds a lot of things that were deleted from the scene
What?
Just commit your changes...
How do I do that then?
Look it up on google.
It's just selecting the changes and clicking the button that says "commit" though.....
I think this self guided collection is really good and you get to code in an interactive terminal:
ty
To be clear, that's not gonna restore your lost files. It just gonna help prevent similar issues in the future.
At this point, you can probably just assume the scene is gone forever. Even if you look into restore points if your OS makes them, you'd lose everything else done on your pc between now and then.
Do yourself a favor and experiment with github. Maybe first commit everything you have via github desktop. And then after you push them, do yourself a favor and make changes on a simple text file and see what the actual difference is. Change the file, look at the file on github, commit and push the file, then look at the file again. Notice the change
You really dont wanna be learning how to not blow up your project, with your actual project that you spent months on.
Let me try tomorrow
ty
Because I will be sleeping.... Sad....
Hi, I've been struggling with this one for a while.
When an x rotation is < -90 or > 90, y rotation is inverted.
If I try to fix that with a ternary I sent here, it works for the most part, but then quaternions being quaternions somehow transform rotation from say x -180 to z 180 or something like that and the script fails.
This is the only code I have and as you can see, I am not setting the z position anywhere.
Am I missing something obvious here or what?
public class CameraScript : MonoBehaviour
{
[SerializeField] private float _rotSpeed;
private Vector2 _prevPointerPos = Vector2.zero;
private Vector3 _rot = Vector3.zero;
private void Update()
{
var pos = Misc.GetPointerPos();
var delta = (pos - _prevPointerPos) * _rotSpeed;
_rot.x -= delta.y;
_rot.y += transform.localRotation.eulerAngles.x is > 90 or < -90 ? -delta.x : delta.x;
transform.localRotation = Misc.VectorToQuaternion(_rot);
_prevPointerPos = pos;
}
}
what are you trying to achieve here?
btw this is not a quaternion problem this is an euler angles problem
I can see people asking 2 questions:
- What does Misc.GetPointerPos() do, just returns a pointer pos.
- What is Misc.VectorToQuaternion(), just does what the name says, takes a vector and transforms it into a quaternion using unity's built in Quaternion.Euler()
In simple english can you explain what you're trying to check with this ternary?
I wanna have a controller that's not clamped on it's x rotation(as most fps controllers are).
This causes the y horizontal axis to be inverted once you flip.
I am trying to negate that inversion.
if the x(vertical) axis is inverted
you mean you want to know if you're upside down?
yes
Simple:
Vector3 up = transform.up;
bool upsideDown = up.y < 0;```
How do u interact with the interactive terminal? Im clicking it and tryna type on it but nothing happens?
let me test that out, thanks, never went outside my original idea enough to think of transform.up 🤦♂️
Idk I just type into it and it works
More generally you do something like:
Vector3 angle = Vector3.Angle(transform.up, Vector3.up);
bool upsideDown = angle > 90;```
you can also use the dot product which is slightly more efficient but this is more understandable imo
My POV:
do you have an adblocker or osmething
no unless safari has one by default
Thanks, is there a particular reason I'd go with that approach?
I just tested the transform.up.y < 0 and it seems to be working flawlessly.
it's just more general
this happens to work because we're comparing with the world y axis
but you could generalize this to check if we're facing opposite any direction using the other approach
why does this matter though
oh maybe it doesn't work with safari
idk, any kond of plugin can mess with elements on a page
thanks again!
Yeah should look like htis
yup it just doesant work on safari. Ran on chrome and it works. And my chrome has adblocker
also mind i ask how u ogt dark mode?
is that just ur browser's color
it's probably based on your OS theme?
idk
Oh wait this is at the bottom of the page
I do not have that 💀
no idea
you can switch themes down here
I usually use Dark Reader browser extension though
oh yeah, sorry my dark mode screenshot was from this page https://dotnet.microsoft.com/en-us/learn/csharp
The theme thing shows on the other page
... I guess I will redo everything... And maybe remake the stage building look a bit different...
Found it ty
first things first is to practice, and learn using version control
or its bound to happen again
I might try tomorrow since I will be going to sleep
does anyone know how to make it so whenever you add a velocity to a rigidbody and it collides with a wall theres less velocity applied ? i cant really explain it well i hope this stupid drawing helps this make sense 😭
Neither the picture nor the explanation make sense to me 😬
what do the red and blue arrows mean
dammit 💔
the drawing looks like you're trying to move pass/into the object (wall)?
the red arrows are the velocity that would normally be applied to the body, the blue arrows are the actual velocity that would be applied
im trying to make it so my rigidbody doesnt slide up things ,,
what do you mean by there is less velocity? when you hit a solid object, do you want to keep going but slower because of the mass of the obstruction?
I'm not sure how this would prevent sliding
whenever you apply a force to a rigidbody itll go up walls so im assuming if you dont apply a force in that direction it wont slide
up
yea thats basically it
I mean if you apply a force to a body it will accelerate in the direction of the force.
Sliding happens because part of the object's velocity is orthogonal to the wall so that part of the velocity continues while the velocity going into the wall is stopped by the wall.
If you want to slide less, give the wall a material with a lot of friction, or kill the velocity that is orthogonal to the wall in OnCollisionStay or something
Is there a way to tell a Nav Mesh Agent that I want it to REMAIN at stopping distance instead of letting the target move within it's range or do I have to code that manually?
Definitely need to code manually
mmm giving the wall a lot of friction i could try that
Ok, how could I code "get the closest position avaliable in the navmesh that is at X distance of the target"?
Cause I could calculate a position from the target and the agent's posstion but I have to be sure it is an avalible position on the NavMesh
maybe something to start with is:
Vector3 targetToMe = (me.position - target.position).normalized;
Vector3 pointAtAppropriateDistance = target.position + targetToMe * X;```
Check the Navmesh API docs. There's a method to sample a closest position on the navmesh
Kinda what I was thinking, honestly
The other day you were struggling with basics iirc. Why are you doing networking??
I think I used that before, did not get great results though
It does what it's supposed to do. If you have an issue with it, provide more details on it.
Cause it is very likely to get a point outside the NavMesh and just get really sticked to the walls
There's specifically API for getting a point on the navmesh. There's no way it would return a point outside of the navmesh.
That would be ruining the whole point of that API.
No like I mean... you generate a point outside the NavMesh, and then that method gets the closest point, which is basically at the border of the NavMesh; the next position calculated (since it is already close to the wall) is very likely to be outside the NavMesh and continue hugging the walls
Like that
Well, that totally sounds correct to me. If you ask for the closest point on the navmesh to a point outside of the navmesh, it would return you the outermost point(still on the navmesh), so I'm not sure what the issue is.
Like basically the whole area that is outside the NavMesh is positions where it might get stucked on walls
Then don't pass in a position that is outside the navmesh
I mean, is technically correct, yeah
How can I know that? What if there is no position at the range and in the NavMesh?
That's the responsibility of your game logic.
You can define some bounds that you would only sample points in for example.
You can know if a point is on the navmesh with the navmesh API as well.
As for how you deal with it, is up to your game logic.
I guess the right way of doing it would be: Get vector from target to agent, then multiply it by the range, then get closest point in the NavMesh to that point; if that point is within range of the target (meaning it had to move closer due to boundaries of the mesh), get a new one (probably the same vector with opposite direction should work?)
Dunno
Seems really messy to work smoothly
Well, what do you want to happen? What is this logic for?
Is supposed to be for the typical "treasure enemy" that flees at the sight of the player and after a while it dissapears
So basically I just want this to be as far away of the player as possible
i did it thank you liberals
In many games such enemies would hug the walls if this is the furthest point from the player. If you want a more sophisticated behaviour, you'd need a better algorithm for their pathfinding.
I mean I would love that if it detects that the point it generated is not far enough, it just tries to go the other way around, so I am gonna try that
You can check the distance between the point you pass in to sample and the returned closed point on the mesh. If it's too far, chose a different direction for example.
Hi, I'm trying to make a barebones rhythm game and I ran into some input issues - when there's a sequence requiring to press 2 keys at once on the keyboard, sometimes the keys just won't register when I press both keys simultaneously. I tried to do some research and apparently it's an old bug that hasn't been fixed? Or maybe it's because my code is bad so here's the code for the input.
https://github.com/Unity-Technologies/InputSystem/issues/663
your code is unrelated to the github issue you posted, you are using the old input manager, not the input system
the code you've shown can also only ever detect a single key press at a time
I'll try to look into the input system, thanks
I could use some help, I'm using UnityEngine.UI, created a Slider variable, and all I want to do is change my color to match the Slider Variable. For some reason my Colors red value keeps going to 191, unless the slider is at 0, then the Colors red value goes to 0. There's no in between.
I'm just messing around with UI and trying to get comfortable with it
but this is a strange problem I'm encountering, note there's no other code
Color takes values between 0 and 1. So your slider needs that too. If you want 0 to 255 use Color32
ohh, okay cool ty Steve
So just to feed my curiosity, if I wanted to use a value between 0 and 1, how would I do that? I realized floats are not accepted, however, bytes are. So this doesn't give any errors, but it also does not work.
floats are accepted. Color is 4 float values
that's not a Color
ohhh
that is Color32
4 float values
Color - 4 float values. Color32 - 4 byte values
no, you are still using Color32
ok, there is automatic conversion between Color32 and Color
I forgot to change Color32 to Color
it was an oversight cuz I was so focused on new Color, but this is pretty much what you meant correct?
yes. you can also do
Color color = new Color32(126,255,255,255);
Is there any actual difference between Color and Color32 then?
Id assume color would use more memory?
But its not so much more that it matters right
yes, 4 times the memory. Also Color32 is what eventually ends up on your monitor
yeah
oh interesting, so that's what you meant.
manupilating floar values is much slower than manipulating byte values
but this is is extremely negligable for most usecases right?
Just preference for how you want to write them?
I remember using both at some point
well, not if you are scanning the pixels of a large texture for example. It can make a huge difference
ohhh
Good point
I do do that in my current project but only for small 20x20 pixel images
But i need to check wether i use color or color32
really the only thing that should use Color is shaders because that is what the GPU works with
CPU based stuff should always use Color32
alright I will go through my stuff and replace it where I can. Thanks!
I guess because GPUs are already optimized to work with floats/ floating point math?
exactly
I tried to use the input system + separating simultaneous inputs for debugging, now I'm puzzled on why only 1 of the 2 supposed methods are run only when there's simultaneous inputs in the same frame
The same reason as before. Because you use an else if chain so only one of those blocks can ever run
when you say Shader do you mean Shader Scripts / Shader Graphs?
yes
I figured, i'm just slow
won't it double count if I don't use else if?
It's accumulative - will become second nature over time.
you're probably not pressing the keys in the exact same frame, there is very likely at least 1 frame separation between the key presses. you'll need some input buffering or to check if the key is currently down rather than was pressed that frame
which, of course was also part of the issue with your previous code so i have no idea why you decided to swap to the input system for this issue
you dont want if else because then you can only press one each frame.
But its also highly unlikely you will hit both keys in the same frame so you need some buffering/ use the Input system/ modifiers
yes, the chances of 2 keys being pressed on EXACTLY the same frame are virtually zero
I don't think the issue was "I didn't press 2 keys"? It's that the bracket for F+J only executed one of the 2 methods inside (despite the video showing that I pressed 2 keys multiple times to cancel out the falling objects)
no, the issue is that you didn't press the two keys in the exact same frame which is the only time that first if statement will ever be true
you need literally frame perfect timing for that which is almost physically impossible, especially if you are running more than 60 fps which is a strong possibility
alright so I'm experimenting, I found this, colors are expected color except, the variable color32. Why is this?
also, dw, I do not use numbers when naming variables, this is just me testing.
in fact I believe that for mobile that is not even possible at all because of the way input is registered
if I didn't press F+J on the same frame it wouldn't have wrote "F + J pressed" on the console though?
shortly after posting I realized I put new Color() and not new Color32()
wrong
yea
if that log printed then both of the Add method calls were executed.
if something regarding those method calls isn't working, then you need to actually investigate that code, not your input code
Color32 is just new Color
not new Color32
so its basically 1, 1, 1, 1
which is white
so there's something preventing 2 Add methods from executing at the same time fsr
Is there a difference between FindGameObjectWithTag and FindWithTag?
FindWithTag says it looks for an active element, while FindGameObjectWithTag doesn't specify any info
you are going to have to do something about that or your life in coding is going to be hell
The docs say both return only active ones
FindWithTag returns only one?
yea, very true, I need to increase my attention span xD
FindWithTag returns only one GameObject and FindGameObjectsWithTag returns an array. Both return only active ones
they do the same thing. FindWithTag just internally calls FindGameObjectWithTag
https://github.com/Unity-Technologies/UnityCsReference/blob/bf780206f6cd0ee3ee4c40e30bb1dfbf2969288a/Runtime/Export/Scripting/GameObject.bindings.cs#L203
there's no s, that one is obvious, I'm asking about the bottom two
my apologies, tap is a list so the add() was adding the value to the list
wasn't a method
any way to look for an inactive GameObject?
Add absolutely is a method. it's just not the source of the issue here. however you are processing the data in the list is the issue
FindObjectOfType? not sure if that helps but it has an "includeInactive" param
ah my bad terminology
no it has no type 😦
preferably do not use any of the Find methods at all. use a better way to get a reference
but I'll just reference it instead
I think that if you call 'GetRootGameObjects' on a scene it includes inactive game objects
Transform equipmentSlot = CharacterLogic.Inventory.Equipment.transform.Find(equipmentType);
is this too much?
Too much for what?
one of those cases where if you have to ask, you know the answer.
In general, I would advise against using Find() unless there is no suitable alternative, and even then, still consider ways to not use Find()
the equipment part itself should probably handle that whole finding an object thing, rather than needing to access the transform and .Find on it
Consider null checking this
I'm actually just asking about this part: CharacterLogic.Inventory.Equipment still re-building the rest
For my equipment system, I have a dictionary that maps equipment types to equipment slots (Helmet to HeadSlot, for example).
If I'm looking for the first equipment item in the inventory, then I have a function FindFirstItemInContainerOfType(ItemType itemType) { ... }
guess I could reference each equipment slot too
Accessing properties is very fast and is effectively zero-cost as far as you should be concerned
I could put Equipment in CharacterLogic too, but I need it more in Inventory
Searching for items in large collections is very unperformant
I think you are worrying about the wrong things. If you think it's too much to write, consider using a property.
public Equipment => CharacterLogic.Inventory.Equipment;
it's just like 15 item slots, but yeah I'll add references for them instead
Then you can just use Equipment/this.Equipment
Definitely use different components for this. You seem to be headed toward making a GodObject potentially, unless your inventry is supposed to be super simple
nah, just wondering if it's not a bad practice or anything
PlayerInventory // PlayerController // etc. is good practice if you plan on scaling more
In what way would this be bad practice? The fact you access a static property?
As with a lot of things it really depends
it just looks weird, that's why I'm asking
You're probably better off by making a singleton if that helps it
Accessing static data can be hard to scale and test
I really don't want any of this stuff to be singletons in case I ever want to expand the game
Assuming this is static. The way this code was capitalized makes me think it's all static
none of it is static though?
i was just assuming they are properties
Player
|
--- PlayerController
--- PlayerMovement
--- PlayerInventory
--- PlayerStatusEffects
...
Then idk 🤷♂️
Can't really give advice on a single line of code like this
Accessing properties is perfectly fine and not bad practice, in general. There are exceptions to every rule, but this is generally the case.
It's only weird if you start tunneling through public variables in convoluted ways like PlayerController.PlayerInventory.PlayerStateManager.WhateverElse
If you want proper help then you should actually share the context around the code
Otherwise I'm just throwing out possible suggestions that likely won't apply
{
[SerializeField] public Inventory Inventory;```
```public class Inventory : MonoBehaviour
{
[SerializeField] public GameObject Equipment;```
Trying real hard not to comment on code style here
i will, these should be lowercase
Not only that
feel free to comment
public variables are usually upper-case though?
private class variables are usually _likeThis
Please don't use public fields
And if you do the attribute is completely useless
Please make it private
What's wrong with public fields?
I think that is explained very well online
It won't have a realistic impact on anything
meh that naming convention needs to be gone already imo. but besides the point, the capitalization makes it look like a property (which i assumed) or static, which FusedQyou assumed
What if another component wants to access it? You can use properties instead of fields but the result is ultimately the same
_ is annoying to reach on my keyboard so I don't like using it
why not? I would just make the field public with a method then?
public/private matters more when you're trying to shield proprietary information from less-authorized users in enterprise networks. Not super applicable to Unity unless you're on a massive prod team and trying to hyper-modularize, no?
A public field breaks encapsulation
I don't really feel like explaining every single reason when this can just be found online
If another component wants to access data, you can have a property with a public getter
It doesn't need to be perfectly encapsulated to serve its purpose
And then the getter will do the exact same thing as the field
I know the diffence between public & private
I've been using private for 6 months and it's just been annoying me and slowing me down, I haven't found a single good reason to use it in my project
Thus with no difference except added complexity
well yea it doesnt matter in terms of gameplay, but god seeing public fields everywhere is such a nightmare
theres literally 0 added complexity
which ends up doing exactly the same as making it public, unless you put logic in that property, which I won't
The complexity of having to care about public/private is complexity itself to manage
Just do what works and meets requirements. Using public fields won't break your game
Also for value types there is a great deal of added complexity
definitely not. the complexity of writing 2 lines vs having a future where anyone at any point can do
someInstance.MyPublicValue = null
and then having to debug why your code isnt working anymore is way more complex
By all means keep using public fields, but in a few weeks it becomes very hard to udnerstand what uses it 😉
And suddenly it's a lot more complex than when it woul dhave been if you just sticked to the property
I think arguing is pointless, you just seem to lack the experience to understand when to use something
I'm a software engineer at Microsoft
I think I know how it works
Because there's a ton of bickering at the lower levels about what is right and what ought to be
And it's pointless because all that matters is meeting requirements
Oof, then I'm very surprised you don't see the point of encapsulation
I know what the point of encapsulation is
I'm telling you that you're overestimating the importance. You're not designing Facebook, you're designing an indie game
You don't need dependency injection to make your sprite go up or down
I mean if your only point is gonna be that it doesnt affect gameplay, then you could argue literally anything if the end gameplay is the exact same.
there is absolutely no way you are comparing a property which exposes a private field to DI
Sorry, I stopped caring about convincing you when you mentioned properties are "too hard" to use over fields
You don't need to protected internal your variables to hide them from other components that you are the sole controller of. C# was made for enterprise to hide proprietary information and improve upon Java. Just meet business requirements
But please stop trying to give bad examples to beginners here
I never said they were too hard to use, I said it's pointless to bicker about public fields = bad and public properties = good
You're boasting on the ivory tower. It just doesn't matter at all
I never thought I would find myself agreeing with a MS software engineer, but I'm with you on this one. There is way too much pointless style policing going on in this server
I agree it's generally good practice to keep fields private and use getters and setters but it's just such a headache to police it all. Just get the job done. Meet requirements and refactor when needed
This is literally 2 lines of code. The amount of headache is solves from someone just modifying it later when they shouldnt and causing issues is justified
It's telling a beginner something that doesn't really matter
- Make it work
- Make it right
- Make it fast.
In that order.
You're trying to make it right before it's working
🤷♂️ if you consider a property too much to manage then theres really nothing i can say about it. And im usually pretty against the whole enterprise solutions that people show in their projects
I agree that what you're saying is best practice, but I just don't think it matters enough to tell a beginner how it ought to be as if their choice was bad. It just doesn't really matter for their use case.
Never said it was too much to manage. I'm saying it's not worth trying to police a beginner into using the "correct" way to code. It just doesn't matter.
Use a property when you want extra control over getting and setting operations, like when you want to invoke an event when a property is set so you can decouple components. I really like this use of properties personally. But if I just store data, why doesn't a field work just fine? I just don't think it's important.
{
[SerializeField] public Inventory Inventory;```
Alright, so the reason I'm doing this is because I use CharacterLogic.Inventory in nearly every other script I have that only has the reference to CharacterLogic, so I don't also have to reference Inventory there
How does making it a public property over a public field change anything?
I understand the difference between public & private, I've just NEVER had a usecase where it actually mattered to me, so I don't understand why you would use private, I understand the theory behind it, but it just doesn't apply to anything I'm doing
Nope. Giving a beginner the proper experience is more important than getting the job done. A lot of people here just work on a project for experience and they don't finish their project.
You want me to do this right?
{
[SerializeField] private Inventory inventory;
public Inventory Inventory { get => inventory; set => inventory = value; }```
Which is exactly the same result?
Thus, the adage:
- Make it work
- Make it right
- Make it fast
There's no point in policing style when their requirement does not work.
Yes, this is the same.
or am I still missing something?
Is there a reason why you would want other classes modifying the inventory?
Do you need anything to assign Inventory outside from CharacterLogic ?
if you wanted to be even more concise you could do [field: SerializeField] public Inventory Inventory { get; set; } (although ideally you'd have a private set, as why would another object need to be able to assign to that property)
I don't think so, just reading I think
Access modifier is all about constraints
Constraining yourself from doing something wrong, specifically
private Inventory inventory does fine without needing extra logic for getting and setting operations
so the whole idea is that I should be doing
public Inventory Inventory { get => inventory; }
or just public Inventory Inventory => inventory
so I can't modify my inventory outside of it?
yes nothing can just do CharacterLogic.Inventory = null
because now its just a getter
Yes and if you want to modify something then you probably want it through proper method
Or you can do
public Inventory Inventory { get; private set; } to restrict setting to in-class and getting to any class
Then remove the setter
No point in exposing it yet
Once you actually want to replace it you can read it. Maybe even make a method and apply validation or different logic to prevent issues
Why not focus on getting the inventory to work first before focusing on optimizing the accessibility
The question was about code style specifically on the small snippet that was given
If that wasnt the case I would not have given the advice
the thing is, I never program things where they're not supposed to be, so I never thought about this lol
and I'm a one dev team so don't have to worry about others
but now I at least understand why everyone says it's so important to set fields to private lol
mate I'm not a beginner, my inventory is working
So what problem are you trying to solve?
I'm asking for information and trying to learn to optimize my code and prevent bad practices
If you're looking to optimize your code, studying algorithmic time complexity and big-O time of data structures and algorithms is a great starting point. Hash set > binary search through sorted array > search through unsorted array > combination check. *But typically, it's best to avoid optimizing before you have a performance bottleneck.
What constitutes bad practice is nebulous and generally comes down to well-named variables and cleanly-defined interfaces between components. It's largely up to preference and what works for you.
Well, as mentioned it makes 0 difference. But say you work on the code in a month and look at that field, would you remember what accesses this field?
A public field just gives too much accessibility, so hence why you would never see this and instead use properties
Even if they are completely empty they would allow for future-proofing any possible changes
You know what the height of bad practice is? It's blindly doing things in a certain way because that was the way you were taught.
There are only 2 rules in programming
- Code must be syntactically correct
- Logic must be accurate and exact
EVERYTHING else is optional
Dev teams do things the way that works for them. It varies a ton between individuals and teams. The fundamentals are the same: working code that meets requirements and that can be maintained. What that constitutes is contentious.
🤷♂️ they were literally asking on the style because it was clear they felt something off by having to do A.B.C.D.E.F
telling them do what works is nice and all but its a bit silly to force it through the entire conversation. Properties were also brought up as a way to skip doing A.B.C because A could have a property to access C
Yes, that makes sense by itself. It's when it was mentioned that using a public field would make your game unmaintainable after 2 weeks that I expressed disagreement
Undertale's dialogue has control flow of a giant, massive, immense if-then block. Hundreds of lines. Ugly code, beautiful game.
OMG
Oh yeah, it's a beauty 😎
never heard of databases, huh
assert dominance by writing unmaintainable code
It was apparently maintainable by him, and since he developed it by himself, that's all that really mattered
I would not call Undertale a failure despite the horrendous switchcase
Ok, but what was he thinking when he wrote that?
As long as he understood it I don’t see a problem
so it would be better to also reference C on A instead of doing A.B.C?
because it screams 'My data structure is wrong'
Better in the sense that your line isnt as long, like this
#💻┃code-beginner message
that's a great way to set yourself up for failure, that's the problem
in this case it worked out because he understood it, but it could have gone wrong in a lot of different ways and have broken the game or wasted months of time
I don't really mind the line being long, I don't really have an issue with the structure either
So I guess it's fine?
He could have refactored whenever he wanted to, but he never felt a need to, and clearly he delivered results. You're not measured by the cleanliness of your code but by your ability to deliver results.
It's still an anti-pattern that should be avoided, anyways.
Honestly, I could never bring myself to write something like that
if its just a one off line then yea doesnt matter. The suggestion was just a way of saving time if this was something you are writing a lot
he got lucky, don't repeat at home 🙂
like an example i have, a lot of my abilities check what faction a character is before deciding to damage them (so you cant hurt allies). I have a property like this on my character
public FactionSO FactionInfo { get; }
public Faction CharacterFaction => FactionInfo.faction;
It's not luck at all. It's just an untidy chunk of code that fits the purpose.
this actually helps a lot
Clamoring over what code is most clean or most optimal is a programmer's way of procrastinating
so instead of CharacterLogic.Inventory.Equipment
I would have Equipment => CharacterLogic.Inventory.Equipment
never used that before 🙂 what's it called?
That's usually what I do when I need a single instance from somewhere and I don't have some sort of DI system
if the current script is using it a lot, then yea id say its justified. Its still just a property
Works fine assuming the instance always exists
its just some syntactic sugar, left side is what i wrote. right side is what it becomes anyways
And go onto the next step please, what it actually becomes when compiled
FYI a property doesn't hold a value, a field does. A property is just a fancy method.
So something like public MyProperty { get; set; } just gets compiled into a method with a hidden field called a backing field.
Hence why Bawsi for example uses a separate field
honestly im not sure what you mean, like the IL?
yes, exactly
You can set a default value to a property
because you are turning a simple one cycle instruction into a mess all for what?
Without using a field. It can technically store data
Then you just set the default value of the backing field
Yes, so it sets the backing field
the property itself stores nothing. it's just a fancy getter/setter method. that still have an implicit backing field generated by the compiler
Have any of you guys worked on any game projects?
https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQPkGYACNQgYUJwG8dDbCwA7YQgQwG4a7PaD6nCAgoQC8APlYdc2AL44gA=
this is the link im using, but i dont really know much about IL and that jazz
yeah I will rework my code to use private fields everywhere, seems like a good idea to stop myself from doing "wrong" things
honestly i wouldnt go back and rewrite everything even. its just sometihng to keep in mind
current WIP
And that is exactly my point. I compile every single line of code I write into IL/machine code in my head when I am writing it
Nice!
@topaz mortar perhaps interesting for you. This is what a property actually becomes during the compilation process: https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYYDKALgE4CWAdgOboCyAngAqUD2ADgKaXkW+dPV7kA3OgDOYyQF90AXnQAiABK8ANps4AadAHVOlTcACEK8cjlA
Notice it generates a backing field that is secretly used.
You can select "IL" as the result and if you look in the code you can see it lowers into separate methods called get_MyProperty and set_MyProperty
Hence the "fancy methods" I mentioned
meh 😛
Do you actually do this???
Oh, yes
I am very, very old school, ASM is the only language that counts
I cannot even fathom. That's incredible
I've been doing this for a very long time
How close do you get when mentally converting from C# to IL?
100%
Hahaha jesus there's no way
IL is pretty simple
if you think of the IL between
public int A;
and
private int a;
public int A ( get { return a; } set { a= value; })
you will only use properties when you actually have to
How did you first begin to understand the mapping between C# and IL?
well, I've been using C# since before it was released, I was one of the beta testers
holy hell you're actually a wizard
maybe, just very old and experienced
and, btw, generally MS devs are not my favourite people
Why not?
because they write crap code
Which products specifically? The teams vary widely
Windows basically
it's the reason I now need a i7 13 series to do the same I used to do on a i386
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
Windows being too bulky, in general?
yes, and very badly designed. I mean, explicitly whoever came up with the implementation of the registry?
Hm, I don't know. It's not a feature I use too often explicitly except when I'm debugging something and I'm usually deep into the rabbit hole.
even if i want to click o nthe commit change, it wouldn't let me
Type a name & description
let me give you an example. A bare bones XP installation had about 256k registry entries. A Win 11 installation has 2.5m using the same shitty implementation
Summary (required)
Is there a strong use case for upgrading it besides it looking/feeling outdated?
Or do you mean it's bloated, or both?
both, it is inefficient, unwieldy and very prone to break
and NOBODY, not even MS ever cleans it up
like that?
That works. Not a super descriptive name, but it works.
That's fair
thanks, it's that many things from stage 1-1 were lost because i accidentally deleted many, went away from it and saved it and cannot undo things there
should i commit ALL of them?
My main bug bear is that MS seem to have forgotten that I own my computer not them, so I should have the choice of what it runs and when
You should be able to commit them but beware if you have oversized .png or other filetypes that might be hard to manage. I'm not sure how git's large file storage integrates into the website if at all, but this should work fine
