#💻┃code-beginner
1 messages · Page 244 of 1
can i ask how would I change the speed at which the thingy moved ? (using Speed)
you should probably go through the absolute basics. these are quite simple coding concepts
like a tutorial from one of the big utubers, they explain really well the simplistic side of things
any recomendations ?
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
do absolutely everything he suggests, do it twice, start changing things up, variable names, add things, recreate the wheel, and most of all complete it
aright thx
np
That video probably doesn't go over this, because navmesh's aren't really an absolute beginner subject, so I just wanted to point out that the NavMeshAgent component has a speed property in it
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-speed.html
So just agent.speed
Is it possible to duplicate the current scene and then load into it through code?
copy paste the scene file, add it to the build settings and load it through code
I can't duplicate it through code? I have a endless level game and it displays the current level (Based on the current scene number)
I also have a score counter that is related to the current scene
So I was hoping that it was possible to duplicate scenes through code
In the editor, you probably can. At runtime, no.
Thats a shame
I guess I could use a int that isn't destroyed upon reloading the scene
Yeah, it feels like you tried to approach the problem from an extremely weird angle
I do that a lot lol
can i get a little help? im kinda struggling with 1 thing with the particle system
(trigger warning, my friends is laughing hard asf, and sounds like a chimp straight out of the zoo)
the issue is that it somehow does more than 1 cycle and more than 3-5 particles per cycle
(had to do a zip since it was to big for uploading it to discord)
Hey so my idea worked, but now it (the score counter and other stuff) seems to be duplicating
Eh its fine for now
I need to go to bed any way 
I can always work tmro
Use https://streamable.com/ to upload share videos if they are too long.
Hello, if I want to make a multiplayer FPS game, what is the best method to use for bullet ? Physics bullet or simple raycast ?
These are different approaches design-wise. So you need to decide which one you want.
Watch "ivanel2 - SampleScene - Windows, Mac, Linux - Unity 2022.3.13f1_ DX11 2024-03-09 08-04-41" on Streamable.
Physics bullet is gonna be harder to implement though, especially in a multiplayer context.
Physics bullet if your game is very low poly and has low resolution textures, otherwise use raycasts
It's hard to say, but I guess it's because you have a burst interval of .01, so it keeps on spawning 100 bursts per second.
so i should change it to 0 or 1?
haven't opened VSCode in a while for my project, got this after updating, should i regenerate my project file or "upgrade" my project to an "SDK-style" project?
Depending on what you want, yeah
i want it to just happen once
Try following the !ide config guides:
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
Then set it to 0. And also make sure that the particle system is not looping in the main module.
Also, this is really not a code question.
srry it was before because i was trying to call it with code and one thing lead to another and i forgot to change places
thanks, tho i found that regenerating my project files fixed it. Still thank you for your time!
Ok, so this is kinda of a way too generic question, but when should I use events instead of, you know, have it build in the object script itself?
Cause I have been looking about it and I am not still sure what the advantage is supposed to be
What do you mean?
For what I know is meant to be sorta of listener of something happening and then sending like a pulse to several other scripts subscribed to it to do something in response, but I don't quite see the advantage of that over just, having the scripts be the listener themselves
How would you make the scripts "the listeners themselves"?
I mean, I guess performance, but like how many simultaneous scripts you must have for this to be even noticiable?
Just write the trigger you have on the event system on the scripts that are suscribed to it?
With events you can get notified when something changes, instead of having to continuously ask if it changed
Uuuuh can you clarify?
How so? Like they don't check every frame to see if the thing they are checking for is changed?
Yeah
I also dont get this
Ok good, I was worried.
I am figuring "check for button to be pressed to open several doors"; you could have an event listener checking for the button press and tell all doors to open when is pressed, or you could have each door trigger when that specific button is pressed instead of using a event listener as intermediary
How much less is efficient is this supposed to be?
And how would these doors check if the button has been pressed?
Wait
When you say "EventListener", which implementation are you referring to?
A UnityEvent?
A C# event?
I mean, just in the same you would do in the event listener? With collision detection and a boolean I guess
OnTrigger/CollisionEnter?
I mean, I though they were the same, you are getting me more confused now
Why use collision detection etc. when you can just make the doors listen to the button's C# event?
For that door example I would literally just make some DoorManager script, give it a reference to all appropriate doors, have a method called "OpenAllDoors" and call that method through the Unity Button's OnClick event.
Shouldn't the button event have a collision detection anyways to, you know have something to listen to?
Is this a UI Button >_>
Like when it is physically pressed? Sure, but not related to events
Or some "button" gameobject in the real world?
I am not refering like an UI button with an "onclick" method, I was thinking more of something a puzzle game, portal-like, where it check if something is on top
Sure, you probably want to detect the button press by physics or something.
But its not related to how you make the doors know that the button was pressed
Alright. Point is I would 100% make it so all your buttons or interactables or whatever work through events. You could end up with tones of buttons/levers/pressure pads that do all kinds of things when their conditions are met.
Use a UnityEvent specifically, and hook it up in the inspector.
Ok, so what I am saying, is I guess you do gain significant performance if there is many things that you want to trigger when X happens, but in an somewhat contained scene, do you really gain much by having events instead of having every "doorScript" check for the "buttonScript" to see if they should be oppening instead?
Cause is seems kinda the same but with more steps
Ah, okay. So you're suggesting the doors check the state of the button every frame?
That would work. It just doesnt scale very well. For a small project its fine
Getting used to events is good tho
Yeah, pretty much, I am actually wondering now why do events only check for changes but normal scripts cannot do that
Ok now I understand. Like Osmal said it doesn't scale well. Lots of doors checking the state of the button every frame is sort of a waste. It's really not an fps problem until you get literally hundreds of doors, but the main issue with that set up, in my opinion, is structural.
A doors job is just to block the player, to open and close. How and when it opens/closes is irrelevant and not its job to figure out. Like I said before imagine if you instead wanted a lever to open the door. How are the doors going to know they need to check the state of a lever instead of a button? It's much better to flip it around. It's the button or levers job to notify the door that it should open/close.
I actually did something similar in a small project before, I just had all stuff than could trigger other stuff have a parent class with a "isTriggered" bool and just assign that to the thing I want to be triggered when the they are
But, yeah, I must say that project was kinda of a mess structurally
Let me get a code example for you. 1 sec.
Put this on your button.
public class Interactable : MonoBehaviour
{
[SerializeField] UnityEvent onInteract;
[SerializeField] UnityEvent stopInteract;
public void Interact()
{
onInteract.Invoke();
}
public void StopInteract()
{
stopInteract.Invoke();
}
}
And this for your door.
public class Door : MonoBehaviour
{
public void Open()
{
//Handle your door opening logic.
}
public void Close()
{
//Handle your door closing logic.
}
}
On the inspector of the Interactable you'll see slots.
Slot in the Door object, and call the appropriate functions. @frigid sequoia
Whatever triggers the button should just do a GetComponent for Interactable and then call one of those two functions.
Now anything in your game can work with any interactable if they work through that Interactable component.
Indeed. My main issue with raycast solution is that the ray only seems to use one vector to calculate if it hits anything, it's not a line like an actual bullet. I'd like to use a 3rd person view meaning the check would need to cast from the weapon to the middle of the screen.
Is it possible to do with a raycast ?
It's not a line, but a ray. A line can fit in a ray. You can also do a linecast if you want. I'm not really sure what the problem is..?
Ok nevermind my question, I found a tutorial online, cool.
Maybe he's talking about fall off?
Like gravity pulling it down over time?
That wouldn't be a line either. That would be an arc
No, I'm talking about line of sight. Most tutorial about raycast will jsut tell you to raycast using the center of the camera. This might work in a FPS because the gun would be conveniently placed in the center too.
You can raycast from wherever you want.
But with 3rd person view, the bullet is not shot from the center of the screen, so the raycast need to be calculated differently. And most tutorial don't explain that
Maybe look for tutorials that cover 3rd person shooting then.🤷♂️
That's what I'm learning about now
Yes indeed 😉
Looking one right now, thanks
You can define whatever start point you want for a raycast. If you're worried about the fact that the position of the muzzle doesn't match the sight line of the player...
ya all FPS need to deal with that
definitely some solved solution out there
No wait you want a 3rd person.
Yup indeed. This will solve my issue. I was using physics bullet but I'm worried with many players, it might slow down the server and moreover, the hit collision is a bit quirky when bullets go too fast.
Ya. "Hit-scan" weapons are basically raycasts.
Rockets and other slow moving projectiles are usually actual physics objects.
This is called hit-scan weapons ? I didn't know
Yes, for rockets and projectiles, that would use real bullets indeed but that won't be hundreds of bullets flying around with such weapons ahha
Well that's more of a Shooter game term. Hitscan weapons usually mean there's no travel time with the bullet, which is what you'd get out of a raycast.
...the reference is null...
...the reference is null..!
...THE GODDAM REFERENCE IS NULL!!!
Make it not null.
Oh, thanks for the explanation, I didn't know about this.
Hitscan in video game design, most commonly in first-person shooters, is a type of hit registration system that determines whether an object has been hit or not simply by scanning if the item used was aimed directly at its target and then applies the effects of the item (usually damage) instantly. A weapon, for example, does not launch a project...
An interesting read. The part about adding a delay to make it more credible is quite smart, didn't think about that.
No problem. Hitscan is a good approximation because bullets travel ridiculously fast, usually hundreds of meters a second.
A real bullet would likely travel the length of the entire map in a handful of frames.
So fuck it.
Shits too complicated to actually simulate.
Let's shoot lasers instead.
Indeed lol
I'll jsut have to look for a proper trail tutorial since i'd like to simulate a nice bullet trail like my current physics bullets leave behind.
Ok, now I get it, so you are not procesing anything at runtime, you are just invoking the methods from runtime when needed, yeah, that makes so much more sense to me now, thxs for making it more visual
basically just render a line
Ya pretty much. Just to help with your vocab a bit, "at runtime" just means when the program is running.
But a simple line between point A and B would not really show the bulelt travelling, would it ?
Events are still executed "during runtime".
It would be a laser but I'd prefer a bullet representation
We're just not updating them "every frame".
I mean, you could kinda call "runtime" when the whole game is running, since it is the main thing, but yeah I got what you say
Just one more example to really hammer home the advantages of events. Imagine a PlayerHealth script and a PlayerHealthUI script. How does the UI know to update the health? Sure, you could give PlayerHealth a reference to PlayerHealthUI, and update it whenever the health is changed, or make PlayerHealthUI check the state of PlayerHealth every frame.
Or.
You give PlayerHealth a event called "OnHealthUpdate" which takes in an int/float.
and call a method on PlayerHealthUI to update the visual.
I am doing just rn. When the player takes damage, the health value changes, and the UI get updated, but at any other time is that method used in any way
Now PlayerHealth has no idea the UI exists, and PlayerHealthUI has no idea who it's getting its info from.
So I am guessing is kinda the same
And this is nice because you can easily cause more things to happen when the player takes damage.
Screen shake?
Blood splatter?
Scream noise?
Just slap it all into that health update event.
Nearby enemies can even subscribe to that event and increase their aggression when the player gets hurt.
Creating some type of swarming behaviour.
Point is, PlayerHealth as a class doesn't care/know about any of this.
It's just screaming "hey this value got updated', and whoever cares about that can do whatever in response.
I am just kinda having all that on the playerController takeDamage method, that's seems more organized though. Mine is kinda bloated
As you learn, you'll eventually start making smaller and smaller classes.
Each handling one thing, but working together.
https://www.youtube.com/watch?v=7zfnxcKFaJg hihi
I managed to make a code that follows holding directly from the cursor (not directly, it is intersecting but is a different story, still directly from the middle part form raycast), now I am not sure how to make something similar to this video, i have a feeling it is transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, ishouldputthecodehere); at the end, but instead of rotation, it is position i think, and 'ishouldputhtecodehere' says how fast or slow it could go there, maybe this is the one i need to change to copy the one in the vid? or more complicated?
Been wondering how to pick up items and stuff like you could back in Oblivion? Well here you go. Quick tutorial of how to lift items, dual wield weapons and magic, and also how to dash. And it seems I glitch the game a little showing it off. To much power!!!
Leave likes!!! It helps tons!!
Join The Cinnamontoastken Family - http://bit.ly/sr...
i kind of want to put weight as well and mouse speed to affect the object
Hey, so far I have 2 scenes on my project and I manage to make menu so the player can go from the scene "main menu" to the "level1" using "SceneManager.LoadScene(_mainMenu);". I put the same postprocessing on both scene but when I play and load a new scene, the postprocessing and light effect seems to disappear
My bad, postproceesing seems to work, it's only about lightning, don't know why
Oh ok I think I fixed it, it needed to generate lightning in the rendering lightning settings, and it creates a file that will store the lightning information and apply it while loading new scenes
Does Destroy(this) refer to the script or the GameObject?
the component
I have a script called "HealthRegenOnCollision" that adds HealthRegeneration.cs on collision to the collider, functioning as poison, but I don't know how to prevent the object from adding more than one script so that there'd be only one poison HealthRegeneration script. The only solution I came up with is adding an if statement that prevents the object from adding the script if there's already a HealthRegeneration component. But I want both poison and health regeneration to apply.
you want to make a script, but want to say if it is poison or health?
So you do want more than one HealthRegeneration on a gameobject. But not more than one type maybe? One way to solve this is to add an ‘type’ enum to the HealthRegeneration then make sure to never add more than one type at a time (or maybe you want to reset / increase the duration of type) if you come into contact with the same source again. You could also add a ‘source’ property to HealthRegeneration and track that the same source can’t add more than one component. As you can see there are many ways to deal with this, but it does depend on the game design.
i think you could make a dictionary, or if else
but I am just a beginner, might not be the best solution

personally, I'll add public int itemType; in the health or poison thingy
I came up with a similar solution a while after placing this question here, I already have a bool to check if it's a status so in the OnCollision script I'll just only allow it to add the script if isStatus is false
Gonna tag this for the future, it might not work if I decide to implement a health regeneration status
Also, why not just use an Enum for itemType?
https://hastebin.com/share/lakogucine.csharp
I made a quick example of what I was trying to say, but I got gpt to write it for me and I haven't checked how solid it is / if it actually works.
but it might help as an example 🙂
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
In this clip, there is a bug where if I move too fast in the air. My camera does some kind of glitch, and it pushes up where I can see my body. any tips on why that is and how I can fix?
How would we know without seeing the camera controller script
https://hastebin.com/share/goyeveduke.csharp
so I have this script here
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and I have the problem where I can't call the coroutine I want inside of a coroutine
I just get An object reference is required for the non-static field, method, or property 'MonoBehaviour.StartCoroutine(IEnumerator)'
which makes 0 sense
the main issue is that this is a class inside of the main class
and that class does not derive from Monobehaviour
it makes perfect sense, your class does not derive from Monobehaviour
but I can't have it derive from monobehaviour either
so pass a monobehaviour as a parameter into a method that starts the coroutines using it
i cant really do that
idk what you mean by pass a monobehaviour as a parameter, for first
should I have a completely different script just for running a single coroutine
say you have this
class MyClass : MonoBehaviour
void StartSomething() {
burstPattern.StartSomethingElse(this);
}
and then in BurstPattern you have
void StartSomethingElse(MonoBevaviour mono) {
mono.StartCoroutine(Shotgun(10));
}
actually before I look into this
what if I do this
just creating the IEnumerator inside of Update
that makes absolutely no sense
this is confusing
so a completely new script
for that
basically 3 lines of code
any mono script will do, I mean you must be calling StartCoroutine from somewhere coz it's not in BurstPattern
my main monobehaviour/class is PatternHandler
and that tries to start WaitAfterStart ?
ig I can use that?
inside of Update, yes
so that where you need something like
burstPattern.StartSomethingElse(this);
to pass the PatternHandler as a parameter into a method on BurstPattern
Is there even a point to regions. The one video I watched was suggesting it but honestly, feels like its useless. Why not comment above the text
It can be convenient for collapsing large blocks of code in the ide but other than that, no
as someone else already said, you can't start a coroutine like this. it needs to 'belong' to a game object / monobehaviour. two easy options:
- use a static reference to start the coroutine: GameManager.instance.StartCoroutine(Shotgun(fireRateCT * i));
- make it an async function instead of a coroutine
I think I got it
Except async methods cannot call Unity api's which Shotgun is doing
internal void startWaitCoroutine(MonoBehaviour mono, float fireRate)
{
mono.StartCoroutine(Shotgun(fireRate));
}
internal IEnumerator WaitAfterStart(MonoBehaviour m)
{
yield return new WaitForSeconds(timeToStartCT);
for (int i = burstCount; i >= 0; i--)
{
startWaitCoroutine(m, fireRateCT * i);
}
}```
this is in the class which doesnt have a monobehaviour
what are you on about, yes you can
then I do this in the monobehaviour class bp.WaitAfterStart(this);
you could just have done
internal IEnumerator WaitAfterStart(MonoBehaviour mono)
{
yield return new WaitForSeconds(timeToStartCT);
for (int i = burstCount; i >= 0; i--)
{
mono.StartCoroutine(Shotgun(fireRateCT * i));
}
}
oh
lemme try that
nothing happens
and i have no clue how to even debug it
this is the full file https://hastebin.com/share/iwabihabeq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
SprayPattern rn is completely irrelevant
i have a question about making a menu where you can choose ladout is it better if i put the ladout manager on the player prefab or make a new script and just put it in my scene
not
bp.WaitAfterStart(this);
but
StartCoroutine(bp.WaitAfterStart(this));
omg im so stupid
i swear if this makes it work
it actually did
thank you!
I just need to figure out why it fired twice
I don't see how it would make sense on the player prefab at all. As far as making "a new script" actually I would expect something like a load out management system to involve dozens of scripts.
the important thing is do you understand WHY it works?
yes, I do
well
90% basically
rofl
it feels unconventional
my middle name
because if PatternHandler derives from MonoBehaviour, and BurstPattern is a class inside PatternHandler, then why doesn't BurstPattern also derive from MonoBehaviour
or at least let me use the coroutine
not the way c# works
BurstPattern does not derive from PatternHandler, it is a class private to it, that's all
yeah I get it
you could if you could make PatternHandler a Singleton then you could do
PatternHandler.instance,StartCoroutine(..);
yeah, problem is its not a singleton
okay its working flawlessly
thank you!
I had some jank going on which triggered it to fire twice but i got it
tbh I'm not a great fan of nested classes unless there is a really good design reason for them being so
idk if this counts as really good design reason
i just dont want to hardcode patterns
so this makes it very easy and fast
whether those classes are nested or not makes absolutely no difference
The only thing that's special about a nested type is that it can access the private members of its containing type.
(and that anything outside of the containing type has to refer to it as ContainingType.NestedType
ah, what is enum?
I havent tried yet 
An enum is an enumeration type. It's a type with a specific set of values.
let me give you a good example of nested class usage :-
I have a Database class which is responsible for all database access
I have a nested Interface ITable which defines the access for a database table
I have 4 nested classes each implementing ITable
Now it makes no sense for any of those classes to be used outside of the Database class because it is only within that class that they can hold relevant data
You literally enumerate all of the type's values
enum Season
{
Spring,
Summer,
Autumn,
Winter
}
ah, it is like dictionary? 
No.
To keep it short, special variable that you assign. Instead of making itemType 0, 1, 2 etc, you can make itemType equal to Heal, Damage, etc
A dictionary is a data structure, not a type.
Season is a brand new type (just like declaring a class or a struct)
Seasons are always used as an example for some reason
Seasons and colors.
aah, I need this 
Dictionary<Season, int> is a dictionary mapping Season to int
seasonDict[Season.Spring] = 123;
Season.Spring is a value of the Season type
Just like 0 is a value of the int type and "Hello!" is a value of the string type.
is like, bookpages, then dictionary is like library?
thats almost what I'm doing
technically PatternHandler is a database, and BurstPattern is an ITable, if we use your example
ok not exactly, more like BurstPattern is a class implementing an ITable but yknow
Key is like the words in the dictionary, and Value is like the definitions.
Dictionary<GameObject, float> stores a float for each GameObject key you give it
List and Dictionary are the two most common data structures I use.
Lists holds a bunch of things. Dictionaries store a value for each key.
so BurstPattern and SprayPattern would be Tables? Then it makes sense
Hi guys, I have a problem with my Saving system in Unity. When I click on Save button it should make .json file with all game data saved and when I load the game from main menu it should just load me that data but for some reason it doesnt. Here is saving script: https://hastebin.com/share/efobihiduv.csharp and here is GameState script where I save all variables: https://hastebin.com/share/riniyipemi.csharp . Also in Saving script my Debug that says "save" doesnt appear but it worked before and I havent changed anything...
"but for some reason it doesn't" is very vague
it sounds like your saving script isn't running at all if nothing is being logged
well yeah, they're tables of what "patterns" i want
Im very confused because my saving script worked 5min ago and I saved my game, then I loaded game from main menu and worked perfect, I tried again with different values(different player and cam pos and death count) I saved and loaded and then it loaded save values that I saved before. It didnt overwrite .json file and I dont know why. Then I deleted that .json file and now it wont even save nor load data...
Understood, generally for code cleanness I would put nested classes at the bottom of the enclosing class so as not to pollute the logic of that script, style police, I know, but my 2 cents
ah, is it in unity stored thingy, like in the scripts and the unity editor
like when I assign 10 as speed in script but set as 15 in unity, or diff case
oh, yeah that's valid @languid spire
oh okay, what should I do then
Ok so my current heading recently broke in my code. Basically I am trying to get a 0-360 heading where it counts up clockwise and once it hites 360 it returns to zero.
To calculate heading I use:
currentHeading = rb.rotation < 0 ? 360 + rb.rotation : rb.rotation;
but it always goes into the thousands.
not sure if it is what is causing it
or if that is the case
tho most of the logic is inside of those nested classes themselves
the only logic except those ones is just the update calling them
you still have a pretty hefty Update method which kinda gets lost in the mess
i think it isnt cause I didnt change anything inside unity inspector of game objects
void Update()
{
stunTime = EnemyStagger.StaggerInstance.stunDuration;
if (Input.GetKeyDown(KeyCode.H)) phaseNumber++;
foreach (BurstPattern bp in phases[phaseNumber].shotgunPatterns)
{
if (stunTime > 0f)
{
bp.activated = false;
bp.burstCount = bp.burstsFired;
bp.started = false;
StopAllCoroutines();
}
else bp.activated = true;
if(bp.activated && !bp.started)
{
bp.started = true;
print("Test");
StartCoroutine(bp.WaitAfterStart(this));
}
}
}```
this is essentially all my update method does rn
I just need to implement this same coroutine solution for the spraypattern too
which should be the exact same length
In C it was always declare first, use after. Luckily in C# we are not so bound to this
I also added a StopAllCoroutines() because I use recursivity in one of my corotuines
internal IEnumerator RepeatPattern(MonoBehaviour m)
{
yield return new WaitForSeconds(timeBetweenBursts + burstsFired * fireRateCT);
for (int i = burstsFired - 1; i >= 0; i--)
{
m.StartCoroutine(Shotgun(fireRateCT * i));
}
if (loopPattern) m.StartCoroutine(RepeatPattern(m));
}```
this is probably not the nicest way of doing it
especially because when a "phase" ends, all firing stops and everything
without that stopallcoroutines it just kept on adding more and more RepeatPatterns
Oh....
I'd suggest keeping a list of the relevant coroutines.
them you can just stop everything in the list
internal IEnumerator RepeatPattern(MonoBehaviour m)
{
while (loopPattern) {
yield return new WaitForSeconds(timeBetweenBursts + burstsFired * fireRateCT);
for (int i = burstsFired - 1; i >= 0; i--)
{
m.StartCoroutine(Shotgun(fireRateCT * i));
}
}
}
Would that many coroutines going off be a perfomance issue?
it should be fine
If it ever becomes a problem you can cache the WaitForSeconds
theres only one RepeatPattern coroutine going off at the same time
possibly, something for the profiller
You dont have to new it up every time you start the coroutine, slight perfomance increase in case you ever need it
problem is looppattern is a bool which is set in the inspector
its basically to see if you only want a pattern to run once, or for it to have a delay and repeat once its done
then you still have infinite loop potential
yes, thats why I used a StopAllCoroutines(); whenever the phase ends
nasty, cowards way out
ikr
I could use some bool to check if the phase is going on or not
actually
i think i have that already
oh yeah i do
whoops
Hi I am searching for some help would anyone accept to help me ?
You dont have to ask to ask. You can just state ur problem brother 🙂
yeah but it still kinda "caches" them up so ill just use StopAllCoroutines to be extra safe
Ah i remember this
it shouldnt have fired those 3 at the end
I have a question related to Zenject. I have a MonoBehaviour script and a service. Where should I implement the movement logic, and what should I do with the basic components (e.g., Rigidbody2D, etc.)? I'm not quite sure how to properly design this. Can you help me, please?
Thanks. I am doing a project for school but I don't really have the programming skills so I asked chatGPT but now I face a problem that ChatGPT doesn't help me to solve : My Coroutine never stops. I put some Debug.Log as you can see and only the "Desactivation" appears, not the "Reactivation".
Does it log AfterWaitForSeconds?
No
Deactivating a game object kills all coroutines on all MonoBehaviours attached to it.
Are you disabling a game object in DesactivateScript?
public void DesactivateScript()
{
Debug.Log("Desactivation");
peutSeDeplacer = false;
}
aw yep
I make a bool false
you deactivate it
That does not deactivate a game object.
What does the bool do?
unless you use that boolean to deactivate a game object elsewhere
Share the entire script, please. !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 also dont get why u need a coroutine to change your scene
if (peutSeDeplacer && !enDeplacement)
{
DetecterDeplacement();
}
Because my player is doing a weird thing when i change my scene. I think you would remake all my scripts but i Don't really have the time
okay
use one of these websites to share the entire script.
I don't understand this utility
go to https://gdl.space
paste your code into the site
click the save icon
copy the URL of the page (which will have changed) and paste that here
also share the script that contains this code
id guess it has to do with this
SceneChanger is probably being destroyed.
It needs to still exist after the new scene loads.
It's for another thing
StartCoroutine runs the coroutine on the object that called StartCoroutine
I can semi-understand french bbut also why tf have a function for a function that already exists
If that object is destroyed, the coroutine stops.
Oh you're probably right because the script is on an object that is on the ancient scene
thats the issue yep
it's reasonable to write a predicate, especially since the logic might become more complicated later
although it is a bit silly here
I would suggest keeping something in the DontDestroyOnLoad scene. Run the coroutine on that object instead of on SceneChanger
You could even run this on the player object...
I'd say this makes it more complicated just in itself
or have SceneChanger be in DontDestroyOnLoad
Like the SceneChanger is on the Player and it verify if the other has a tag which would activates the Scene change ?
Are there many SceneChangers in your game?
What you can do is have the SceneChanger call a method on something in DontDestroyOnLoad
And that thing then runs the coroutine
Maybe call this the "Scene Controller"
The Scene Controller would stay on all scenes and just runs coroutines ?
It would be in DontDestroyOnLoad
I'm looking for a mathematical formula for failure rate based on times fired that would be easily tweakable, thoughts?
So it would not be in a specific game scene.
Do you want failures to be completely random, or do you want them to get more likely over time?
totalOutComes/favoredOutComes?
the more shots fired the more likely, probably just a formula that gives a % chance of failure based on the amount of shots fired
oh nvm
you could just use an AnimationCurve if you want to tweak it interactively
How would I put in DontDestroyOnLoad
or some BLM system
you already use it in SceneChanger
DontDestroyOnLoad(other.gameObject);
Yes for the player doesn't get destroyed
What you could do is check if a "Scene Controller" already exists
maybe just like
shotsFired / likelynessOfFailure / 100 and then cap it
If one doesn't, create a new one from a prefab and call DontDestroyOnLoad on it
You could also do this when the game starts
divided by 100?
This would be a good place to use FindObjectOfType.
SceneController controller = FindObjectOfType<SceneController>();
if (!controller) {
controller = Instantiate(sceneControllerPrefab);
DontDestroyOnLoad(controller.gameObject);
}
controller.ChangeScene(targetScene);
idk that's how i'd get a percentage
Add a key at 0,0 and at 500,0.01
okay and the Coroutine is in this scripts ?
now you have a 1% chance of failure at 500 shots
Yes, you'd put the coroutine in the "Scene Controller" component
okay thanks i'll test that
you just need to make sure the object you run the coroutine on still exists
That's why I was thinking of just doing this
player.StartCoroutine(...)
oh
That might actually be the best way to do this
Okay
As long as the player object is never deactivated
Find the player and start a coroutine on them
StartCoroutine is a MonoBehaviour method. You can call it on any MonoBehaviour.
Sorry but what's a MonoBehaviour ?
public class SceneChanger : MonoBehaviour
It is the class you inherit from to make your own components.
a is the likeliness of failure while x is the number of attempts
y is the chance of failure between 0 and 1 (100%, 0%)
I can't access the Coroutine which is on the player from SceneChanger
You do not have to move the method.
player.StartCoroutine(ChangeScene());
It doesn't really matter where you got the coroutine from.
It matters who you give it to with StartCoroutine
I a
I am really sorry but I don't understand how to do it I get the error "'GameObject' does not contain a definition for 'StartCoroutine' and no accessible extension method 'StartCoroutine' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)"
I am trying to rotate a vector to match the gameobject's rotation. It should be Vector3 posOneAhead = transform.rotation*Vector3.up; but I get a compile error that I cannot multiply Quaternion with a Vector3.
that should actually work just fine. However you could also just do transform.up to get that same result.
I suspect your error is coming from a different line of code.
Not sure what you are asking to fix, but also this isn't a code question.
I guess you want 'transform.position' not 'transform.rotation'?
I want transform.position + transform.rotation*Vector3.up
Basically, one step ahead of what it's facing now.
posOneAhead = transfrom.position + transfrom.forward;
transform.TransformPoint(Vector3.up)
or what simex wrote
And how do I get 90 degree to the left?
-transform.right
or TransformPoint(Vector3.left)
new position = position + forward * speed
@swift crag Are you here ?
-transform.right would be the left direction
Do you have a "Player" class?
A component you put on the player object.
Hey, i have a little question, I want to make a Ball Game and every ball should have its own float variable, but just use one script on a Prefab. And if i put the Variable up, all Balls get this Number, but i want that just one specific one has it. Can someone help at this?
Show me the inspector for the player object.
Show your code. In normal circumstances a variable on the script is unique to that one object.
you did something wrong
Any of your components would work.
also, if you don't want to run the coroutine on the player, you can just use DontDestroyOnLoad to prevent SceneChanger from being destroyed
and have it destroy itself when it's done
this script doesn't look like it lives on each ball
this looks like a singleton
But why do I get an error ?
Because GameObject does not have a StartCoroutine method
If it is on each ball it doesn't matter much because if your other code is using instance to access it, it's all only accessing that ONE instance.
Like this?
transform.position = new Vector2(dashPower, 0);
Only classes that inherit from MonoBehaviour have that method.
So i need to try the second option ? This one ?
It sounds simpler to me.
But the GameObject will stay between the scenes for some time
Oh okay, i understand, thank you, so i have to change the instance, and retrieve the value somehow different
If you explain what you're trying to accomplish maybe I can suggest a better solution.
How and when are you trying to read the Value number and what are you trying to do with it?
I have been locked not knowing how to write on a method for a while. How do I... increase a value over time given the time and the value I want to increase but do it on a exponential rate?
Well "exponential" is pretty vague but generally just means the rate of increase is itself increasing
so something like:
float rateOfRateIncrease = 1; // acceleration in units/s^2
float rate = 0; // rate of increase in units/s
float currentValue = 0;
void FixedUpdate() {
currentValue += Time.deltaTime * rate;
rate += Time.deltaTime * rateOfRateIncrease;
}```
Thanks Fen it was the problem you were thinking but i, now, have another problem
value += increment;
increment *= increment;
An exponential function's rate of change is proportional to its current value.
https://gdl.space/iconamidaz.cpp I changed my script and now I have this problem : "NullReferenceException: Object reference not set to an instance of an object
SceneChanger+<AttendreChangementScene>d__5.MoveNext () (at Assets/Scripts/SceneChanger.cs:53)"
then:
void FixedUpdate() {
float rate = someRatio * currentValue;
currentValue += rate * Time.deltaTime;
}```
maynn how do i make my character damage the enemy
lemme show u the code
this is my enemy attack script
https://gdl.space/penowabiga.cs
works fine when the player is in zone it gets damaged
https://gdl.space/dafobaloco.cs this is the script for patrol behaviour
this is within the player controlller script
i literally dont undestand why it doesnt work
What debugging steps have you taken?
Have you added any logs to make sure any of the code is actually running?
havent added logs no
that's step 1
add logs in OnTriggerEnter. Log the object you collided with. log its tag. Log whether it has the Health component on it. etc.
To be more especfic I want to do typical thing where score increases by X but it doesn't happen instantly, but more like... it goes really fast at the beggining and slows down at the end of the transition. So.... it would be the reversal of your solution?
Every time the Ball touches a Wall the Value gets one up. And after a Time the Value gets addet to another Variable
so this
player.GetComponent<DeplacementPersonnage>().ReactivateScript();
which means that player does not have a component DeplacementPersonnage. Assuming player is not null
How do you get a rigidbody Velocity to convert to a Vector3 slerp. I need the Vector2 velocity value to become its 3rd argument
what do you mean by "after a time the value gets added to another variable"?
I don't understand this sentence. What are you trying to accomplish?
Sounds like you just want Mathf.SmoothDamp
Yes thanks I thought of the same thing
or perhaps DoTween.DoMove but with an easing function like this https://easings.net/#easeOutExpo
So my goal is to make the Main Camera follow my player object. While I got the player down it is struggling to keep up with its velocity, so I wanted to make it follow the player by matching the players velocity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Vector2 FollowSpeed;
public AdvancedPlayerMovement status;
public Transform target;
// Update is called once per frame
void Update()
{
FollowSpeed = status.currentVelocityRaw;
Debug.Log(FollowSpeed);
Vector3 newPos = new(target.position.x, target.position.y, -10f);
transform.position = Vector3.Slerp(transform.position, newPos, FollowSpeed*Time.deltaTime);
}
}
Slerp is for direction vectors
Okay Fen I am really sorry for the waste of time but it didn't fixed my problem to have a coroutine...
not position vectors
Yes, SmoothDamp would accomplish that. SmoothDamp approaches a value without overshooting it, and it moves faster when it's further away from the value
Show me your new code.
correct, but what slerp is doing for this is moving the camera in the direction of the player
TO be perfectly honest you should really just use Cinemachine - which has damping features.
But the Coroutine activates ect it's not the problem. My Player does the weird thing anyway
it's inappropraite. Lerp would be more appropriate but still not totally appropriate
Vector3.SmoothDamp would be good
Cinemachine 👀
but yeah - use cinemachine
Cinemachine solves most of your camera problems for you.
https://gdl.space/adivojataf.cpp Here my code if you want
you will get this behavior in a few clicks with cinemachine
roger
This sounds like exactly what I am looking for, I am gonna try to mess with that thxs
I have a question - I've tried to hardcode a value into a script for turnSpeed, but it's not updating outside of the script. Is it because it's set to public and you can edit it from the gui?
yes
The one downside of youtube tutorials, they don't provide alternatives
@swift crag Could I add you, I could show you what the weird thing my player does
No. Just describe the problem or record a video.
okay
yes it's serialized so it's saved to the scene or prefab file now and has to be modified there.
If you want to hardcode it, don't serialize it
Ok. Are there any security issues with making variables public/is it a bad practice? Or will whatever my scene settings are set to be the ones pushed out when you compile and publish a game?
I've always been taught to set variables to private and put a setter/getter to change the variable
Public variables are bad practice.
Yes the settings in the scene will go out in the build
@swift crag My game is not beautiful I know but the problem is happening the second time i take a scene changer
Is the alternative what I've been taught for general programming up to this point? Just make a getter/setter and call it from the other scripts?
Yes, use accessors as needed
okay, and what is the problem?
It's good to default to private but not because of 'security' -- assume that whoever has your game also has access to anything you ship with your game
yes, it's a design issue, not a security issue
The movement of the playe
You will need to explain.
Ok, thanks for your help @wintry quarry @swift crag
The first time it spawns normally but the second time after spawning it moves to its ancient position and I don't understand why
I didn't ask it to move
Maybe it's always putting you where you were supposed to appear in the old scene
like you're positioning the player before you change scenes
Okay but if in my scripts i put the ChangeScene before the player positioning it doesn't change anything
What should I do ?
New to the convo, but I believe Fen means that you have something like this pseudo code:
SceneManager.LoadScene(...)
MovePlayer(...)
Check if the behaviour you happen after loading the scene is in a Start method
You want my script ?
Sure
OK, lets look at this
private void ChangerScene()
{
// Charge la scène
SceneManager.LoadScene(Scene);
StartCoroutine(AttendreChangementScene());
}
what do you expect of the game object running this script when that code executes?
It loads the scene
and then?
And the start the coroutine
Why is the code in French
Because it's my bad sorry
but it does not exist anymore because you've just loaded a new scene
No i changed this so the gameObject stay in the scene
but it doesn't fix the problem
so this is on a DDOL object?
DDOL ?
Dont Destroy On Load
Ok, and when you destroy a game object you also destroy it's coroutines
- You have made it DDOL on TriggerEnter, if colliding with a player. Usually this is done in Awake
- Why do you need to DDOL your objects in the first place? Why don't you perform whatever
AttendreChangementScenedoes inStart?
yes but the coroutines have already been done
unlikely
my player controller script - https://gdl.space/uqenesahul.cs
health script - https://gdl.space/ofugokivap.cs
enemy attack script - https://gdl.space/fapijutoli.cs
enemy patrol script - https://gdl.space/udovokeweh.cs
can someone help me please, Im creating a 2d platformer game and I need to be able to attack the enemy, so far my attack animation just plays but doesnt actually deal damage what do i have to do to make it deal damage.
the Destroy call is at the end of the coroutine.
my understanding is that the coroutine is completing properly
the player is just appearing in the wrong place?
Fen would explain better i don't know
yes but it doesn't always happen
the point is to make the SceneChanger survive the scene loading process
I originally suggested just making a SceneController that is created once and handles all of the scene changes
that makes sense
Perhaps you just have the wrong spawn point in one of your scenes.
easiest way is to
- have an empty gameobject
- parent it to the player
- stick a boxcollider2d on it and make it as big as you want it
- make sure its a trigger
- give it a tag like "PlayerHitbox" (doesnt matter much)
- have the enemy do something when they collide with a trigger that has the "PlayerHitbox" tag
- use a script to activate and deactivate that hitbox/gameobject whenever the animation plays
Oh it's used to load another scene? I thought it reloaded the current scene
I can give you the script but the spawn point is the position of the exit point
Are you sure your box cast is working properly
https://gdl.space/nakefocizu.cs Look at ReinitialiserPosition()
Exactly
It is used to reload the scene?
No to change the scene
empty gameobject withinthis ?
to load another one
Okay, yes then you do need DDOL
yea
You want to keep the scene changer, and something else?
this is 3d but its the same idea
yes but it doesn't fix my problem
I use this one for parrying projectiles
My problem is this
projectiles have a check in them, where if they touch an object with the "Shield" tag, they get parried
To be honest I still don't understand the problem. If you want the scene changer to remain, you use DDOL in Awake. Whatever you want to happen after the scene loads, you put in a Start method.
My problem is the player moving to its ancient poisition when i change the scene
So where do you set the position after loading the new scene
how do i make it so at this exact frame only it deals damage
https://gdl.space/nakefocizu.cs Look at ReinitialiserPosition()
The Ball falls down and hits Walls. Everytime the Ball hits the Wall, the variable should add 1 and save it, like a cache. When it is on the Ground the Cache should add to a Money System, which i already have. But if i spawn 2 Balls the Value gets reset
You can execute an event at that position in the animator
What calls ReinitialiserPosition
it's depending on the position of the exit i took
crappy AI code, again
https://gdl.space/munajoqege.cpp last line of the OnTriggerEnter2d
what do you use for starting the animation
the players idle animation
Yes I know but i really wanted to make a game and It worked since there
if thats what u mean
Okay this is way too much code I don't even understand the language of, so basically I would do this:
- You want something to remain after loading, you use DDOL on Awake
- Whatever exit you take stores whatever variable you need in the DDOL object
- Unity's Start method is called when the scene reloads
- You use the variable you set to position the player wherever you like
also your enemy script here already has damaging implemented
it just uses Raycasts
If this doesn't help you, you should rely less on AI and learn C# and Unity fundamentals
yes my enemy can damage me but the problemn is i wnat to be able to damage it aswell
i just dont know how to implement it
I know I should do it but now I don't really have the time
basically it draws a line from the enemy forward, and checks if the line touches the player
The problem is that the AI knows nothing about coding and therefore nothing about floating point precision, you should do
well u have the tools
If you don't have the time to learn, you definitely don't have the time to make an entire game
howd you add the enemy attack script if you cant add the player attack script tho
not what I meant
whats telling your character to start the attack animation
which part of the code
We don't have the time to help you with AI-generated code.
But the animation works right?
yep
on that same place you can activate the damage hitbox
you can serialize it as gameobject and use *gameobjectname*.SetActive(true)
So what happens afterwards and what is supposed to happen?
if the enemy is within the sword hitbox, it should deduct x amount of enemy HP
I don't want to make an entire game it's just a simple game for a school project it's not that i don't have the time to learn it's tha I don't have the time to learn as I need to finish the prototype in 2 days
Okay sorry for wasting your time i'll search by myself
If you don't have time, why should we waste ours on you?
Because you know how to code and I don't
this is even worse; the whole point of a school project is to learn
I'm trying to explain to him how he should approach the problem instead of spoonfeeding the code
rn he has nothing for attacking
wrong answer
you assume we know how to code lol
or that chatgpt knows how to code
it just fetches information from the internet
serialize the sword hitbox?
Can you post the code that checks if the enemy hits the sword hitbox?
u know how u can type [SerializeField] GameObject *gameobjectname*; to serialize set what it is in the inspector
do that with the hitbox
he did
Ah gotcha
Just joined the convo ^^
the enemy uses a raycast
alr, within this method im assuming^
all good :)
well thats a monobehaviour/script not a method, but yea
oh okay
So nobody wants or know how to solve my problem ?
"dont have time to learn"
why should we bother if all this is in passing
The problem is you wanting to code a video game without knowing how to code
even worse, its for school
they apparently don't want to do their own school work
should it be like this or like that
I want to implement a snap-to function where another game object gets snapped into a grid and then glued to another (FixedJoint2D). In the OnCollision2d function, I update the position of the transform and then immediately add the FixedJoint2D. It seems that I have to give the gameObject one more frame to update before adding the FixedJoint. How can I do that?
You cannot serilize local var in the inspector
It's not that I don't know how to code I know some basics just not for C# In Unity and for bugs I don't know where it comes from some code of theses cripts are made by myself
sounds like a bunch of excuses to me
I just wanted help by someone who knows more than me
this is why AI generated code is infamous.
Sure, it can make some things faster, but it will not teach you anything just copy pasting code
On n'est jamais si bien servi que par soi-même, friend
Then why code your game in C# and Unity in the first place? I'm so confused
Because it's the thing i started to learn
with Unity Learn
you serialize at the start of the class
yep did that now
goodgood
So you do want to learn. Then learn, that's what I said ten minutes ago. It's no good trying to get us to magically get your AI code to work. If you truly want to learn, go to YouTube and learn. I'm sure there are great materials pinned somewhere here as well
should the code for the player attack be something similar to this
That's the last I'll say in regards to that
nothing you sent was part of any unity learn courses
if you want to. Personally I suggested a simpler solution, but its not like the one u have
that one draws a Square in front of the enemy, and if it finds the player inside of it, it tells it to get hit
its not great from what I can tell, based off of the fact that it'll deal damage to the player even if the square hits a wall or the ground
actually not even that, but if it hits a wall or the ground you'll get an error in the console
it doesnt check if it hit the player, it checks if it hit anything
I am wrong okay, i maybe shouldn't have asked ai to do it but when I came here to ask questions it wasn't for the firt problem i faced. I solved other problems by myself and ChatGPT was not helpful for everything. I came here after hours of thinking and searching but nothing worked
ok so what do you hope to accomplish with code you sent ? and how's that related to Unity Learn or your um School assignment?
A further improvement would be to use events. When you detect the collision the event is fired. That way the script doesn't even need to know about the other script. Plus, you can use it as a general component-based system, which is great for reusability and you can even edit it in the inspector
isn't this something that should be in Start or serialized?
not for a raycast hit
oh I think I get it yeah
but itd be simpler to check if the touched object is the player or not, if it is, return true, else return false
o well
I think for now i;ll keep it hjow it is
it wouldnt take much to fix it
but sure I suppose
tho for player attacking id suggest using the trick I said above
First you need to know that I didn't have to make a game it could be anything that people would see to sensibilize them to something in link with food/health. I chose to make a game because It's what I want since i am a child and I thought that i could do it with the help of an AI it wouldn't be that difficult. And it is not my only problem is this one otherwise I would probably have finished.
this one??
yeah
Wrong answer sorry
well because it's for school makes it worse imo, because that's means that you have the resource of an entire university as well as AI and community help behind you. yet, you still didn't pay enough attention in class, ask fellow students, or the professor for help. and now you want us to fix AI code you don't understand
Well now did you realize that coding isn't just a "quick" thing ?
Hey lads, so im trying to spawn a bunch of rigidbodies ontop of eachother in a circle radius and have them push out of each other, is there a way to get rid of these overlaps someway through settings or would i be better off coding it? 
qucik
It's not an university and I don't have the ressources
that has nothing to do with it honestly
I'm still in high school, they dont teach us jack shit
yet u can still learn
sounds like you need a simpler project
I knew that and it's not a problem for me my problem is that I don't understand how to solve lmy problem
im saying this as an above average student at an elite school btw
its easy to say this when u dont even pay attention to the lectures
You said it yourself, you have severely underestimated the amount of work making video games entails. Choose something else for your project
learning to solve problems IS game development lol
My game is proably the simpliest
i still dont get wtf hes trying to do
Yes and doesn't it the right place to solve my problem I don't understand ?
america or uk high school?
better, romania
oof
isn't it*
What is a good way to make a rigid connection between two gameobjects that also transfers rotation? Using FixedJoint2D is ok, but it doesn't transfer rotation to the other gameobject.
uk teaching for computer science at least before university is really bad
yes but when you actually wrote the code and have an idea or two where its broken. We cannot help with broken code written by a SPAM generator , I mean AI
the problem is that the source of your problem is not yourself
youd at least have an idea what the code does if you wrote it yourself
it wouldd literally go over your head anything we try to fix
As a teacher myself, i would never ever teach Unity in CS haha. Why should your teachers teach you Unity?
for example.. Comparing floats with == will never yeild a good result
floats are not precise
therefore are diffcult to get a == to work
all those clearly wasnt explained by spambot :
wdym Unity in CS?
also I didn't say that they should, I just said that they don't even teach the things we're meant to be taught properly
I understand what it does just the movement of the player with the math calcul okay I don't understand everything
isnt your problem with like scene loading or smth
No
also what math
Oh sorry I interpreted that "they don't teach us" as such
Mathf.RoundToInt
at least ceil/floor it yea
or just use Mathf.Approximately or >= | <=
It's a part of the problem but it comes from the player spawning
// Prints 10
Debug.Log(Mathf.RoundToInt(10.0f));
// Prints 10
Debug.Log(Mathf.RoundToInt(10.2f));
// Prints 11
Debug.Log(Mathf.RoundToInt(10.7f));
// Prints 10
Debug.Log(Mathf.RoundToInt(10.5f));
// Prints 12
Debug.Log(Mathf.RoundToInt(11.5f));
Now we're back to mouth feeding haha
Thanks
i think the IDE also tells u in a nutshell what some functions and such do
he just asked about Mathf.RoundToInt so I sent Mathf.RoundToInt
they have no idea what they want
You're talking to me ?
half u, half navarone
I think my problem is that the player has not finish its movement when it collides the Scene changer so the scene is changed but the player still move from where it spwaned to where it should moved
well no they still teach us some interesting stuff
tho I have to go to tournaments and such to actually get to be taught the "not braindead" stuff
like this is the first time I actually got a bit stuck on a lecture in informatics
there's also Backtracking which fucks with my brain
its a simple concept I just can't visualize it in code
where is the oriignal question
Far
you probably know you have to understand recursive first
public dfs(State state)
```what you have now, and what you can do next
wait are u telling me or
I used transform.setParent(go.transform), but the two rigidbodies still behave independently. Is there something else I have to set to then make both behave in sync?
yes
ah ok
whats dfs first things first
I know what recursivity means
I've been using it for a while now and I got comfortable with it
And between the original question and now Fen helped me and I understood the coroutine wouldn't solve my issue
also I'm doing stuff in c++ so I'm not gonna get much into this topic
it was more of a thing to mention than an actual relevant issue
also you need at least a configured IDE
depth first search, since backtracking is travelling on the recursive tree
internal IEnumerator RepeatPattern(MonoBehaviour m)
{
yield return new WaitForSeconds(timeBetweenBursts + burstsFired * fireRateCT);
for (int i = burstsFired - 1; i >= 0; i--)
{
m.StartCoroutine(Shotgun(fireRateCT * i));
}
if (loopPattern && activated) m.StartCoroutine(RepeatPattern(m));```
I actually used recursitivity today, right here, so yknow
maybe a fixed joint?
I use Visual Studio
I tried FixedJoint2D, but it gives me weird behaviour.
I can see that.. It's not configured though
oh yeah, basically going forward until you meet a stop condition, then slowly going back into each rec branch
How to configure then ?
!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
Thanks
rn im looking into permuations without the formula
with divide et impera
private static void permute(String str, int l, int r)
{
if (l == r)
Console.WriteLine(str);
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
} ```
this is the method I see for it pretty often
It's configured now
strings have length so the r parameter is redundant, just check if l>=.length
"a bit" out of topic
show
its divide et impera
oh wait
nvm yea ur right about that
that code is from geeksforgeeks
just wanted to show an example
ill try smth like "all paths from top left to bottom right in a 2d matrix"
i don't know what you want to see but
not divide and conquer
the all paths problem is divide and conquer and can be solved by dp. btw the topic should end right now,, not related to unity anymore
ok now its actually useful editor
you have a compiler error
Oh Thanks that's why i din't had the colors...
right
yeah I realized in a sec
yeah true that, i think ill try. also yeah lets end it
Where ?
you can click here now it will show you where is the error
it was a semilicon if it's the right name ';' this thing missing
I don't have anymore
hello there, donno if i should ask this here or otherwhere, but here's my question
im animating a gameobject with a position animation, but even when the animation is not playing, the gameobject (player) cant move through inputs with rb, is there anyway to prevent that?
The animator will control every property that's animated by any state.
Maybe this would be a place to use root motion.
It pushes the animator's transform around instead of directly controlling it, basically
oh nice
I have not tried using this with generic animations before, though. Only with humanoid ones
But it sounds like the process is roughly the same either way
gotcha, i'll give it a try, tnks
alternatively, turning off the animator should make it give up its control
I want to say it will, at least...
meh, i would prefer to make the movement manually with scripts or other way
but i think root motion will work
is the animation meant to actually be used to move around the world?
or is it just there to make your character wiggle around
nop
Okay, then there's a much simpler fix
Parent the animated object to an empty
- Player
- Visual
just like a little effect when swinging a sword
but this wont let me move the collider, will it?
the player collider
Put the player collider on the Player object
(and the character controller / rigidbody)
where men fall
Can we avoid GetComponent's Garbage(40B)?
Serialize it in the inspector?
holy fck what are u optimizing lol
I use TryGetComponent which doesnt allocate when not found but idk if that would help here at all
I hate those little garbages :d
Thank you!
it has like 0 effect? 40 bytes?
Yep almost zero 
is that like a youtube challenge
yes -- GetComponent doesn't actually return null when it can't find anything
it gives you an invalid unity object
actually, does it even produce garbage when it succeeds?
Yes
yea thats wat im confused on (i havent tested profiled this myself)
I did it for you, it does
i recall also reading that the in-editor behavior is different than it does in build,
I could be wrong though. It was a while back
Oh you may be right. I didn't test in build
Hi it's me again sorry for before and thanks at everyone who tried to help me I understood my mistakes and I won't use AI again. I'm here because I want to make a PNJ ask questions an let the player answer. At the end of the questions, the PNJ make a review of what is good or not according to the player answers. I'd be thankful for any help.
PNJ?
You would need to learn strings and maybe dictionary
and how to create a c# object
probably need arrays too
Hum okay thanks
personnel non-jeuer or smth
personnage non-joueur yes
right mb lol
np
review of what is good or not according to the player answers
wdym here
checking the answers against the questions
Hum I can explain but I found a video after posting this message that explains what I need sorry it's mb
so like
What's 1 + 2
a. 3
b. 5
c. 9
?
yes they would store all the answers then check them
It's because it's a quizz based on the health of the player
So it gives advices based on the answers of the players
yeahh I get it
int whatAmI = 9 / 2
correct
in python its even more fucked tho
Uh becareful i got banned 10 mins while saying rude words to none by unity bot
uh oh potty mouth
What would be the easiest way to make a super simple system of 3 hearts. Something where I could easily add and remove hearts. The old way I used to do it was a hardcoded system, having each heart be its own GameObject, but that system really sucks.
just use an Int lol
depends on how severe it is i believe
int hearts
for UI just use an Image component inside a horizontal stack
There's a reason I'm in #💻┃code-beginner lmao. Still learning
An int for the number of hearts and a list to keep track of instantiated prefabs to display them
fair enough
the basic types are the best to learn first and foremost
Ah so, Instantiate heart objects in a row with a set distance between them. When the play loses health remove one?
I'm aware of the basics of programming. Just didn't know how I'd use an int to display the different amounts of hearts.
Yes more or less.
But yeah use the UI tools
I'll check them out
You don't need to manually position them
Yeah that'd make life easier
I'll checkout the documentation and come back if I have any questions
oh right, so you would basically keep an array to track the hearts
why does this coroutine keep updating without stopping? void Start()
{
StartCoroutine("FindTargetsWithDelay", visionCheckFrequency);
}
IEnumerator FindTargetsWithDelay(float delay)
{
while (true)
{
yield return new WaitForSeconds(delay);
FindEnemy();
}
}
Is there something equivalent to "Awake" that I can call for inactive components?
just call the method directly
{
StartCoroutine("FindTargetsWithDelay", visionCheckFrequency);
}
IEnumerator FindTargetsWithDelay(float delay)
{
while (true)
{
yield return new WaitForSeconds(delay);
FindEnemy();
}
}```
why does this coroutine keep updating without stopping?
yes, you can just do this:
StartCoroutine(FindTargetsWithDelay(visionCheckFrequency));
You can call functions on script that is on disabled object, as long as you have the reference stored @wind raptor
I would check the value of visionCheckFrequency
If it's serialized (i.e. not private), look in the inspector
it does what i want but i just want to understand y
because you put inside of it an infinite loop
the while true?
ye
while (true)
🤷♂️
That means loop forever
i take it unity defaults to false
huh
typo
No, that would make it NEVER loop
while loops run when the condition is true
If you pass it true, the condition will always be true
Lmao yeah that makes sm more sense than the dumb solution I had come up with
thnx. iunderstand now
I think you don't even want a loop at all, right? So remove the while entirely
no worries, we learn by making mistakes. Some of us made those mistakes earlier than others 🙂
no i want the loop. Its my ai vision
I'd rather not require something else to call Awake on it if possible. This is my class.
public class PuzzleDetail : MonoBehaviour
{
public static List<PuzzleDetail> Instances { get; private set; } = new List<PuzzleDetail>();
private void Awake()
{
Instances.Add(this);
Debug.Log(gameObject.name + " puzzle detail added");
}
public void Select()
{
foreach(var p in Instances)
{
p.gameObject.SetActive(false);
}
this.gameObject.SetActive(true);
}
}
Is there not any function like Awake or Start that can automatically be called on startup?
Even if disabled/deactivated?
if you want to stop it make the coroutine bool a variable you can switch or store coroutine in variable and use StopCoroutine
Then I am confused. What was the issue in the first place?
I just wanted to know why it worked. If i understand it i can apply it
it wont call Awake you would just call an Init method..
if the object is disabled how do you expect anything from itself to run..
Yeah it's just the outside script needing to call Awake or an Init method that I was hoping to avoid.
why though its a perfectly normal pattern
I do wish you could pass arguments whilst instantiating it
Sure, I get that. I didn't know if there was some magic "AwakeEvenIfDisabled" method
C++ can do that! (it's mildly frightening)
No need any other things. Using a Singleton that has a list of objects and an awake method that calls other awake's from the list would help if it fits your case. Or literally RuntimeInitializationMethod attribute
also just to be clear you mean disabled object not script?
cause awake does run if script is disabled but object is active
Not a singleton. I have a reference to "Instances", not Instance.
GameObject is inactive
you could potentially do that, just have the object be enabled and script itself is disabled
That is what i am saying. A singleton can stay enabled and others can be disabled
ah yeah you could use the attribute
But be aware that attribute will work for static methods only
how do i fix this choppiness when it comes to this crosshair and pointing weapon
set my cam to late update
i think whats going on is the scripts fighting with unity's physics engine
You'd have to show your code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
heres the crosshair code
Something more is going on
heres the shotgun code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you have this thing as a child of the ball or something

