#💻┃code-beginner
1 messages · Page 824 of 1
It should still underline the error then, and tell you you have one
How to i select the collum
(you may also see something like Flow.cs:12 in other contexts, only showing the line number)
you generally would not
Just go to line 12
private struct RecursionNode : IEquatable RecursionNode
it's only necessary if you have 400 long lines
line 12
yeah, missing comma as the error says
where is it missing?
did you perhaps accidentally modify this file?
Is your ide telling you there is an error there?
it seems like this is from an asset so it shouldn't have this issue on its own
Its from a decompile
ah.
of course
But critically, this isn't in Packages so it can be edited
Seek help with this elsewhere
yes, that's what i'm saying
Not here
Welp then you're on your own #📖┃code-of-conduct
(btw, the error says the opposite of this.)
Yep, just expanding on that, but it seems it doesn't matter anyway since they didn't even make the project in the first place
Yeah youre right lol
It has an extra symbol somewhere
No, it's missing a symbol
But its also a decompile so lord knows what could be fucked up
Did i not say that then initially
What
Ah fuck
I said the same thing twice
Because that line isn't the syntax for implementing multiple interfaces
I am very... tired 
a powerful website for storing and sharing text and code snippets. completely free and open source.
what is my mistake im just so tired..
what's the issue
Not mentioning the problem, for one
altough camera is close to some other objects that have the lod script, only 3 that are the closest to origin are chosen to be on?? here is my set up for manager and for individual poles
all i want is to just turn lights on when you are 15 units away, it just does it for these 3 that are closest to origin?
even if I manually put a camera as variable instead of getting the Camera.main i get the same result, so its not that kind of problem
doesn't unity's LODs do this for you already
enable behaviours?
it'll swap meshes with enable behaviours if attached
So you're saying that the problem is: only three lights near the origin of the world are turned on when approaching the lights?
they always are, for some reason
i recorded a video with debug logs, ill show right now
wait i compressed it
also it says 2 because i added a second distance to test
but yes, same result
also yes, it is from origin, for some reason
I've got to run but show your lod component array, log the positions etc so that others can help you better (they may not be where you think they are)
here is the radius and position from OnDrawGizmosSelected
just changed the last line to Gizmos.DrawWireSphere(pos, manager.Distances[i]);
the other things like list and everything can be seen above here (2nd and 3rd image)
NOOO
No way...
i forgot to write this line of code

Anyone here experienced with inventory systems? i got a primitive one setup that can hold quantities, icons, descriptions and image displays but idk how the hell to drag and drop items
Sounds like you're mixing up inventory logic with its ui logic. Separating the two should make things easier to reason about.
Right i do have separate scripts for inventory as well as my ui logic with loose coupling. Im at the point where i cant find a tutorial for exactly what i need so maybe i gotta slow down and find a original solution for my system
Yeah. You wouldn't find a tutorial for every specific case.
For drag and dropping specifically, you should learn how drag and dropping ui elements work. Nothing to do with inventories on its own.
I wouldn't sweat too hard on making one. Make it as primitive as possible and forgo any loose coupling
kk, once i learn the drag and drop elements do you figure ill be able to implement it with what i got?
Unity complicates stuff as you can store backend code on those UI components
If you can reason about the logic, why not.
Word, i already tried making systems while ignoring coupling and i made big sphagetti shit was so ass
https://www.youtube.com/watch?v=bTPEMt1RG3s
Go with this series if you want to follow something. Gives you a rundown of all of unity's features you'll probably be using and you may learn a few things.
Tutorial series on how to make an inventory system in Unity, using C# and the Unity UI. In part 1 we build the base UI, implement Items using ScriptableObject and make the Inventory class. We'll also use the Character Stats asset (developed in another tutorial series).
► Next Video (Part 2): https://youtu.be/4JewzU_phTM
► Items & Inventory ...
Hell yeah
can we discuss this in dm. Thanks
Hey all! I'm trying to implement a simple exploration system in my game. The entire map should be hidden at the start besides where the player is, and anywhere where the player goes gets revealed permanently.
How would I go about doing this? I've currently got a large, flat cylinder attached to the player that represents their vision. How do I go about storing where they've explored, and only revealing areas after the fact?
(Posted a slightly more indepth explanation in code-general with images, since the scope of it might be outside this channel) https://discord.com/channels/489222168727519232/1483647256023535789
I should have asked this yesterday but can someone tell me how to find unity assets or frankly prebuilt things in general that would properly fit the architecture of a planned game? i do not want to reinvent the wheel so it'd be awesome i know where and what to get the things i need.
i mean like pathfinding, grid systems, maybe some kind of ease of action queing system etc. And the 2nd part of the question is still on finding out what i need since im a beginner
https://assetstore.unity.com/publishers/1
Unity's a bunch of templates you can rip apart
Welcome to Unity’s own collection of assets. You’ll find a variety of complete projects and tutorials, models, environments, props and editor extensions. Keep up to date on the latest tutorials and projects from Unity on our Learn pages.
I didnt think about taking a whole template. So can i take like the tower defense template, and strip it down to smaller tiles, different time systems etc without breaking things?
Eh, I ideally you just learn from it. You can probably grab scripts and paste them over into a new project, but usually there's a bunch of dependencies that it makes it pretty hard.
I thought programmers are suppose to be decoupling code blocks. Damnit. So im back to square one of need individual unity asset systems so i dont reinvent the wheel
There's usually multiple ways to go about something. Like a tower defense game you can just build a 2D grid and do it by index placement, or have a freeform environment to build upon and use colliders for placement.
there's no magic solution where you get to completely avoid programming here
even putting two completely separate solutions together is gonna be work
i understand but skipping parts that could take ages to do, seems... important
potentially yeah
Anyone know how much it would cost to hire a programmer babysitter? I always hear compsci people complain about being terminally unemployed but if that were true they would be pretty cheap would they not?
we dont really do that here
I am not looking to hire someone here im asking how they would cost
and most places adjecent to here would not be recomending you pay people below minimum standard rates in their country so it depends
depends on where they live
Tbh even so that compsci whining about being unemployed sounds fake. There is rarely times i have hired people outside of house improvement. That i would want to hire a specialiy job like that even though im not a company should mean they are in high demand
Stupid ass statement
usually around 40 I'd say is the average rate, but always people offering for less if you look around
interesting thanks, id hope they be cheaper because im not expecting them to code just to babysit. but ill see about it
Hello, I am trying to create a system where once the player enters within a certain distance of an enemy the enemy attacks the player with lightning (Marked by a red circle on the ground). Everything is working fine except I can't seem to figure out how to apply damage to the player if they are in the circle at a certain time. Could someone explain to me how I would do that?
That’s honestly more work
What are you using so far to detect if the player is inside of the circle
lol probably but ur not just developing the game but also learning so ur getting a teacher as well
I am currently using OnTriggerStay but that applys every frame the player is inside.
Anyone you hire will almost certainly be teaching you, not the other way around
Isnt that what i said? You hire a babysitter, you write the code, they review and give u development direction. So ur developing a game AND getting a teacher that is helping u learn
Ah misunderstood what you said, apologies
Hi, I'm here because of the graffiti video. I'd like some help figuring out how to do it. Look, I already have a yellow line, which is the raycast. But what do I do to paint the wall? I already have that yellow line coming from the player. But I still need to paint the wall.
OnTriggerStay can work fine, but ideally you do something like OnTriggerEnter -> run a timer and accumulate deltas while true -> apply damage when timer runs its course. You can use OnTriggerExit to know that the player has moved from the source and can clear the timer then.
I am sorry but what is a delta?
delta time
how does delta time work again? i think i remember it having a problem with a late 0.3 tick system
or perhaps i needed to just use frame interpolation smoothing for sprites or something
can also just compare Time too since this isn't something that requires that much precision anyway
Hi, I'm here because of the graffiti video. I'd like some help figuring out how to do it. Look, I already have a yellow line, which is the raycast. But what do I do to paint the wall? I already have that yellow line coming from the player. But I still need to paint the wall.
Help.
surely whatever resource you used to learn about the topic covered that?
It's just the amount of time passed per frame processed. It helps prevent coupling stuff directly to frame rates as you'd get different results depending on different rates otherwise.
by frame u mean the registry of the whole system right? like ingame data updating
From Software loves to always have some mechanic each game where they do just that such as weapon durability becoming a larger problem if your monitor refresh rate was higher than average.
i feel like i am going to start crying when i get later into development, that sounds absurdly annoying
just ridiculously stupid bugs like that of data tied to monitor hz
Elden Ring had some hitbox issues earlier on where character invulnerability was tied to that too so you would instant die to some enemies if your refresh was higher.
oh if its even in AAA games that makes me feel slightly better. What a weird bug
It's mostly because these games are usually locked at a frame rate, but PC releases they allow for higher rates. Elden Ring though is actually locked at 60 unless you do modify the game.
well clearly they cant just fix the framerate issue without breaking the code in a major way. the spaghetti code problem seems to be quite depressing for many people. ive heard of compsci students even dropping out of it as a major just for that reason
like it would be too much work? sounds simple to me (tho i barely know shit)
Can anyone help with me with my code, im trying to have Slope rotation what is smooth with my player. And i have it in but its pretty bad, And its just stubby.
Whats the difference between doing
private int Num;
and doing
int Num;
Assuming you're declaring a field on a class or a struct, nothing.
private is the default access modifier for fields
If you're trying to declare a local variable, then the private one would be a compile error.
If it's a field then better do private to make the code consistent but you don't have to there's no difference except for looks. If it's a local variable in a method then just do int Num
Alright thanks to both of you
You'd need to show the code at least.
The car Rigidbody has interpolate . It is vibrating like this
but how / when is the camera's position being updated
i managed to fix the problem now
Just curious, what was it?
i could not identify the problem my friend helped me. But if be concise there was difference between the frame rate and update timing
so im trying to transfer those int into my second script and i want to be able to modify is from both is side
i just cant seem to figure it out ive been trying for 2-3 days
make it public
ah
lol sorry realise i was highlighting it
is the class also public?
do you have a reference of this script to the other script?
if you want to access any members of a script in another script you need a reference to it
how do i do that
so in the other script you create a new variable of that class, assign it, then you can call that variable and access all its public members
OO
@silent sorrel try checking out https://unity.huh.how/references
Choose the best way to reference other variables.
thank u
you'll probably want serialized references
will read all that
Hey, I'm making a simple level where you throw a disk around, parts of the maps are overlapping and even if colliders are at the same height the disk keep bumping on the jointure, what would be the best way to fix that?
If you hold V you can vertex snap your meshes so they align perfectly
Oh wow i didn't know that, thanks!
is there a way to fix this. the script i wrote is grayed out. the variable is missing
I don't see any greyed out scripts. What variable is missing?
- Check your console window for compile errors
- Make sure the variable is public or has
[SerializeField]and is a type that can be serialized
Sure, what variable though? And did you check for errors in the console?
Why do you think it should show "Move"? What does the code look like?
The script itself isn't greyed out. It's only the Script name that is in grey - because you can't change that in the inspector.
Again. make sure:
- your code is saved
- it has no compile errors (check the Unity console window)
- It has refreshed (ctrl+R iin Unity if you have auto refresh disabled)
Again
have you checked the console window for errors?
maybe ill need to recheck the code
you can only get properties in the inspector if the field is public or serialized
Show us your console window and show us your code
theres no issues from visual studio
I'm not asking about Visual Studio
I'm asking about Unity's console window
Does your script actually have any of those to change
Hey there you go
thats what i was gonna check now
Looks like you have errors you need to fix
also if your VS was saying there is no issue, you need to configure Visual Studio
seems that way
!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
alright ill try see if i can fix it from there. thanks yall
yall were right about it being the errors. its odd it didnt show in visual studio but its fixed now. thanks again
If you configure Visual Studio as per the instructions linked above it will start showing you errors
alright will check that
Hold on
Hi i dont know where the help chanle is
i dont know if i missed soemthing but in unity 3d the 2d png objects arent reacting with lights dont know why
what do you mean by "2d png objects"
what exactly?
spriterenderers?
found its
the object in the back is a 3d plane that reacts to light but not the png
heres the settings i think might helps
sprite render isn't affected by 3d lights
how do i fixs it then
custom sprite shader
is it easy
HLSL? no. But possibly can plug it into lit inside of shader graph?>
i will trys
hmm I think sprite lit just means 2D lights
I just remember it being a pain with shader graph but it's been a while. May be able to do it with just a lit graph nowadays
hello, i have a question. i have a script that turns a specific object to face another object that I use for head rotation on animated rigs (very simple script, it's just Quaternion.Slerp in LateUpdate). the problem is - when i disable the animator component and enable it back - suddenly the head turn stops working and it locks the head in the last rotation it had. it slightly jitters (my guess) attempting to rotate towards the target, but it can't. constantly disabling and enabling the animator component causes the head to rotate and then stop, so my guess is that animator sort-of locks the bone. also happens on disabling and re-enabling the object. i applied the mask to the animator base layer, so im out of ideas for why it can be the cause. what might be the cause of this issue?
Animator normally overrides transforms, iirc there is an option to disable that
masking out the bones in the import settings does help, but sometimes the animation should still play, and applying mask to the animator layers seemingly does not work.
yeah that's what i figured, though i assumed masking would help
may i ask why you are enabling and disabling the animator at all?
maybe you can split it between two gameobjects one controlled by only animator and one through script
i also mentioned enabling and disabling the entire object
it doesn't happen only on animator disable
same question applies to the go
because its better than destroying the object
guys can i delete the cooldown after jumps? cuz after landing on the ground there is a little time around 2-3s when i cannot jump
hm sometimes i do want to play the animation it had, like when there is nothing to look at, it should default to the animation it had prior
we´d have to see some code
okay, it is fine if i paste here?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
a powerful website for storing and sharing text and code snippets. completely free and open source.
the // in hungarien if i forget
ok
if you want a slightly earlier isgrounded detection you would use a raycast
before you land the rc would detect the ground a few ms earlier, this will allow you to jump with nearly no delay when you land
Another option would be to store the user's jump intention for a few milliseconds after they press it and immedaitely jump if you become grounded during that time.
also a decent idea
thank u guys
thanks so much it wokred that saved me 20 hours
If you need shadow casting you can turn on debug mode and enable it on the sprite render. It's odd that they did implement shadow casting on that but not 3D lights.
assuming your method doesn't already implement it. I forget which has priority
How do I get BuildNavMesh to only apply to certain objects. Currently it's trying apply onto every object which causes errors.
How do i achieve better blending between 2 rule tile sets
is this a coding question or
you need to mark only the desired objects as nav static
Thank you
pretty sure this is outdated by now with using the navmesh surface components
It's rule tile related, im not sure if it requires code or not, but i essentially want it to consider rule tiles as valid neighbours for this
couldnt find a newer doc, but it is pretty same concept
Last time I dealt with unity's nav tools I remember having to disable gameobjects and bake it for stuff I didn't want to bake on lol
have you actually verified that because the new global bake doesn't exist anymore and now is reliant on the navmesh surface and which objects and layers are there
It says that Navigation Static has been deprecated
well yes cause as mentioned global bake isn't a thing anymore
Navmesh surface lets you chose which objects to bake, you have several options on how to approach that
one Mao mentioned could also be an option
navmesh surface has an option to only bake on "children" gameobjects you could also use that so like temporarily make the navmesh objects the child of navmesh surface gameobject, bake and unparent
would make more sense to have a tag system for it tbh
but knowing unity they would tie it to your physical layers
layers or tags wouldnt make sense because it would brake other things..
these are the options
modifiers can do a lot of the heavy lifting but its quite annoying having so many components on random objects
but beats having to use that "Static navmesh" option per object, that was also annoying just less a component
time to make an asset then
the A* project iirc had a solid navmesh before unity changed it, I wonder how they did it. I only had the free version for 2D but heard the 3D had good things
Unity sort of caught up with them
it's just better
the free version is kinda unnecessary now
while the paid one is still strictly better
I think the runtime bake was only specific to that asset
does unity even have 2D navmesh yet
sadly no
oh wait
lel
is this for 2d?
A* path project did 2D but as actual grid not navmesh only the 3d one
the 2D one from h8man on github uses the Unity navmesh iirc but for 2D not sure why unity couldn't just do the same
Unity's navmesh is actually fine for 3D. But their agents and avoidance is primitive
So if you are making an RTS game, Unity's agents fall flat instantly
it takes a lot of fiddling to get some real solid results and even then requires you to manually mess around with the pathways
like getting only the path then process it yourself to add some curve to it or making it slightly longer / not so robotic.
by moving the agent using those point but agent.Move insteadof the SetDestination
downides of only using "shortest path"
check out people like LlamaAcademy they go indepth with this stuff
The big problem is the API for the agents is limited. It's less like a motor and more like you see is what you get and don't think about modifying it further.
to be fair for most basic usecases it just works ™
Yeah true, it's more like a teaser until you want to actually put some money into it.
like some of the problem like them being "singlefile" when putting 1 destination is easily solved by adding several points to try to "surround" player and so on
every horde zombie shooter in unity "SetDestination(player.position)"
done
🙄
Good way to add some variance to updating the path, so they aren't always dead eye on you
let them overshoot the location sometimes so they can get around you
yea exactly, you gotta play around with the chosen destination then switch up later when certain distance or something
main pet peeve for me , when multiple agents are in a narrow hallway and especially going in opposite direction and they get stuck 🤦♂️
a* project is all about the avoidance and fixing these issues but otherwise Unity's fine for some smaller dumb AI games
iirc unitys navmesh used older version of RVO but I think now its some other custom solution
I just know that if you have 30+ agents together with Unity's agents and RVO enabled the game fps just tanks
modifying the behavior of navmesh agents is such a pain. and god forbid you're slightly above the ground, because navmesh generates only one-way links
and other options are either free a*, paid a* or custom thing that will take months or years
tho there might be more pathfinding solutions if you're willing to pay
Hi-ya! I need to make my Start method in a script to wait 5 frames after it should be called to do the things inside. IS there a way to do this?
Start can be a coroutine, but that also sounds odd, why does Start specifically need to wait 5 frames?
Because it looks for a component that also gets made in start, and after putting the calls in update the error only happens for 3 frames.
why is the component "only made in Start"? why can it not be made in Awake?
well its on a OnClientStart from FishNet. So the components get called before they are made since making an object/component takes more time then attempting to find it in a small list of children
sounds like the object that needs a reference to it should actually just be subscribing to an event that the spawned object invokes when it is spawned
And how can i do this?
create an event on the object being spawned, invoke that event at the correct timing you'd like. have the other object subscribe to the event before it is invoked
k thx
I have been using unity assets for my game character. The only problem is I want more animations. Is there a good video tutorial on how to create animations for existing models?
#🏃┃animation
although this isn't unity question, you gotta use other animation clips or do them yourself in something like blender
3D sorting transparents
does anyone get this bug or know how to fix it where you go into a prefab, set a number, then exit the prefab and it isn't saved properly?
Like I go and try to make the width of something 150, even press ctrl+S to save, and exit the prefab and it has a width of 1 or 15, cutting off the last numbers? It's very annoying
Are you looking at the prefab or an instance of it already in the scene? If that instance has overridden those values it won't automatically update to the prefabs values if you change them
So, if you made an instance, modified a value, then edited that value on the prefab, the instance won't have that value changed
no I'm editing the prefab file through double clicking in the assets, its not an instance
is it really that bad to store static gameobjects to scriptable objects?
I'm trying to make a viewmodel system where it links with my hotbar
and what im basically doing is, fetching the itemData from the item in the slot, then seeing what viewmodel prefab its going to use (they are all children in the player's camera) and then it calls my viewmodel manager that handles disabling and enabling the objects correctly
I think I did a similar thing? When I made an inventory I used ScrObj for items, with a prefab field. The inventory was just a list of ItemData, to use an item you could just access ItemData.prefab
The downside is you have to assign everything correctly, because it's a circular dependency where ItemData has a field for the prefab, and prefab has a field for the ItemData
couldn't I just code an extension that basically auto assigns it normally to the genericPrefab I have going on?
If you want to, not sure how much time would you save with this though.
When I wanted to make 3D previews, I just put a secluded area on the level, placed a camera that outputs to a render texture and when the game wanted to show you the viewmodel it'd just instantiate the prefab before the camera and the render texture was on the UI.
do you generally make the camera follow the player, or make the player bring the camera to itself?
generally the former because it's better for the camera to be in charge of it's related responsibility but honestly either is fine
how do you make an object call the position of another and go to it? (take a wild guess what the implementation is for this)
reference.variable to access public fields/properties of another object. And "go to it" is basically changing the object position closer to that target position every frame.
I'd suggest going over the basics and/or watch some tutorials. Since you're asking very basic questions.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I used too much ai over the summer and need to relearn traditional methods of learning programming 😔
i got used to being able to answer niche questions
These are not really niche questions.
And yeah, I wouldn't recommend using AI if you can't reason about these things with your own head first.
didn't say they were
didn't mean to send that so early
I'm trying to make a sprint in this basic movement system I'm just messing with, but I'm getting stumped on how to actually make them sprint with the way I have things set up.
Tl;dr I'm using a separate input system and character controller, but all the input system does is just gather the inputs it doesn't have any direct affect on how anything actually works, and for the sake of brevity I've taken everything out that isn't directly relevant.
private CharacterController _characterController;
public float walkSpeed = 10f, runSpeed = 20f, RotationSpeed = 5f, JumpForce = 10f, Gravity = -30f;
void Start()
{
_characterController = GetComponent<CharacterController>();
}
public void Move(Vector2 movementVector)
{
Vector3 move = transform.forward * movementVector.y + transform.right * movementVector.x;
move = move * walkSpeed * Time.deltaTime;
_characterController.Move(move);
}
public void Sprint()
{
if(_characterController.isGrounded && Input)
{
}
}
The sprint function isn't finished yet, but I'm trying to do is swap the "walkSpeed" with "runSpeed" whenever the player presses the sprint button and I'm using the new input system so I can bind it to the "sprint" action broadly rather than a specific key like the left-shift key. What's most annoying is that I'm pretty sure I've already done something like this in the past but I can't find it and I can't remember how I did it.
I'm trying to do is swap the "walkSpeed" with "runSpeed" whenever the player presses the sprint butto
That sounds like a pretty solid approach, and your english sentence here is pretty muhc a fine way to structure it.
Something like:
bool isSprinting = false;
float currentSpeed;
float walkSpeed = 10;
float runSpeed = 20;
public void ToggleSprint() {
// invert the bool
isSprinting = !isSprinting;
// set the speed based on the bool
currentSpeed = isSprinting ? runSpeed : walkSpeed;
}```
then you just call ToggleSprint when the player presses the button
unless what you mean is more like "sprint whil ethe button is held down"?
Is that what you mean?
Yeah while the button is held down
So it will kind of depend on how exactly you're handling the input in code
(just a lil' explanation of how this ternary operator works if your not familiar with them)
My input system looks like this, again irrelevant aspects have been removed for brevity.
public PlayerController CharacterController;
private InputAction _moveCommand, _lookCommand, _jumpCommand, _sprintCommand;
public void Start()
{
_moveCommand = InputSystem.actions.FindAction("Move");
_lookCommand = InputSystem.actions.FindAction("Look");
_jumpCommand = InputSystem.actions.FindAction("Jump");
_sprintCommand = InputSystem.actions.FindAction("Sprint");
_jumpCommand.performed += OnJumpPerformed;
_sprintCommand.performed += OnSprintPerformed;
Cursor.visible = false;
}
private void OnSprintPerformed(InputAction.CallbackContext context)
{
CharacterController.Sprint();
}
but I'll assume you have something like this, so here's an example
public void OnSprint(InputAction.CallbackContext ctx) {
if (ctx.started) { // on initial press
SetSprinting(true);
}
else if (ctx.canceled) { // on release
SetSprinting(false);
}
}
void SetSprinting(bool sprinting) {
currentSpeed = sprinting ? runSpeed : walkSpeed;
}```
ok in this case you'd do this:
_sprintCommand.performed += OnSprintPerformed;
_sprintCommand.canceled += OnSprintCanceled;
}
private void OnSprintPerformed(InputAction.CallbackContext context)
{
CharacterController.SetSprinting(true);
}
private void OnSprintCanceled(InputAction.CallbackContext context)
{
CharacterController.SetSprinting(false);
}
And setSprinting would just be something like:
public void SetSprinting(bool sprinting) {
currentSpeed = sprinting ? runSpeed : walkSpeed;
}```
(optionally with an internal bool variable if you need to know that info for other things too)
And the setSprinting would be in the controller script or the input script
Or does it not matter
Cause they're both connected anyway
controller
currentSPeed is a property of the controller, not the input
Well I'm not getting any errors but it's also not making me faster
you'd have to show the current state of all your code, as well as inspector defined values, etc
also potentially the configuration of the input action
InputController
public class InputHandler : MonoBehaviour
{
public PlayerController CharacterController;
private InputAction _moveCommand, _lookCommand, _jumpCommand, _sprintCommand;
public void Start()
{
_moveCommand = InputSystem.actions.FindAction("Move");
_lookCommand = InputSystem.actions.FindAction("Look");
_jumpCommand = InputSystem.actions.FindAction("Jump");
_sprintCommand = InputSystem.actions.FindAction("Sprint");
_jumpCommand.performed += OnJumpPerformed;
_sprintCommand.performed += OnSprintPerformed;
_sprintCommand.canceled += OnSprintCanceled;
Cursor.visible = false;
}
public void Update()
{
Vector2 movementVector = _moveCommand.ReadValue<Vector2>();
CharacterController.Move(movementVector);
Vector2 lookVector = _lookCommand.ReadValue<Vector2>();
CharacterController.Rotate(lookVector);
}
private void OnJumpPerformed(InputAction.CallbackContext context)
{
CharacterController.Jump();
}
private void OnSprintPerformed(InputAction.CallbackContext context)
{
CharacterController.SetSprinting(true);
}
private void OnSprintCanceled(InputAction.CallbackContext context)
{
CharacterController.SetSprinting(false);
}
CharacterController
public class PlayerController : MonoBehaviour
{
private CharacterController _characterController;
private float MovementSpeed;
public float walkSpeed = 10f, runSpeed = 20f, RotationSpeed = 5f, JumpForce = 10f, Gravity = -30f;
public float _rotationY;
private float _verticalVelocity;
void Start()
{
_characterController = GetComponent<CharacterController>();
}
public void Move(Vector2 movementVector)
{
Vector3 move = transform.forward * movementVector.y + transform.right * movementVector.x;
move = move * walkSpeed * Time.deltaTime;
_characterController.Move(move);
_verticalVelocity = _verticalVelocity + Gravity * Time.deltaTime;
_characterController.Move(new Vector3(0, _verticalVelocity, 0) * Time.deltaTime);
}
public void Rotate(Vector2 rotationVector)
{
_rotationY += rotationVector.x * RotationSpeed * Time.deltaTime;
transform.localRotation = Quaternion.Euler(0, _rotationY, 0);
}
public void Jump()
{
if(_characterController.isGrounded)
{
_verticalVelocity = JumpForce;
}
}
public void SetSprinting(bool sprinting)
{
MovementSpeed = sprinting ? runSpeed : walkSpeed;
}
}
you character controller ignores the MovementSPeed variable
it just directly uses walkSpeed in the Move function
That would explain it
Okay I swapped it for MovementSpeed but now it isn't moving at all
in Start you should do MovementSpeed = walkSpeed;
so it's initialized to walk speed instead of just 0
beyond that - make sure SetSprinting is getting called with Debug.Log
You have to call the DontDestroyOnLoad method, not name your class that. See the example in the documentation: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Object.DontDestroyOnLoad.html#:~:text=DontDestroy.cs script%3A
I forgot it in this script but it doesn't work anyway i tried it with many scripts
The example in the documentation works. If it doesn't work for you, you did something wrong
I forgot to check out that link i will try it
public class DontDestroy : MonoBehaviour
{
void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
if (objs.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
}
This won't fit my case
what in here doesnt fit your case?
Like i want to control only one object not an array of objects
FindGameObjectsWithTag just finds all instances, and if there already is one it destroys all further
its just the return type of that find function
you will only find one (most likely, unless something went wrong)
"This does not work" is not an error description
When saying things like this maybe include what is not working
Okay i managed to make it work:
using UnityEngine;
public class DontDestroy : MonoBehaviour
{
public GameObject[] objs;
void Awake()
{
if (objs.Length > 0)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
}
It doesn't work on cameras tho
What even happens if you DDOL an object that is also being Destroyed 🤔
presumably it gets destroyed
Probably just destroys fine?
DDOL just moves it to a different scene, no? stuff in there can get destroyed just fine
and Destroy works after a frame, so i don't think DDOL would end up targetting a destroyed object
if it were DestroyImmediate, that could have issues though
Is the objs array supposed to check if there's multiple of these objects alive?
what even is this
At this point i don't even know what i'm doing I've been trying to make it work for 2 hours
a bastardized singleton? lol
You probably want to search for how to make a DDOL + Singleton class
I'll search for it thanks
Ah yeah that has a DDOL example^
using UnityEngine;
public class DontDestroy : MonoBehaviour
{
private static DontDestroy _instance;
void Awake()
{
if(_instance != null)
{
Destroy(gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
This would work if I made separate script for every object i want to keep
yes, that's typically how the singleton pattern goes
if you have like, 10+ objects you want to keep, you might just.. have too many
But you have no content in your class, if you want the camera to not destroy you better include it in your class.
I will just add this part to camera and ui class
like that
you generally don't add this to stuff
stuff is a singleton, not has a singleton
Here DontDestroy object has children UI and Free Camera(screenshot 2) but when i start the game (screenshot 1) they aren't it's children
Do they also have some script that sets them DDOL?
Because DDOL should be only used on the root object
"DontDestroy" has that script
what is going on there..
Where do the UI and camera objects go when you start thet game?
you don't need a DontDestroy class
they dissapear for some reason
Then you have some script destroying them
I do not
your DontDestroy has one...
And you used the search feature to confirm that they really are being destroyed?
For the purpose of keeping these persistent objects alive (and only 1 instance of them), why not?
why not just have the actual class that matters be the singleton, so it's actually useful
They didn't really ask for a specific singleton, just DDOL
they're using the singleton pattern in their DontDestroy, and given that this is not in a persistent additive scene, you'd need a set in each scene for ease of testing
it's already a singleton, just not a particularly useful one
it's in the actual class of the camera controller, rather than some generic DontDestroy class, right?
Yes
could you be more specific as to how it isn't working for the other one?
When i start the game I have both Free Camera an DebugUi. When I switch scenes only Free Camera is present on the new scene
But it's not
these gameobjects are active, right? also make sure you've saved and recompiled
Yes they are active and i have auto compiling
I will show screenshots
could you show the hierarchy as you switch scenes
FreeCamera and DebugUi are on Free Camera and UI?
yes
neither appear to be in DDOL there
And now the free cam also doesn't work!
Exactly
do you have domain reload disabled
Oh i accidently moved the code files to downloads when i wanted to put on discord instead of copying
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Okay everything now works. I created two scripts FreeCameraDdol and UiDdol with private void Awake() { if (_instance) { Destroy(gameObject); return; } DontDestroyOnLoad(gameObject); _instance = this; }
General idiomatic way is to be more explicit and do if (_instance != null)
While it won't have much difference here since Unity has custom behavior it never works for other non-Unity classes unless they do the same
I copied it from the internet and after trying to make it work for 2 hrs i don't want to touch it
If this took 2 hours of work then it might be better to get more familiar with Unity and/or learn what makes this code work
I know i use unity for 2 days
Make sure you actually get rid of the instance when switching scenes so the debug UI can reinitialize. Otherwise it's dangling against a component that no longer exists
Maybe I need to fix something with listeners
I DDOL
Does your other scene have the same UI?
No i have DDOL script. The UI object is only in the first scene (main scene)
Do you have an event system in the new scene?
I do
i got this warning so i changed the relevant line to awake but it still flagging as an error:
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
rb = player.GetComponent<Rigidbody>();
}
why is this happening?
make sure you've saved and recompiled
i have
Did you remove FindGameObjectWithTag from where you were previously using it
also go down the stacktrace, see if it's actually from this script on that line
public class GrapplePointInteractable : MonoBehaviour, IInteractable
{
GameObject player;
Rigidbody rb;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
rb = player.GetComponent<Rigidbody>();
}
void Start()
{
}
public void OnClick()
{
Debug.Log(transform.position);
rb.MovePosition(Vector3.up*20);
}
public void OnDrag(Vector3 hitPoint)
{
//throw new System.NotImplementedException();
}
public void OnDragEnd()
{
//throw new System.NotImplementedException();
}
public void OnDragStart(Vector3 hitPoint)
{
//throw new System.NotImplementedException();
}
public void OnHoverEnter()
{
//throw new System.NotImplementedException();
}
public void OnHoverExit()
{
//throw new System.NotImplementedException();
}
// Start is called once before the first execution of Update after the MonoBehaviour is created
// Update is called once per frame
void Update()
{
}
}
``` i did
i can tell it's this script specifically, but cant find any reference to a specific line
does the stacktrace not have more content?
UnityException: FindGameObjectWithTag is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'GrapplePointInteractable' on game object 'Sphere'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.GameObject.FindGameObjectWithTag (System.String tag) (at <31f3cd5c2a074982a9d5664e7709cac1>:0)
GrapplePointInteractable..ctor () (at Assets/Scripts/GrapplePointInteractable.cs:5)
ah
Maybe you just didn't clear previous errors in the console?
it was indeed disabled
only now i realize the starter asset 1st person controller doesnt have a rigid body -_-
oh well, ill experiment with Translate
oh ok
cc.Move
i'm still not entirely familiar with what CharacterController does or can do, so thanks
i wanted to access the Grounded bool from the script, since it was already public, but im not sure what the correct syntax or function to do it is
.Grounded
you have to type it properly first
i tried that but it shows this
you've typed it just as a MonoBehaviour
oh ok
MonoBehaviours don't have all that extra stuff
that makes sense
it's not quite having the inteded effect, probably being overridden by the firstpersonController script -_-
i wanted to disable the effect of gravity while clicking an object in the world
maybe i could change Gravity instead of grounded
...you were trying to change the grounded state?
i'm trying to make a grapple point you hold and it pulls you towards it
i got the pulling working, but gravity still affects you during it
so i was trying to make the player "grounded" at that time
so, an x/y problem
if you wanted to disable gravity, then disable gravity, not some weird other thing
well, disabling gravity didnt really work either, mostly my interactibility scripts fault
Many controllers disable gravity when grounded to avoid sliding down hill when not moving
(Not sure how relevant that is with CC though)
that would make the CC handle incorrectly though
Right because it expects the gravity to push it into the ground in order to detect being grounded?
yes
Just seems like this script is doing its own ground checks (I see GroundedRadius etc)
this is a world object intereaction script i made for the camera,
the issue is that the dragging action doesnt end when the mouse is off the object, so if i'm still holding when i look away the drag wont end, and gravity wont be reset
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
yes
so you aren't receiving any input whatsoever when the mouse is not on an object
consider handling the cancel/complete actions outside the raycast check
i'm also noticing that if you drag from nothing onto an object and release, it seems that you'd call OnDrag/OnDragEnd on that object
testing on some other objects that last point seems to be the case
so pass the endDrag if to otuside the physics raycast main if?
lemme try
wait no that doesnt work
cause that returns a null if you arent pointing at anythin
you'd be targetting currentInteractable
tbh you should probably be targetting currentInteractable for some other of those too
just makes more sense as you read it
i'm a bit lost, nothing works outside the main raycast checks since both currentInteractable and newInteractable remain null, unless you mean to check currentInteractable in the raycast if check
does anyone know how to smooth out a vector 3?
PlayerRigidBody.linearVelocity = new Vector3(MoveDir.x, PlayerRigidBody.linearVelocity.y, MoveDir.y);
Can you explain what you mean by "smooth out"?
basically when i start moving my player, it feels very snappy
It sounds like what you mean is "smooth out the transition from the current velocity to the user's input velocity"
yup
you could do something simple in FixedUpdate like use the MoveTowards function to make the transition gradual. But you'll want to make sure the y part is not including. Something like:
float acceleration = 5f;
void FixedUpdate() {
// what's the current velocity?
Vector3 existingVelocity = PlayerRigidBody.linearVelocity;
float yVel = existingVelocity.y;
// Establish our target velocity
Vector3 targetVelocity = new(MoveDir.x, yVel, MoveDir.y);
// do the smoothing
Vector3 newVelocity = Vector3.MoveTowards(existingVelocity, targetVelocity, acceleration * Time.deltaTime);
PlayerRigidBody.linearVelocity = newVelocity;
}```
oh wow thanks! i also have a question, what is the difference between Update() and FixedUpdate()?
FixedUpdate is in cadence with the physics engine
which is what matters here because the velocity is only used to move the player in the physics update
Update runs every single frame
You shoul;d read this to get a more thorough understanding: https://docs.unity3d.com/6000.3/Documentation/Manual/fixed-updates.html
the diagrams in there explain it really well
i'll take my time to read it
can i talk about visual scripting here too or not
hi i was looking for a way to slowly rotate an object towards another in 2d. basically i have a missile that i want to aim towards a moving target but i cannot use quaternion.slerp because the missile is constantly changing position as well as the target. i probably need to rotate a vector towards another vector with time, but im not sure how to do that without slerp because slerp i can only really use when vectors are actually fixed
alternatively i could just rotate it clockwise/anticlockwise until the difference in angle is very small but i was wondering if there was some simple solution im missing out on
Quaternion.RotateTowards works
As does Vector3.RotateTowards
Slerp can still work it's just not recommended
YOu can also use angular velocity if it's a rigidbody
this is causing me headaches with it turning on 3d axes so ill see if i can use quaternion.rotatetowards
that does sound almost perfect for me
Everything in unity is 3d
even 2d games
but basically you would just be dealing with transform.right
yeah
e.g.
transform.right = Vector3.RotateTowards(transform.right, directionToTarget, Time.deltaTime * rotateSpeed, 0);```
i was trying to avoid using transform.right/left/up etc. cuz it confused me
it's the simplest way for sure
okay
transform.right is just the red arrow in the scene view
"rotate my red arrow towards directionToTarget"
and transform up must be the blue?
think of it that way
green
okay
transform.forward is the blue
(whether to use up or right depends on how your sprite image is laid out)
im just using a square bullet stretched on x-axis so i guess transform right should make it look correct
make sure directionToTarget is calculated properly as well
it would be:
Vector3 directionToTarget = target.position - transform.position;``` assuming `transform` is the projectile
Make sure you're at the same z position as well
if not you'd need to 0 it out: directionToTarget.z = 0;
yeah i already ran into the z-axis problem and fixed it i was just stumped on the rotation
Hi, anyone try to putting a animation by script like that?
I was trying to playing a animation via script to make a live, when losted, start a animation
But I'm don't know its schizophrenic from my part, or it's realy possible to do this
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
most of that is correct, but this is not:
var _lostLifeHash = lostLifeClip.GetHashCode();
GetHashCode() is completely unrelated to the concept of a "hash" in the animator
every C# object can give you a hash code, and the hash code is meant to be used for things like testing if two objects are the same thing
You want this method:
StringToHash is useful if you're going to play an animation many times. It reduces the amount of work needed to find the correct animator state
I wouldn't bother here, since you're only doing it once
using System;
using UnityEngine;
public class ChestSystem : MonoBehaviour
{
void ChestOpened()
{
// Save the expiration time when the chest is opened
DateTime expireTime = DateTime.UtcNow.AddMinutes(50);
PlayerPrefs.SetString("ChestExpire", expireTime.ToString("o"));
PlayerPrefs.Save();
}
void OnGameEntered()
{
string saved = PlayerPrefs.GetString("ChestExpire", "");
if (string.IsNullOrEmpty(saved)) return;
DateTime expireTime = DateTime.Parse(saved);
TimeSpan remainingTime = expireTime - DateTime.UtcNow;
if (remainingTime.TotalSeconds <= 0)
{
Debug.Log("Chest is ready! You can open it.");
}
else
{
Debug.Log($"Time remaining: {remainingTime.Minutes} minutes {remainingTime.Seconds} seconds");
}
}
}
this code work right ?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi!!! i am beginner and how do i start learning C#?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
👆 this is for my unity oriented stuff
wdym?
like i cant find any good tutorial on yt
is there any site where they teach everythin from basics?
You've been given several
really good one. found in the pins
https://learn.microsoft.com/en-us/shows/csharp-fundamentals-for-absolute-beginners/
and the Unity learn site for unity specific, but you should go through basics of c# beforehand
thanks i will try it
I am trying to code a support Enemy that boosts the Enemies around it. How would I apply the boosts to the enemies around it? I can't seem to figure out how
what's the point of dynamic font atlas for textmeshpro fonts?
like anything in development 
there are dozens of ways to doing this..
what exactly are you trying to boost anyway ?
movement? health ?
Yeah those stuff. I have them in a seperate script, but I don't know how I would apply the boosts on a wider scale than just a singular enemy.
this is a code channel, try #📲┃ui-ux
well you can either do it from the support enemy itself or the regular enemies,
for example the support enemy can grab all the enemies in its range and then apply the movement / stats boost
when they exist the range you debuff it
How would I get the information of all the enemies in range and apply the buffs? I tried GetComponent but that doesn't work for 2+ enemies since it only grabs the script from a single enemy.
many ways, one of them uses physics like and overlap or OnTriggerEnter/Exit
probably less efficient , if without collider those you need a way to register enemies in some sort of tracker / list and youd have to compare distances at certain intervals and if they are within range you'd apply/remove the buff
Overlap would for example give you an array of enemies within a zone then you can loop through those and apply it
i feel like we could make a nice little visual guide on the ways you communicate between things
i´d also recommend using overlap all the way
overlay is good but you'd need a way to tell if they left the zone if they entered one
TriggerEnter/Exit may be easier for a beginner
Enters Trigger -apply buff
exit Trigger - remove buff
I've never heard of Overlay before. I'm going to do research into it.
why do textmeshpro assets change when the code is compiled?
there now it's a code question
2d or 3d game?
3d
overlapsphere is what you need
Oh thank you.
for optimization purpose the NonAlloc version is better
remember Overlap will only tell you whats inside RIGHT NOW
probably doesn't. probably changes on domain reload
pretty simple to do check though, you can keep the colliders tracked inside a HashSet then compare at the end of the frame
After I know whether the Enemies are inside or outside the radius how would the buff be given to them?
you can either do it through a method that modifies the stats you want, or maybe apply a specific component for buffs.. really depends on the design
unityevent could be really helpfull, you invoke the event and all the enemies that are nearby get informed
I honestly forgot UnityEvent existed
could also work yeah you just need to consider how many things can apply those sorts of buffs
The only fix I've found for this is to paste into a textbox that uses the font a text file with all characters you will use (alphabet/num/sym) and then set it to static. Otherwise you get artifacts like a single letter in a word using the fallback text.
as nav said, there are really many ways of doing this
You quick question: my and two friends are working on a game for school and it is my task to figure out how to store general data while the game is running. We have a post void-like game and we need to store in what level the player is, and how long the current level should be, the score of the player and those things. How do we simply store those? The data doesn't have to be stored if the game is closed.
It would be nice if setting to static gave you a default working set of symbols
ScriptableObject's
Singleton DDOL
Both ! 😛
I only need one
either will work (since this isn't a permanent save anyway)
i´d simply use a static non MonoBehaviour for this
that could work too
orr a singleton could also do the job
depends on how they wanna store what level the player is in
after all SOs are very similar to how static class works (data itself per SO)
im scriptable singleton pilled now
my only requirement is that it has to work
thats a good requirement
and maybe that it doesnt cause my game to crash
since the deadline is tomorrow and we procrastinated a fuck ton
thats vague . all the mentioned methods *just work *™
I like the example this has
https://unity.huh.how/references/singletons
i think someone needs to spoonfeed that dude he is in a hurry
people in a hurry can starve then 😛
awake assignment and not a getter tho ehhh
is it just making a background scene with a script attached that stores the data>
just open the link homie
alright big boi
I dont see a reason to needing to run it on every get or am I misunderstanding what you said
generally the pattern i use just checks if the field is null and if it is assigns it
so it is a null check per reference fair
i guess you could use a bool though idk
awake just feels a little flimsy, maybe its a skill issue on my behalf
so I make the singleton class with the variables and maybe a method or two, and when I need it in a class I just make that class inherit the singleton?
can it inherit both singleton and monobehaviour at once?
thats if you create a generic
which code block are you looking at. @gilded badge
yes if you use the second pattern then you would put the public fields you want / method in the child class
thats if you want to make multiple singletons without having to keep writing the same pattern for each (we avoid repeating code as much as possible for clean code)
I think i just need one?
if I were you I'd make a struct for that data you want then put that in the singleton
[Serializable]
public struct LevelData {
public int Score;
public int Level;
}
public class MySingleton : MonoBehaviour {
public LevelData LevelData = new();
//awake setup
...
MySingleton.Instance.LevelData.Score = 32
etc.
so I do
Singleton.cs
public abstract class Singleton<T> : MonoBehaviour
where T : Singleton<T>
{
public static T Instance { get; private set; }
void Awake()
{
// Destroy this object if we already have a Singleton defined
if (Instance != null)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
Instance = (T) this;
DoAwake();
}
// Virtual method to allow implementations to use Awake
protected virtual void DoAwake () { }
}
public class YooooooData : Singleton<Foo>
{
double score = 0;
int iterationlength = 12;
}
dosomestuff.cs
using UnityEngine
class DoSomeStuff : Monobehaviour
{
void Start()
{
Debug.Log($"hey look data {YooooooData.Instance.score}");
}
}
YooooooData.Instance.score
oops
I'd still recommend storing some stuff in a saperate POCO if you later decide to save it in a file
Slightly unrelated but try to strive for more logical class and variable names
this isn't advice for bread person but just on the topic of singletons i've really been liking this
public class ScriptableManager : ScriptableObject
{
private static ScriptableManager _instance;
public static ScriptableManager Instance
{
get
{
if (_instance == null)
_instance = Resources.LoadAll<ScriptableManager>(string.Empty)[0];
return (_instance);
}
}
having singletons as scriptableobjects has been super helpful in not having to rely on a given scene having to be loaded up and/or cursed editor code to redirect scene loading and stuff
(string.Empty)[0];
this means you have to use Resources folder and hope its the first one is the proper SO?
this is an example, when it comes to naming variables I am very serious tothe point where I ponder for two straight minutes what I should name everything
i dont but thanks
I don't trust myself with this level lol
maybe with a subfolder
I once had KuusiMethodsMethods and it took me ten minutes to come up with something better 😭
Yeah i used to use Resources but switched to Addressable if needed
(not this usecase specifically tho so it doesn't matter in the long run )
i was pondering if it was possible to use a little editor script to create and assign an instance of a scriptablesingleton to the actual monoscript and if that worked as a reference to an asset for builds
very cursed option so haven't tried it
oh me I'd use any excuse to try making editor script xD sometimes I enjoy it more than coding in unitygame itself
as a javascript and typescript soydev, I am glad to see arrow functions in C# because they are just so clean if an entire function body is one return statement
oh absolutely but im sick of being unemployed so i gotta actually make games 😭
what was that old saying, always spend 5 hours automating what can be done in 1 by hand
exactly
i was so lazy to fix some animations in blender i created an editor script that lets me apply offsets all at once across keyframes
look at this before and after cleanup of this inspector 😄
way too much time spent on this
never got used !
so much time on unused tooling
I have a bunch of those but I look back and rather have something pleasant to look at later on lol
ok so what did you do to test and whats the result
// Sla hier global data op
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour
where T : Singleton<T>
{
public static T Instance { get; private set; }
void Awake()
{
// Destroy this object if we already have a Singleton defined
if (Instance != null)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
Instance = (T)this;
DoAwake();
}
// Virtual method to allow implementations to use Awake
protected virtual void DoAwake() { }
}
public class ContextData : Singleton<ContextData>
{
public double score = 0;
public float mapSize = 6;
}
using System;
using Unity.AI.Navigation;
using Unity.Mathematics;
using UnityEngine;
using static Utils;
public class GenMan : MonoBehaviour
{
readonly int iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
Vector3 currentCoordinate = new(0, 0, 10);
int currentAngle = 0;
[SerializeField]
private GameObject straightHallSegment;
[SerializeField]
private GameObject leftTurnHallSegment;
[SerializeField]
private GameObject rightTurnHallSegment;
[SerializeField]
private GameObject startRoomSegment;
[SerializeField]
private GameObject endRoomSegment;
private NavMeshSurface surface;
// Sanity check :D
void Awake()
{
if (iterations < 6)
Debug.LogError($"invalud iteration: {ContextData.Instance.mapSize}");
// unimportant
}
void Start()
{
// unimportant
}
}
this is the error
if you're getting a null reference its most likely because you're trying to call this in awake before the other awake ran
that error line number doesn't match your code (line 9)
you can change the script order or access singleton in start
it does? line 9 is readonly int iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
see getter tech im telling youuu
Also this:
void Awake()
{
if (iterations < 6)
Debug.LogError($"invalud iteration: {ContextData.Instance.mapSize}");
// unimportant
}```
Is liabler to run into an execution order issue. If GenMan.Awake runs before ContextData.Awake, the `Instance` property will be null
ah yeah same issue
thats seems logical
that's especially bad
trying to access it in a field initializer like that isn't gonna work
so I think I should call the ContextData.Awake() somewhere?
true
iterations I would probably make a property so it's lazy loaded
it will get called, it just hasnt by the time the other code is running
Move your sanity check into Start not Awake
Singleton setup Awake
Other Scripts access that singleton Start
otherwise you need to change the script execution order
your trying to walk into a store before they are open
you can stop i understand the metaphor
you're trying to poo before the toilet seat cover has been open 🤔
omg i get it
your trying to enter the last judge fight without ringing the bells
what do you mean by this
oh shit
do you know what Start method is ?
better head back to shellwood then
right now the code is running
GenMan.Awake()
ContextData.Awake()
you want the stuff in genman.awake to happen after contextdata.awake
it executes when the scne starts or when the gameobject is created i dont remember which one i think the first
point is it runs after Awake guaranteed
dats it
i do now
when you do
Script1.Awake()
Script2.Awake()
its not guaranteed which one will run first unless you messed with execution order
okay ill test now
so usually ppl do
Script1.Awake()//Setup
Script2.Start() // usage
okay so i put the sanity checkin start, genman doesnt have an awake method now but it still doesnt work
"it doesn't work" is vague
you have to be more specific
is there a contextdata component in the scene
put Debug.Log inside ContextData Awake and see if it runs
no i have not heared about that yet
ah i guess that was a lost assumption
MB need to be on gameobjects to run
its not in the tutorial page so honestly fair
you just gotta stick it on a empty object
its kinda unity 101 stuff lol
dont 🙄 me
ehhh your not wrong but with the statics and generics it might get lost in the sauce
this doesnt work but that doesnt surprise me now
listen I suck a lot at unity the things i learned today only is already huge
wait in the scene?
did you put it in Singleton<T> class though because Awake is running from there
no
trying that now
the Awake in ContextData you put isn't running because it should tell you its running the one from parent
"something something hides inherited member.."
how do I add a component to a scene?
do i do that in the script or in the editor?
oh
GameObjects -> Containers of components basically
MonoBehaviours -> Components
to the gameobject that GenMan.cs is attached to or does that not matter
Ideally on its own Gameobject with the same name so its easy to find but it doesnt matter where, as long as you remember where it is
alright
especially if its a DDOL you may not want GenMan to be carried too
i have that
ContextData.cs should be its own file
now you should be able to add component
yay its there
now it says that there is a NullReferenceException at GenMan.cs, which is this readonly int iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
Im guessing its because awake hasn't been called or something?
yes, you'd (ideally) want to wait until Start or later to access the singleton, and a field initializer runs before even Awake does for that object
okay so how do we make it wait
iterations = Convert.ToInt32(math.floor(ContextData.Instance.mapSize));
put this in start
didn't we tell you this earlier a few times
you make the field not readonly and assign it in Start or later
heres a rule of thumb, if I make the mistake 4 times, its because i don't understand you
ask for clarification then
here's another rule of thumb: if you don't understand something then ask for clarification instead of ignoring the things people tell you
alright, thats true, my fault
I apolagize
Okay it works now yippie :D
Okay so for context when i reach the end of my level, you dive inside a swimming pool whose walls are made of gruyere cheese (long story), which increases the level lenght (which is what i needed the contextdata for), and then reloads the current scene so you start at the beginning again and clear the slightly longer level again
problem: when the scene is reloaded, the map doesn't generate (which means the contextdata isnt delivered properly somehow)
where did you put the DDOL ContextData at, which gameobject?
cause that causes that object not to be destroyed on reload
what is DDOL?
on the object that spawns the map
DontDestroyOnLoad
aha
that was to keep the values "saved" between reloads
the object wont run awake / start again in that case
aha, so the reload script looks like this:
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndLevel : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Debug.Log("Level cleared");
SceneManager.LoadScene("Game", LoadSceneMode.Single);
ContextData.Instance.mapSize *= 1.2f;
}
}
dont you want to set map size before you load the scene?
yes, lemme swap order
iirc that will run all lines until the end of the frame no ?
maybe im wrong nvm just swap the order just incase
i don't think so?
i also could be wrong
pretty sure that will at least pop awakes on the new scene before getting to mapsize
can I put the contextdata on a different gameobject and then access that?
you have no reason to do that
contextdata should be on its own object if you dont want other objects to DDOL
which I dont because that causes the map to not reload right?
DDOL will keep the gameobject "alive" do you want MapGen to also not reload awake/start
i do want it to restart so it generates the map again?
so then dont put it on the same contextdata object because its set as DDOL
yes
DDOL = dont destroy this gameobject between reloads / scene changes
this
I did say this earlier, yes its should ideally be its own gameobject
alrihgt let me do that
🙂
for some reason my dropdown doesnt remove the checkmarks of previous selections?
i dont have multi select on, so im confused on why this is the case
How did you select all three?
just clicking
And that's after unchecking the multi select?
yep
Does it stay unchecked at runtime?
yep
Can you take a screenshot of the whole component?
code:
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class DifficultySelect : MonoBehaviour
{
[SerializeField] TMP_Dropdown dropdown;
void Start()
{
dropdown.value = GameManager.instance.difficulty;
dropdown.onValueChanged.AddListener(ValueChanged);
}
void ValueChanged(int index)
{
GameManager.instance.SetDifficulty(dropdown.value);
}
}
Oh, it's the tmpro one...
lol glad im not the only one that groans when i see that
welp no clue what i did
but now it works
LOL
average unity bug ig
Yeah, tmpro components aren't documentes very well beyond the regular text components.
There isn't even an explanation of that property anywhere.
private void InitializeGame()
{
GameObject navMeshSurface = new GameObject("NavMeshSurface");
DontDestroyOnLoad(navMeshSurface);
surface = navMeshSurface.AddComponent<NavMeshSurface>();
surface.layerMask = navMeshMask;
surface.BuildNavMesh();
Debug.Log("Meow Meowed");
}
before i get too deep into debugging this any guesses on why the navmesh seemingly fails to generate nicely in builds but is fine in editor? the log runs and theres no meshes to cause r/w issues
solved, was popping off from
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
in build i needed
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
How do i get out of tutorial hell?
I've been through it before it just seems a bit slow because I have less and less time overtime
e.g. making a basic movement system for an FPS game, what's the best way to do that?
*I have proficiency in lua(u) because of other game development engines
there is no best way
there's honestly a million ways
best way to get out of tutorial hell is to slowly learn how to learn so instead of relying on strict tutorials you can figure out which specific parts of code and/or unity you don't understand so you can learn that part individually and put them together like puzzle pieces
yeah i get that
i read API alot but i wanted to speed up the process
because i would've saved alot of time if i just found out about a peculiar one
it's easy to find a movement system for a fps game, even unity hub has some templates and tutorials directly
pick that and work with it 😛
tanks
okaythajnksgoodnight
Got a code philosophy question. Which is better? Having a singular script involved in all things player movement, or a bunch of smaller scripts for individual actions?

"better" is funny concept
Kinda curious what different situations call for what
depends
can player movement be restricted for some reason
if yes, smaller scripts might be better
I guess here's one example rolling around in my head. What if an item gives a new movement option exclusive to it?
it would be easier to just attach a component
rather than do an if else in one big script
as long as you don't have 8 billion movement options, the resource cost is inconsequential
So in that situation multiple smaller scripts would be the approach?
Gotcha. I imagine if it was something where your movement options remain static, then one big script would be fine
what do you mean "static"
Oh, so like you don't "lose" or "gain" movement options
you wouldn't need multiple components when every movement behaviour is clearly identified
if you need things like moveSpeed changed or something you can still make methods, or specific stat component
Gotcha. I think I have a better picture here
is there a good way to serialise stat modifiers that modify arbitrary stats
so like don't put inputs in a movement script cause now you're limited by Player controlled movement and now you need to make a separate script for enemy, when you can just keep the same script but pass inputs via method so only player requires "input capture component"
Ah, yeah I got something like that right now. A component dedicated to input capture
say a sword modifies the "attack" field, a shield modifies both "attack" and "defense" fields
how would i go about converting the "attack" in json to a class field reference
without a massive if else / switch case statement
rn i'm thinking generating a dictionary with reflection on awake so i can just index things, but it feels wrong almost
dont you have like an enum or something more reliable than a bunch of brittle strings to match ?
wouldn't that be a nightmare to manage
if you have a few dozen stats you need a enum with a few dozen entries
how so ?
and how would it be referenced in a json
how many stats you gonna have
the ussuals ?
public enum StatType{
Attack,
Defense,
Speed,
CritChance
}
there's around 10 so far
{ "stat": "Attack", "value": 10 },
..etc```
i'd also want to open it up for modding
isn't Attack still a string at the end of the day
in json but not in your game logic
i don't reckon the dictionary will be used during game time,
it'll just be used when loading a character to switch all the "stat" strings in json to an object reference
all you gonna do is get the json stuff and convert to object, the rest is handled in like a dictionary
then this might limit you to strings then
enums are def closed
figured
should be fine if i don't use the dictionary outside of loading the character?
wdym why whats wrong with dictionaries
dictionary is common in modds
I meant with strictly reflection only and not implementing a more structured thing to fallback on
but how much you gonna give leeway that wont just break your game lol
i'll be running stat checks frequently with a lot of objects, figured indexing the dictionary with string would be slower to just using the class field
there's not really any point of using the dictionary afterwards? unless it's a stat that's modded in then yeah
it is but not by much
it still gets hashed afaik
also avoids magic string in the code
something like this for class fields
Stat stat
Stat anotherStat
dictionary<string, Stat> statIndex
All vanilla code will use stat and anotherStat directly, mods will have to resort to the dictionary to access the stats
stat, anotherstat are also kept in statIndex
when an character gains an item
{"stat": "anotherStat", "value": 5} creates a modifier class instance with a reference to the anotherStat object from character, and value of 5
yeah
something like this effectively
Negligible difference over other approaches. I would suggest sticking to the simplest approach and not worry about excessive optimization early in development
I don't know the logic your mod has so I can only assume things but generally these are not the things that will cause performance issues
Is there an equivalent of OnPointerDown/Up but for gamepad face buttons?
It depends what you mean
Do you mean when using UI navigation? Or do you mean when using a virtual cursor
Or do you not mean UI at all
UI navigation on a button
You need to provide more details about the situation
There's OnSubmit if you're hitting the submit button
ISubmitHandler
I need to be able to hold down the south face button on a controller to press a button, not just pressing it
Are you using the new input system or old
Also progress a progression bar so I need to know when the button is first pressed and when it stops.
New input system
And is this for all buttons or just this one
This one and another, not all of them