#💻┃code-beginner
1 messages · Page 333 of 1
Some is certainly not fine if it's not working
idk if i have trouble with it, the thing i wanted to work 4 hours ago finally works now, i can look at the rest tomorrow. its 23:47 here and i rly want to sleep since 2 hours xd
From what i can see its just a bunch of referencing errors that i will have to fix because its coded for a single variable instead of a list, nothing big.
Can i PM you in the next few days if i rly cant make it work for some reason?
Using print or Debug.Log methods
Consider pinning me in this channel. Good luck.
how?
google it
try it
find out how it works
do a couple things with it
if i dont fix this within the next hour im just gonna sleep cause itl be 11 pm
cool?
that doesnt mean you cant learn how to use Debug.Log within 1 hour
you should easily be able to debug your game within 1 hour and fix the problem
yea
it says ; expected and then when i put a ; on the end of the line it says to i get 90 more errors
if it says ; expected doesnt always mean you need a ; there, it might mean theres other errors near it that cause it to say ;
what line is the error on and which script
where you want it to run
for example before and after setting a value of something
Usually that error means it is missing a semicolon BEFORE that line, or something else as gr4ss said
ok not gonna lie i think i might just not add crouching for now
im gonna keep the code incase i can work something later
you can comment a line by // or a whole section by
/*
code
*/
alright thx
hi ! Can somebody explain me why some Unity built-in features like coroutines generates GC Alloc which later cause from time to time game to free. My game logic si 2 ms per frame and then when GC incremental collect is called, the cpu time is 60 ms
public List<Item> Items = new List<Item>();
public HashSet<string> itemNames = new HashSet<string>();
How is it possible to make the lists into one "shared" list? (Note that one list is a string and the second list is a GameObject)
allocating any object on the heap will cause GC allocation.
how do i reset a integer? like if i press it 10 times it will go back to 0
wdym by a "shared list"?
this is basic C#
how does one "press" an integer?
just setting a value
but for games, that GC collect is a killer of quality
can someone please explain to me what this means?
You know, it would be the same list, but the problem is that each one is of a different type
you didnt assign the button
do you assign it anywhere?
so don't allocate as much stuff on the heap, and make sure you reuse things whenever possible.
thank you so much!
im not really sure i was just following a tutorial
it means the createNicknameBtn reference is null. when you tried to use it
you didn't assign it properly
probably missed the part of them assigning it in the inspector, or didnt get to it yet
WHich means you missed something in your tutorial
Not possible since they're completely different types.
ok ty ty yeah i think that might be it
Suppose they were one type
i forgot to make it something you can do in input manager, im so dumb
what a waste of time lol
then you can make 1 list, there is nothing to "suppose" here
then you just assign with =
but your example is a List and a HashSet
those are two different things
that is the exact reason you use Debug.Log and figure out that your code is not running, then you would figure out its because of your input
yup
is there a physics-based way to scale up an object? i want to scale an object until there's no space but it's causing problems (btw, for future reference, would i put this in the coding or physics channel, since it has both)
I think what you're actually asking here is "How do I make it so my set of items and my list of strings never get out of sync." The answer to that is:
- Judiciously updating them both at the same time
- Getting rid of one of them entirely, and using the remaining one as the only source of truth.
Not sure where to ask this. How can I tell what render pipeline was used from one of my previous projects?
not a code question. but why not just open the project and look?
The first setting under Graphics in Project Settings.
ty
i have a button that i cant type in it, can someone help me please?
how are you making it so that you can type in it
its a prefab so i didnt make it
so how do you want to be able to "type in it"
i know im not giving you a lot to work with im sorry 😭
well of course, you cant "type" in a button
basically i want to be able to type in the input field when i press on it using my mouse
oh im sorry i didnt mean button, i meant input field
do you have an EventSystem in your scene?
basically i cant type in the box that says "enter text"
i dont think so, how do i install it into the scene?
it should have been added to the scene automatically when you added the first UI object or canvas
like you create a new game object, its under UI > EventSystem
i have textMeshPro, does that count as an EventSystem?
a TMP is a TMP
no, the EventSystem is a specific component
a EventSystem is an EventSystem
which you can find under ^
OHHH i think i know what you mean, no i do not, how do i install it into the field?
either make it kinematic or destroy it. rigidbody does not inherit from Behaviour and therefore has no enabled property
you already asked this question and i already replied
oh, mb
whats kinematic tho? static but whats different?
gotcha, other question, can i support controller and stuff if i use the legacy input system (if getkey.............)
yes but it would be much easier to use the new input system
sure, if u check out the Input Manager you can see that Unity already has multiple bindings for their preset inputs
but like gr4ss mentioned, the newer input system is well more suited to support multiple input types and binds
how can I fix this?
Are you using Visual Scripting?
oh nvm I fixed it lol
this problem came back and now I cant fix it. any help?
Perhaps answer the question that was asked?
yea I am
where
That was their answer. Yes, they are using visual scripting
ah ok, english doesnt make sense to me
anyone know how to fix it?
Presumably regenerate those generated files. I'm not familiar with the VS package to know how you do that
How did you fix it back there?
I just closed the editor and reopened it
You seem to be working with some unity tutorial project?
Did you open it with a compatible editor version?
Is the installed visual scripting package compatible with your editor version?
lemme check
when I made the project I used the vr template
thats my version
didnt feel like typing it out lol
It was working fine yesterday
but the errors started popping up when I edited a script from a package I was using
Does it appear when you try to build the game?
yes
Well, editor API can't be included in a build.
The scripts with the errors seem to be generated by visual scripting package. And I don't know enough about visual scripting to tell if that's correct or not. Might want to ask in #763499475641172029
My guess is that these generated files should be in a Editor folder. Did you move them around perhaps?
I did move one
Do you remember which one? Can you move it back?
I just moved it back
ohh shii I think yall fixed it
I rly apricate yalls help
thanks
For future reference: don't move autogenerated folders and files without completely understanding why they are placed there.
I have a really basic question, but I'm wondering about stuff in term of approach. I have a game where the player has to shoot but this is how it works : There is a bar that has a pointer on it, and that pointer moves in a sine wave all over the bar (left to right). The player presses space, then another bar appears and it does the same vertically. Then it shoots. Then it goes back to the beginning of the flow. Imagine shooting darts and aiming horizontally and vertically in separate game states.
I'm thinking of a state machine, but I wonder if there is a better approach built into unity?
No, there is nothing built into unity to do that
Yes a state machine is a good idea here
to orchestrate things
I've seen some people use the animation flow chart to do state machines, is that just a hack to help visualize or a good idea?
I mean, I guess you could.
I would just do it in code. That is definitely my bias though
I think I would do that too
Hello,
its not possible to reference a Subscene in a ScriptableObject ? This one (the public field) get cleaned up every time I close the editor. Thank you
Now, since I have different UIs and whatnot that will be displayed in each state, would it be a good idea to have those objects inside dictionaries and disable / enable them depending on the state (I use the state as the key to the dictionary, for example)
Maybe ask in #1062393052863414313
I have never tried, but they would know most about subscenes
ho right I forgot its part of entities , thanks
That seems reasonable.
Could be as simple as an array and just use index 0 and 1, if you ONLY have the two bars. If there are more and they don't increment clealy like that every time, then a dictionary would be a good idea
I'm hesitating between that and an event system
Where on state change they listen to it and enable / disable themselves? Not sure. That's where I'm a bit confused atm.
my abilities SO has an enum that is set inside the inspector
i want to reference that to check whether the card is strong or weak against whatever its facing to double damage or not
but the only option for referencing an enum within it that its giving me is by the actual SO
ability SO
will i need to make a seperate class for typings?
put the enum outside the ScriptableObject class
alright then how would i reference to put it inside of my SO?
make it public
did not work
https://paste.ee/p/rOQgr - contains the enum
yes you need to reference the ability SO in order to access its enum variable
there is no other way
put the enum outside the class, like an interface
oh wow i didnt know that was possible
thanks
ah, i assumed you were trying to access the enum, not create a variable of that type because you were talking about "referencing" it.
yes, enums are just a type so they can be declared right out in the namespace, just like any other class, interface, or struct
worked
super useful information actually
ecspecially for structs
too
and when a type is nested inside of another type (like an enum nested in a class) then that outer type is part of the fully qualified name of the nested type. so public class MyClass { public enum MyEnum { } } when used outside of MyClass, but in the same namespace then MyEnum is called MyClass.MyEnum
it's not an object reference, it's just part of the type's name
i noticed that
thats the reason why i couldnt reach my abilities type
technically they all had their own enum which was bad in itself
now anything needing a type can easily have one (type as in my in-game type)
so ig no?
i mean, if the intention is to check whether you are in play mode or not, then no that is not going to be a conditional compile symbol. you can check if you are in the editor for it though
That would be super inconvenient, as you would need to compile your game code both for the editor and player.
uh, isnt building supposed to recompile stuffs itself anyways??
There's a bool you can check to run code only in edit/play mode. https://docs.unity3d.com/ScriptReference/Application-isPlaying.html
Yes, but for that you have the platform defines, like UNITY_EDITOR
You don't build your game every time you enter play mode in the editor to make it clear.
im using isplaying now, just weirdly got curioused if theres an coindition symbol
that would require a complete recompile just to enter play mode
im trying to work with the new input system its coming up with a null reference on line 39 but idk why it is doing that
most likely UserInput.instance or UserInput.instance.controls is null
Did you enable the input in onenable?
the input not being enabled would not cause a NullReferenceException
in fact, it would have to be not null in order to enable it
thank i think i figured it out
is it just me or KeyCode.Question isnt SHIFT + /?
Maybe a non standard english keyboard layout?
it doesnt work on you aswell?
Wdym?
in non-stone age unity versions the Use Physical Keys option makes that keycode useless
not sure how it works on your prehistoric version
physical keys option?
it's an option in the input manager. dunno if it's in your ancient unity version
what's the proper way to make sure input works on all devices? keyboard/mouse, gamepad, steamdeck, mobile, more?
The proper way? Test it on each device.
no which system do I use for it?
I've been seeing a lot of new/old input system talk here, but dunno what that is
The new input system
which is? or can I just google "unity new input system"?
You can just google it yes
The old input system can be set up via Project Settings -> Input Manager. In order to use the new input system, you'll have to install the Input System package in the Package Manager.
You can adjust the input for all the devices using both of them, but the new input system is usually considered much better, because of its increased adjustability and a big variety of inputs.
It's simply called "new input system", yes
Actually, it isn't really hard to use, and so, I would recommend it for your game
I'll take a look at it, thx
how to check if the player collides with a specific gameobject
before an answer is provided, can you explain the purpose of doing so? that way a proper solution can be provided
2d platformer game, player falls down, i take 1 of their lives
if theres another way of doing this btw itd be better bc my friend said sometimes you can clip through objects if youre too fast
well in that case you don't necessarily need to check for a specific game object, you can check a tag or use TryGetComponent
how do i chrck tags
you can use the CompareTag method in your OnCollisionEnter2D/OnTriggerEnter2D
just make sure that your player or the object it is colliding with has the tag (depending on which object you are checking from)
can you explain a bit more? i‘m in a gamejam and i‘ve never used this before so
You have to make sure both objects have colliders and the desired one the tag you need.
Check out OnCollisionEnter2D
perhaps you should take some time to learn how to use the unity engine before you participate in a jam, there are excellent beginner courses pinned in this channel
ik how to use unity, not tags
But tags are considered "the basics"
Ye tags are pretty basic
surely you know how to detect a collision, yes? and you know how to call a method on an object. so naturally your next step should be to google the CompareTag method to see how you would use it. it's not some high level concept that requires a tutorial, but if this is too much for you to figure out on your own then you need to go learn the actual basics
Hello. I'm running into an issue where the text input fields in my game only detect clicks on their leftmost side. Any similar experiences and/or fixes?
brother there's no shame in not knowing
sounds like something is blocking the raycast from the mouse. make sure there are no raycast target objects in front of the input field.
also not a code question #📲┃ui-ux
i never said there was. there is shame in intentionally not bothering to learn what you are doing and trying to pass it off like you have done so or insisting you don't need to so that other people have to put in more effort to help you 🤷♂️
how tf am i supposed to learn if i dont know what to google bro
you just told me and i went to google it
but yeah again thanks idk how many times you want to hear that but thanks before this starts to get disrespectful
You inability to use google it not their problem.
Probably, you first want to use this tutorial
very funny joke, i think you didnt understand that i meant i didnt know what i was looking for rather than how to press keys on my keyboard to search
You may be muted if it starts to get disrespectful
if you've never heard of something how can you google it bruh
I see, perhaps I have underestimated your abilities
Pressing the keys is a really great start. Now, you want to find the suitable keys for typing "unity tag", "unity comparetag", "unity oncollisionenter2d" etc.
i dont think you still dont understand what "never heard of" means
obviously i've heard of it after this very amazing person told me about them
and i went to gogole
thanks for your concern though
Sigh I recommend you go through !learn to get your bearings first. The guided tutorials there will do you wonders.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Right, I'm sorry for not sending the voice message for you to hear it. Perhaps, you may be able to google something you have read in [this](#💻┃code-beginner message) message?
Right, so what's the problem now?
perhaps you may be able to read the messages i sent afterwards before replying
that you think im incapable of googling..
Right, because of you telling me you don't know how and what to google
That's why I assumed you haven't used google yet
didnt*
what*
not how
"Unity how to check tags"
You were told this, from that point you knew, and could google that
and i already said i did
as soon as i was told about it
Then perfect, you figured it out. Stop this all
No one was saying you had to know it before that point
you're not gonna believe this
🤯
scroll up
I read it all. You misunderstood them all
So what's the purpose of continuing this if you have already learned how to google how to check the tags?
yes, you're right
i've been trying to say that the whole time but you said i didnt know the topic OR how to google so i was clarifying for you
idk you seemed confused thats all
have a nice day sir / maam
thta's not confusion, i was talking after i learnt about the subject 🤦
Next time, consider googling about the things you hear first right away. And have a nice day too!
I tried to disable the movement script when my cursor is unlocked and shown
private bool isCursorVisible = false;
private bool isCursorLocked = true;
public FirstPersonController firstPersonController;
void Start()
{
SetCursorVisibility(false);
SetCursorLock(true);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
ToggleCursor();
}
}
void ToggleCursor()
{
isCursorVisible = !isCursorVisible;
isCursorLocked = !isCursorLocked;
SetCursorVisibility(isCursorVisible);
SetCursorLock(isCursorLocked);
}
void SetCursorVisibility(bool isVisible)
{
Cursor.visible = isVisible;
if (isVisible)
{
// enable cam move
firstPersonController.enabled = false;
}
else
{
// disable cam move
firstPersonController.enabled = true;
}
It told me "The type or namespace name 'FirstPersonController' could not be found (are you missing a using directive or an assembly reference?)" but the script name is FirstPersonController.cs, where did I do wrong? (sry Im completely new in c# and joined an advanced course.)
make sure that your !IDE is configured so that you can use the quick actions to import the correct namespace (assuming you aren't trying to modify code in an asset since I'm assuming you don't know what assembly definitions are)
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
ok thanks Ima try to figure that out❤️
alright this next week for my game is creating the enemies battle AI in the card battles
anyone have any tips for creating a calculation for the best decisions in battle based on typing, health, and attacks?
it's kinda both
but since we have no variables for an equation, it would become more of a game design question I guess
technically you could create an actual AI
like make AI play your game
and reward it if it beats an other AI
sounds a little out of my range
that's probably not the way to go since we're in a beginner channel lol
what kind of tips are you looking for?
you just need neural networks, but yeah its not the most beginner friendly
i'm certainly not a bad programmer but i got like 7 months under my belt of pure laziness
if anyone has experience making an enemy decision making in a custom battling game
how might i go about turning the types, health, abilities into maybe like percentages or numbers in a calculation
you could assign a weight to each factor and then use the option with the highest weight
for example a damage card that can destroy another card gets a very heigh weight
a type card that targets a type it's weak against gets a low weight
a type card that targets a type it's strong against gets a higher weight ...
plus you can also give health a weight too
the lower the health, the higher the weight
so it focuses on trying to heal
I have three walls and a crate on the map rn. I see 4 wall messages and a crate message. Shouldn't overriding change what happens in a function? Or did I mess up the syntax
!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.
that's not helping
you want me to write the 2 lines of code in separate documents through a website to limit chat flooding?
yeah that's what i was thinking
no, you should just sent it like this so people can actually copy it or edit it
do you actually need virtual & override for stuff this basic?
i was about to ask too
one sec mate
I think its more about the basics and learning how it works?
ive made some pretty big systems already and messed around with classes quite a bit but I never had to use override or virtual
Its very useful in alot of cases/
The syntax looks correct
idk ig i just didnt use inheritance all too much yet
Do you have both script attached to one object?
it looks like it's actually required if you want to overwrite a function so guess it's fine 🙂
tbf I probably should be using inheritance because I'm making a bullethell and projectiles could use it, but idk how to honestly
well you just got a very simple example 🙂
maybe add , gameobject to the debugs and check which one is sending it twice?
like I have this example
But I assume you just have the script for wall **and **crate on one of them, cause the syntax is correct im pretty sure
and I have a lot of projectiles that have the same setup but different values
but idk if thats what inheritance is used for
If all of your projectiles are prefabs then I guess this works
Ye why do you need virtual and override for that
nah, inheritance is if you want to use the same function but get different results
for example a class Animal could have a function Speak
then the class Cat would return "Miauw" and the class Dog would return "Waff"
if your bullets do not behave differently in the same situation/function, I think there's no need
I see, thanks!
I've never used it myself
I mean
“Miauw “ and “waff” 💀
yeahh i probably dont need it
it was actually a really good explanation
programmers tend to make things more complicated instead of explaining them 🙂
No the explanation was great I was just surprised by miauw instead of meow and waff instead of woof 😂
I'm Belgian 😅 It's miauw and woef here
Oh I see my bad 😅
As long as your bullets are this simple you dont need it. But what if you want one bullet to have an additional effect thats unique to this bullet?
With inheritance you can derive from the baseclass "Projectile" and still have all bullet functionality. Without it you have 2 different classes with only a small difference and if you need to access the script youre gonna have to look for 2 different scripts now on each projectile. And it just gets worse the more you have.
but why wouldn't you just add that extra functionality to the base class instead of bothering to add inheritance?
if the classes are like 2000 lines long then yeah, but in most cases?
Inheritance is pretty important for alot of things and the basics of oop, you technically dont need it but you can do many more things much more efficiently if you know this.
Well you dont want functions on a projectile that dont belong to it right
why not?
Ye I love inheritance
it's just a few lines of code that never get called, I don't see the issue? maybe that's why I've never used it 😛
Why would the dog class have a function for saying "Meow"
its gonna get extremely unreadable and harder to maintain after a while
and the more you add the worse it gets
because if my world only contains 2 animals it would be easier to make a function Bark() and a function Miauw() instead of adding inheritance
no
yeah this, but in most cases you never get that far, at least I've never had any code that required this because it got too complex
Even then I would much more like to have a function called "Make sound"
and not have to check first which function I need to call now
this is what I mean btw
It’s also cleaner
Or for Items, in my game I dont want to have a long switch case or 20 if-else statements for using items:
I dont want to check for which item I am currently holding to use the correct function:
I just call the UseItem function and each item will know what to do
i sent a 1 min video but basically the first 20 seconds explain what I mean
Hmm I might be doing this 🤔
Thanks!
Or an event
ok, sorry for not rtesponding, had to do something rq
I guess yeah but no need for it right?
Mm, I don't fully know the issue.
nothing even shows up
Looking lit
click on the debug
Should be public virtual void no?
it should highlight the item in the scene view
im not even quite sure what you want to achieve here
ty :)
both from the crate
Could be? I also do it with public first
Ye
does the order even matter?
yep
I never used this stuff, just checking it out. Ill try that
no difference
Yea didn’t think so
test
And you sure you only have one script on the crate?
public protected internal private new abstract virtual override sealed static readonly extern unsafe volatile async
The order doesn't matter here
I'm an idiot xd
this is the order I got from googling
i can only guess what volatile means
I know what async means
Ik but it’s unconventional
Tf is thst 😂
Too many errors
It's a prefab variant, forgot to remove it
wdym
told you all the way up here @magic panther xD
A static method cannot be virtual, override etc.
They were saying order not one variable/method
this might just be a coding convention and not smth that matters
Oh
Ye I think so
I missed your message, my bad
also one last thing
it has to do with multithreading or something
like it can be accessed by multiple threads at the same time
Share the error
because what it should do is trigger an Interact function in the collided object
the Start was for testing, I renamed it to Interact now in both scripts, all is the same apart frtom that
It's just because I don't know how to trigger the function
Collider doesn't have an Interact method
ik
Then why use it?
what do I replace collider with
honestly id use some sort of other function that isnt Start
Which class' method is it?
I did use another one
oh
yea mb
Which class got it?
but how do you call it
Wall and Crate
the perfect outcome is to check if the hit object has an Interact function and if it does, call it
Check it with TryGetComponent<T>
where tho
so that do something like that ? ```using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Build : MonoBehaviour
{
public GameObject prefab;
public Cellule cellulePrefab;
public List<GameObject> instances = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
for (var a = -50; a < 50; a++)
{
for (var i = -50; i < 50; i++)
{
Cellule newCellule = Instantiate(prefab, new Vector3(i , a, 0), Quaternion.identity);
newCellule.build = this;
instances.Add(newCellule);
}
}
}
public class Cellule
{
public Build build;
}
// Update is called once per frame
void Update()
{
}
}
if (hitInfo.collider.TryGetComponent(out Wall wall))
wall.Interact();
there are other scripts that have it, there's other wall types
like the Crate
which expands the Wall
Which should all be inherited from Wall
so this will work?
No, I've just posted a random piece of code, which is not supposed to do anything
got this error
Where is the line 41?
hitInfo is null
oh yeah xd
You don't use the canMove boolean
hitInfo != null
ok, so canMove &&
as both of these ifs checked for canMove, I rearranged it like this
I mean, its collider is not null in this case, as RaycastHit is a struct which cannot be null
something is null
Why is it reversed.
one sec brb
bool canMove = !Physics.BoxCast
(hitInfo.collider.TryGetComponent(out Wall wall) returns null
You should either remove the ! or check for !canMove
It doesn't
It returns an error
As collider is null
It doesn't fully return null
hitInfo.collider returns null, and trying to get the component from null results in an error
And this fixes it
the raycast hit nothing, you check the result anyway. you only don't check it when the raycast was successful
canMove == true here implies that the cast didn't encounter a wall, so check for !canMove instead
wdym reversed
It's better to remove the !, as moving when canMove is false isn't logical
If I had to rewrite it like this I'd change the variable name tbh
removed the !
i'll test it
It won't work
yeah I can't move
You either remove the ! before the cast, or put the ! before the condition
Not both
What isn't logical is moving when canMove is false, so that should be changed, as he did now
Isn't it literally what I've said?
You were talking about removing the !, so I assumed canMove = Physics.BoxCast, which would return true for encountering a wall and implying that it can then move, which wouldn't be logical
If that's not it, then my brain is fried, I had 3 hours of sleep.
I simply forgot to change the variable name after implementing the !
it almost was cantMove
which sounds dumb as hell
It does
Imagine
hey, im making my character abble to dash following a tuto but i dont understand why he dash only in one direction even if i walk in an other direction, can someone help ?
I was trying to create a button and connect it with my script but idk what i should input here
cause your velocity vector is in fixed direction, aka your transform.localScale.x
I know it's confusing, because when you turn left you flip your local scale from positive 1 to negative 1, instead of flipping your character using the scale, use
this.GameObject.Rotate( 0, 180, 0);
using the Rotate Method, will save you from a lot of headaches in the future.
ok so im making a new movement code https://hatebin.com/jsdkqtfasu why isnt it working
there is NINETY errors
maybe share those, we are not mind readers
oh okay cause when i flip i only change the sprite renderer x, so i have to change my void flip ? or have to change in dash ? sorry im starting so i dont get eveything ://
all of them are just uh
ambiguity between x and y
on line 43 ?
no theres way more then just that
then show them
there is one in nearly every line
Just your void Flip()
also, leave the scale at positive 1
once you add the Rotation Method, you will no longer need to mess with Scale
ok ok ok lets try it thanks a lot
@bronze zenith if you will not supply the requested information why are you asking for help and how do you expect us to provide it?
i was trying what the other guy said but im not good with code so im struggling
ill give the error information
try this @bronze zenith https://hatebin.com/sgnpogrycr
i cant actually fit them all on one screen
does not matter, just screenshot the console with the first error selected
ok
sorry, try this one instead https://hatebin.com/pnqqgfaytm
I forgot to change a word
OK, you have duplicate scripts (PlayerMovement) , sort that out first
but theres one place playermovement is used
not about used, in your project
oh wait
dang, lol I keep forgetting the add the paranthesis
this one should be fine @bronze zenith
np, let me know if that worked
i found the scripts
i deleted them from the player
but not the actual game
(before)
yeah now theres no issues found
thanks guys
ok theres 8 more errors
same code
every time i use rb it doesent exist in the current context
nvm, think i fixed it
Hello, How do i connect both animations in my script to make it functional?
public HashSet<string> itemList = new HashSet<string>();
How can i see this list in the Inspector?
do you mean console log?
in that case:
google unity serializable hashset
No, they mean serializing it in the Inspector
oh
No, in the inspector
Like this
You may want to either implement a struct yourself, convert it to a List, or use the marcospgp's answer on Unity's forum, which internally converts the HashSet to a List
The link doesn't seem quite right
Now it works. Links don't seem to support specific highlights
hi i make a "game of life" and i just dont understand why sometime my code work and sometime not exemple: https://cdn.discordapp.com/attachments/1149752436681080952/1236615797493989386/20240505_114848.mp4?ex=6638a7b5&is=66375635&hm=3ee9c4f17f5eb0967578e206239b29717e2499626e3866cd37d58f893785043b&
this is my code for transform different cell:
{
while (gameStart == true)
{
yield return new WaitForSeconds(1f);
celluleVivante = 0;
RaycastHit2D[] hitList;
hitList = Physics2D.CircleCastAll(transform.position, 1.3f, Vector2.zero);
foreach(RaycastHit2D hit in hitList)
{
GameObject obj = hit.collider.gameObject;
if(obj.tag == "vivante")
{
celluleVivante++;
}
}
if (gameObject.tag == "morte" && celluleVivante == 3)
{
gameObject.tag = "vivante";
sprite.color = new Color(0,0,0);
}
if (gameObject.tag == "vivante" && (celluleVivante != 2 || celluleVivante !=3))
{
gameObject.tag = "morte";
sprite.color = new Color(255,255,255);
}
}
}
Use a site to post your code, please.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you mean for pattern
XAX
XAX
XAX
wont become
XXX
AAA
XXX
btw rules of game of life is dependent on your implementation, please state the rules
What do "X" and "A" mean?
"dead" and "alive"?
yes
It should become if I'm not wrong
X A X -> X A X
X A X -> X X X
X A X -> X A X
It's weird how to check them with CircleCastAll
btw they should use grid not a circle cast nor any physical query
its the only way i find so...
You should store the cells in a List of structs
yes sparse array should be better i think.....
or even quad tree
but grid is simple enough for beginner
It's limited to be rectangle-only
what is that
A list of structs.
and i need raycast for check only near cell
Don't do it
Consider, probably, having a List of Cells, where struct Cell has its Vector2 position and a reference the block, or whatever you're using
And, yeah, you're not checking them correctly
You have to check each cell's position with the following directions:
private static readonly List<Cell> _directions = new()
{
new(-1, -1),
new(-1, 0),
new(-1, 1),
new(0, -1),
new(0, 1),
new(1, -1),
new(1, 0),
new(1, 1)
};
Damn, useless comma at the end.
But, right, these are the 8 cells, where the cell checked has the offset (0, 0), and so (-1, -1) is its top-left corner
Should be called _offsets, actually
how can i check a vector position?
Check a vector position?
Not quite sure what exactly you're referring to
like how can i get the tag of my gameobject with a position
Store it in a 2d array/sparse array/quad tree/ anything that can store grid
So you have a List of Cells, each contains the Cell's position in the grid and the reference to the e.g. GameObject
I just wonder whether these cells should be GameObjects..
But, right, they may
idk im suck
Are cells a class or struct?
i just go delete all and watch a A - Z game of life tutorial
Does anyone know why raycast might not collide with game objects? I raycast from a gun and sometimes to goes right through the enemy... it is not about the layers, on the right you can see layers that are beeing ignored.
if (Physics.Raycast(rayCastOrigin.position, direction, out hit,
_weaponInfo.Distance, ~_ignoredLayers))
{
float magn = Vector3.Distance(rayCastOrigin.position, hit.point);
Debug.DrawRay(rayCastOrigin.position, direction * magn, Color.cyan, 3f);
var trail = SetUpTrail();
StartCoroutine(SpawnTrail(trail, hit));
DealDamage(hit);
}
You don't pass layers to ignore in a raycast, you pass layers to collide with
Hello guys so I just wanted to make a new game that will be happening in first person. I saw that Unity had a template for first person, so I thought I would use that. Everything works fine unless I started adding UI. So the template already offers the option to click ESC to freely move the mouse. But as soon as you click on a UI button, the mouse gets locked again. I tried to fix it, but I am pretty new at scripting, which is also why I use this template, and at some point, after spending a whole day going through so many scripts, I gave up.
no, you can , if you write tilda sign before it
A bit of a weird thing to do but you could also add QueryTriggerInteraction.Collide
why your draw the ray only if you hit it
though it cant solve yur problem but help to you debug
well, i have an arena/ level with only closed space, so i didn't think it makes much of a difference since distance of raycast is set to 200
Have you tried doing a Debug.DrawRay with the raycast to verify the line is correct?
but now you want to know why your ray doesnt hit anything
Raycast always hits something, the problem is, for some reason sometimes it ignores enemies, here is perfect example. The blue line you see is a draw ray from a gun to a hitpoint. So it shows the whole path of a bullet, two shots go right through the enemy, so raycast didnt collide with enemy (he was standing idle) but the third one did collide and hp bar reduced a little, though you cant see it on screenshot
and scince raycast hit enemy once its not about collision layers
The Cell was a record in my case
Have you tried doing Debug.DrawRay right before your raycast to verify the data that you are feeding to the raycast?
But in their case, it may, probably, be a class. Though it doesn't matter, it can also be a struct.
i would let the raycast able to hit anything first then check the layer of target to debug
or just check the layer of the yellow capsule in inspector and its collider
I would suggest you try out the Conway's Game of Life on Exercism, in case you first want to know how to implement it with a simple matrix. Should be a bit easier than doing it in Unity right away.
If you don't want to solve it, you may also try out my solution for this task or the solutions of the others. In case you want to use mine, I may assist you with its further implementation in Unity.
I'm not sure whether the links work as expected, so let me know.
The difference is that, instead of a matrix, which lets you access the cell's row and column, you'll, probably, want to use a List with the positions, which are not necessarily in a rectangle form.
Enumerating through every list's cell and checking the cells in the 8 directions shouldn't differ too much
https://leetcode.com/problems/game-of-life/description/
curious if leetcode has game of life...and they have it
see how the leetcode problem passes the cell
i find a good tutorial in youtube for make it with tile map so go try
I like Exercism more through 😉
Alright, you may also try this out
idk if youtube tutorial are the best way to learn but i gonna try
ty for the help btw
Could you send it?
Learn to make John Conway's Game of Life in Unity. Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and ...
Oh, right, I haven't considered that you could have a simple rectangle game field
So a matrix can be usable in this case
Hoping someone can help me figure this out. I've got a fade-in/out transition setup to happen between scenes. It's currently doing this via a LevelLoaderController class (shown in the screenshot).
When the user clicks the "Play" button on the main menu, it works flawlessly.
However, on the next scene, when the user pauses and selects "Quit" it doesn't do anything (the quit button worked fine before introducing these transitions).
I've debugged it a bit and can see that when I press the quit button, it reaches the yield statement but then doesn't ever go past that.
At a guess, whichever object which is starting the LoadLevel coroutine is being destroyed
How could I tell if that was the case? Would it disappear from the hierarchy during a test play? If so, nothing like that has happened.
Also, when debugging, it hits the yield statement and doesn't continue past that but, if I click the quit button again, it keeps reaching the same point and never getting past the yield (or starting any animation)
you could add an OnDisable method to this script with a Debug in it to see if it fires
also the script where you start the coroutine
Will check, 2 secs
Have added the OnDisable method in my PauseMenuController (where the corouting that's not working is being called) and nothing was being output to the log
try running the coroutine on the levelloadcontroller not on the script with Quit
Same thing :/
just to be sure change your string variable from Start to start
it's odd to have a variable the same as a method
I presume this is a DDOL object
The trigger is named "Start" but Rider made the suggestion to convert it to a variable instead 😛
I've changed it from the int variable to the string "Start" but still has the same behaviour
The object is a prefab that's loaded onto both scenes which, on scene load, plays the fade-in animation automatically. That gameobject also has the LevelLoaderController script attached to it
Which is then supposed to play the fade-out animation on scene change
but it needs to be DDOL otherwise it will not survive scene unload
Can give it a try. How do I set it to a DDOL object?
So this should be fine?
Now the second scene doesn't load at all 🤣
Fades to black and then never fades in the next scene from the main menu
What's in the animation
I think is should ask here so is there a script where you can push a button and opens a door but the door only opens for you? cause I've been trying to do that but I cant
Also are you changing time scale at any point
What does "only opens for you" mean?
Is this a multiplayer game?
Yes... on the pause screen... 🤣 I think I'm starting to know where the problem is
ye
In general scripts don't just exist for your particular nuanced use case. You have to write them.
Use WaitforSecondsRealtime
and, if you are even considering doing multiplayer you shuold know simple stuff like this already
Yeah, code-beginner + multiplayer is usually a disaster
Multiplayer is not a beginner subject people
eh it's turning out pretty well for me
Least of all networked multiplayer.
it's not even a 'general' subject, very much 'advanced'
Thanks. It's working better now in the fact that it switches scenes but doesn't do the fade out (presumably because the timeScale is set to 0 (?)
that will be it
Is it possible to make the animation play irrespective of the "world time"? Similar to the WaitForSecondsRealTime?
coroutines, like Update do not run when timescale=0
Managed to sort it by changing the update mode to Unscaled Time
On the animator
Cheers for the help both 👍
float elapsedTime = 0f;
while (stunRemaining > 0)
{
float curveProgress = elapsedTime / length;
float curveValue = launchTime.Evaluate(curveProgress);
rb.velocity *= curveValue;
yield return null;
stunRemaining -= Time.deltaTime;
elapsedTime += Time.deltaTime;
}
I dont think im doing this correctly. I'm trying to implement balloon knockback by using animation curves, but if i set the value above 1 the player gets launched instantly as i'm assuming its just multiplying by 2 over and over again
@wintry quarry i'm trying out what you mentioned last night, idk if this has been done correctly though
You have the Cellule class inside the Build class. Why?
Buttons in unity could exist only on UI level, so if I want to make button on one of my sprites, I should either make anchor and follow on UI layer, or write custom script with button-like logic. Both ways seems very awkward to me.
Am I missing something?
There are world space canvases
But this would ruin my hierarchy, so I kinda still obliged to use anchor to connect sprite and button..
How would that ruin your hierarchy?
Button will be part of the other branch in the hierarchy
Unless I do mini-canvas for each object that uses it
Yeah, each thing that needs a button would have their own canvas as a child. Then enable and disable them as needed
That makes sense, thanks!
how can i reduce velocity with an animation curve ?
Multiply the direction you want by the return of evaluating the curve (also multiplied by a speed factor)
Should be setting the magnitude of velocity with this, not multiplying
i cant set magnitude, though
magnitude has no setter
You set a float
And use that as the magnitude along with a direction from elsewhere
where would i get the direction from?
the only thing i can think of is the velocity of the rigidbody
Whatever direction the player was smashed in?
but what if they hit a wall is the issue
Then you stop
Or you bounce them
Or slide them along it
Whatever
Smash bros characters bounce at a certain threshold
would i have to manually calculate the bounce direction?
I guess? These are all implementation details for you to figure out
Nobody ever said this would be simple
Vector2.Reflect exists though
this reminds me of my old system 😭 i'll experiment with this
hello I want to make an attack I have 2 meshes for it and want to do it such that when Q is pressed the attack mesh is switched to from the standing mesh pls help
You have already been answered. Why do you cross-post?
should i use trigger or bool in the parameters of the animator for transitions? can i untrigger it? if then whats the difference with bool?
A trigger parameter is basically a one-time-use boolean. It unsets itself whenever it's used for a transition
trigger is like a flash, a signal for a single tick, bool is constant until you change it
mmm gotcha thanks guys
This raycast system never detects Edges, only Vertecies and I don't know why.
public static bool pathFromPoint(Vertex start, int pass_betweens, Camera pass_c, List<Vertex> pass_verts, List<Edge> pass_edges) {
start.colliderEnabled(false);
Debug.Log($"<b><color=#FFFF00>Attempting to generate a path from vertex {start.name}.</color></b> ");
Vector2 randDir = random2DRotate_Arbitrary(10, 40, start, start);
Debug.DrawRay(start.position, randDir, Color.yellow, 100000);
RaycastHit2D hit = Physics2D.Raycast(start, randDir);
start.colliderEnabled(true);
if (hit.collider == null) {
Debug.Log($"<b><color=#FF0000>Path generator @ {start.name}: Raycast Failure.</color></b>");
return false;
}
Vertex end;
switch (hit.collider) {
case EdgeCollider2D:
//start.colliderEnabled(true);
end = cVertex(hit.point, pass_c);
Debug.Log($"Path generator @ {start.name} collided with an edge");
break;
case CircleCollider2D:
//start.colliderEnabled(true);
end = hit.collider.gameObject.GetComponent<Vertex>();
Debug.Log($"Path generator @ {start.name} collided with a vertex");
break;
default:
Debug.Log($"<b><color=#FF0000>Path generator @ {start.name} failed finding an endpoint!</color></b>");
//start.colliderEnabled(true);
return false;
}
Debug.Log($"<b><color=#FFFF00>Path generator @ {start.name} successfully found endpoint {end.name}.</color></b>");
Debug.DrawLine((Vector2)start, (Vector2)end, Color.red, 1000000f);
//Debug.Log($"Path generation starting from vertex {start.name} has found a vaild collider: {}");
ptpPath(start, end, pass_betweens, pass_c, pass_verts, pass_edges);
return true;
}
ive seen the on any state being used but whats this one for?
to stop playing the animation after its done
so you can play it just once
transition to it and no more animations will be playing
Decompiled my own code for some reasons, and saw this..
can i go back to other state or its forever?
hey guys, i have a class which contains a string and a list of strings, and a list of that class:
[field: SerializeField] public List<ownedItems> OwnedItems { get; private set; } = new();
[Serializable]
public class ownedItems
{
public string CatalogName;
public List<string> ownedItemNames;
}
how can I foreach check OwnedItems list, if it any "CatalogName" inside of it contains a specific string?
For example theres 7 of these classes created inside the list, how can i check if any of them is equals for example to "Skibidi"
my brain isnt working for 2 days
foreach (ownedItems oi in OwnedItems) {
if (oi.CatalogName == "Skibidi") // do something
}```
simple no?
or using Linq:
bool anySkibidi = OwnedItems.Any(oi => oi.CatalogName == "Skibidi");```
holy ducking shit i didnt think of putting ownedItems 
brain is not braining
thanks 
i just got confue
well
your confusion is probably stemming from the fact that your variables are named poorly
And you're not following C# naming conventions
I have made 2 games originally, and other games by following tutorials since 1 year. Yet I have to look up on google again whenever I want to start coding. Like if i want to create input method, I will have to look again on the internet to remind myself that this is how we do it. How do I fix this ( I want to remember all these by heart)
repetition is key
doing it once or twice ain't gonna cut it
You have to consistently do it eventually it just becomes "muscle memory"
I mean you dont have to make an entire game just practice those functions together lol
haha yes yes i get u
does unity have a built-in function that would allow me to check via code whenever an object is illuminated by some source of light? I'd like to check if there is any light on it.
its not that cut and dry no
believe me, when I started had to do this exact thing because I wanted a spotlight to act as an enemy alert system
really depends how accurate you want to be and what you're doing thre are several workarounds
i wanted to create a hostile creature that would stalk the player but it would be afraid of light so it could be startled by a player's flashlight etc.
would raycasts be accurate enough?
raycast could work but if its a flashlight you might need a bigger shape like a sphere or something
SphereCast
ok, thanks for the overall idea of how i could get that to work. i will try this someday
yeah physics cast is def the way to go if you want something that works and is simple
fine, thank you
{
if (Player.transform.position.y < -5 && !PlayerDead)
{
PlayerDead = true;
Time.timeScale = 0f;
}
if (PlayerDead)
{
Dead();
} else
{
Alive();
}
}
public void Dead ()
{
DeathScreenUI.SetActive(true);
Cursor.lockState = CursorLockMode.None;
}
public void Alive()
{
DeathScreenUI.SetActive(false);
PlayerDead = false;
}
public void Menu()
{
Alive();
Time.timeScale = 1f;
Debug.Log("Menu");
SceneManager.LoadScene("StartMenu");
}
}```
@rich adder
whats the problem?
So when my player character goes below -5 it succesfully dies but when i click on the menu button the next scene does not succesfully work due to timescale still being 0
Basicly the game is stuck cause the game is paused
also when putting for example instead of (player.transform.position.y < 5) a keypress the whole thing does work
switch it back to timescale 1 when you change level?
yes due to my character constantly being killed
well why are you doing it eveyframe
just do
if (Player.transform.position.y < -5 && !PlayerDead)
{
PlayerDead = true;
Time.timeScale = 0f;
Dead();
}```
what is even the point of the if statement after
can someone explain the problem with my script basicly i am supposed to take damage when i walk inside a box
Like in real life, we must verify our existance every moment to avoid falling onto an existential dread we can never recover from. They are just thinking about their character's psychological state..
!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.
yes must check my pulse every second to make sure i aint dead lol
who holds this script?
Put a debug before the if statement in OnCollisionEnter
Well actually, yeah, the opposite makes more sense the way it is set up
what kind of collider does it have? maybe you need OnTriggerEnter instead
i dont see how you can "enter" it if its not a trigger
will try that
doing that now
like this?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Death : MonoBehaviour
{
public static bool PlayerDead = false;
public GameObject DeathScreenUI;
public GameObject Player;
void Update()
{
if (Player.transform.position.y < -5 && !PlayerDead)
{
PlayerDead = true;
Time.timeScale = 0f;
Dead();
}
}
public void Dead ()
{
DeathScreenUI.SetActive(true);
Cursor.lockState = CursorLockMode.None;
}
public void Alive()
{
DeathScreenUI.SetActive(false);
PlayerDead = false;
Time.timeScale = 1f;
}
public void Menu()
{
Alive();
Time.timeScale = 1f;
Debug.Log("Menu");
SceneManager.LoadScene("StartMenu");
}
}```
It just means collide. The frame you enter the collision
ok
What kind of colliders do you have?
box collider
did you try it
They meant are they trigger colliders
yep
Well yes, it must be OnTriggerEnter then.
still stuck
Which object has the rigidbody
player
perhaps you forgot to give the player the tag? or a rigidbody?
how are you calling Menu
Ok, then the issue is that you cannot receive OnCollisionEnter when they are triggers
what is stuck exactly
Make the change they suggested
with a button
is Menu log printing
the animation to the menu screen
yes
well yeah animations dont work with timescale 0
exactly but buttons dont work either no?
Time.timeScale = 1f; before doing any animations
oki
buttons should work fine
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Levelloaderscript : MonoBehaviour
{
public Animator transition;
public float transitionTime = 1.0f;
public void newLevel()
{
StartCoroutine(loadLevel(SceneManager.GetActiveScene().buildIndex + 1));
}
IEnumerator loadLevel(int levelIndex)
{
Time.timeScale = 1f;
transition.SetTrigger("Start");
yield return new WaitForSeconds(transitionTime);
SceneManager.LoadScene(levelIndex);
}
}```
still does not work
you are changing timescale in all sorts of places
debug the value then
coroutines / animations dont work with timescale 0
so if its not working then timescale is prob still 0
so where should i put Debug.Log(Time.timeScale.value)?
but you need logs inside to double check what Time.scale is when you press that
just Time.timeScale
is fine
still dosent work
Did you put the debug before the if statement?
{
Debug.Log(Time.timeScale);
if (Player.transform.position.y < -5 && !PlayerDead)
{
PlayerDead = true;
Time.timeScale = 0f;
Dead();
}
}```
i put it here and in my console i am only getting 0's
Did you move the script to the player? If so, did you change the tag check to check the other object instead?
let me do that
The debug would be more helpful at this point
ok
ok so your other functions aren't running
probably
if i remove the Playerdead = false at alive it works
oh you were setting it back to false?
You should remove the whole alive method.
Just do that stuff in Awake
that makes sense.. you created a loop
yup very beginner
huh I didnt even see that in Alive()
But now when i have died once and go back into the game i cant die anymore
put that stuff in awake
i deleted awake
got it working thanks
^ that or make Init method
Don't
So how should i fix that?
i reinstated awake
how should i set Playerdead to false again
the same way you set it to true
Hi I have a problem with player knockback for Unity 2D
It's not working when the enemy is colliding with player
ok
private void OnCollisionEnter2D(Collision2D other) {
if(other.gameObject.tag == "Player"){
playercontroller = other.gameObject.GetComponent<PlayerController>();
playerrb = other.gameObject.GetComponent<Rigidbody2D>();
playercontroller.ChangeHealth(damageamount);
Vector2 difference = playerrb.transform.position- slimerb.transform.position;
difference = difference.normalized*thrust;
playerrb.AddForce(difference, ForceMode2D.Force);
}
}
📃 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.
With an = sign
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEditor;
using UnityEngine;
public class EnemySlime : MonoBehaviour
{
// Start is called before the first frame update
PlayerController playercontroller;
Rigidbody2D playerrb;
Rigidbody2D slimerb;
public int damageamount = -1;
public float thrust = 20;
void Start()
{
slimerb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D other) {
if(other.gameObject.tag == "Player"){
playercontroller = other.gameObject.GetComponent<PlayerController>();
playerrb = other.gameObject.GetComponent<Rigidbody2D>();
playercontroller.ChangeHealth(damageamount);
Vector2 difference = playerrb.transform.position- slimerb.transform.position;
difference = difference.normalized*thrust;
playerrb.AddForce(difference, ForceMode2D.Force);
}
}
}
public void Alive()
{
if (PlayerDead == true)
{
PlayerDead = false;
}
DeathScreenUI.SetActive(false);
Time.timeScale = 1f;
}
what am i doing wrong?
so are you certain the function is even running ?
I used a Debug.Log statement and yes it triggers
Get rid of that if statement
Just set it false
try with Impulse force instead
thats what it was breaking it in the first place
i tried and it does not work
You tried that in Awake?
Or in Alive?
how would that break anything
it still doesnt work
its probably because you're overriding the player movement with velocity
this
can you show the current code and send it in a link
the updated code, not the old code. What you wrote so far
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
Awake runs once in the objects entire lifetime
You were calling Alive over and over
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Death : MonoBehaviour
{
public static bool PlayerDead = false;
public GameObject DeathScreenUI;
public GameObject Player;
void Update()
{
Debug.Log(Time.timeScale);
if (Player.transform.position.y < -5 && !PlayerDead)
{
PlayerDead = true;
Time.timeScale = 0f;
Dead();
}
}
public void Dead ()
{
DeathScreenUI.SetActive(true);
Cursor.lockState = CursorLockMode.None;
}
public void Alive()
{
DeathScreenUI.SetActive(false);
Time.timeScale = 1f;
}
public void Menu()
{
Alive();
Time.timeScale = 1f;
Debug.Log("Menu");
SceneManager.LoadScene("StartMenu");
}
}```
this works once but then it stops working
Because you don't set it in awake!
Just try it
Playerdead = false;?
Of course
Vector2 movement = position.normalized;
rigidBody2D.MovePosition(rigidBody2D.position + movement * speed * Time.deltaTime);
This is the only other code affecting movement the posistion is from Input.GetAxis(Vertical/Horizontal)
doesnt work
It will. Show what you did
why are you using MovePosition?
did you make rigidbody kinematic
public void Alive()
{
PlayerDead = false;
DeathScreenUI.SetActive(false);
Time.timeScale = 1f;
}
Oh my god. Do it in Awake
You've been told this a bunch of times
Not Alive, Awake
Awake is a unity method that is called automatically
im so sorry
I don't think so should I put it in the start function
Yes. Void is a return type
What's the name of changing rooms via "doors" on a 2D Plateformer game (like Celeste and Hollow Knight) ? I'm looking for some kind of tutos on the internet but no idea how to search for them.
i thought you were misreferencing alive
I explicitly said "not in alive, do it in awake" 🤣
Edit: well, close to that
#💻┃code-beginner message
Hi, this is eren
I'm newbie here
Can you please tell me how can I learn coding?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the start function?
what does that have anything to do with what i asked
To make the rigidbody kinematic
is the rigidbody kinematic or not ?
whew it works
It is
then how do you expect AddForce would work on a kinematic ?
thanks @rich adder @summer stump for the help and patience with my feeble coding skills
All good! Glad you got it
I changed it but it's stil the same
you changed what?
the kinematic to false
are you just randomly doing shit expecting a different result without understanding why?
MovePosition is meant for rigidbody kinematic
it overrides any forces, of course Adding force won't work
so before adding the force I can set iskinematic to false and after I can turn it on again to let the player move?
https://hatebin.com/annfkevskk
I need help, it says that there is no file and created absolutely same file...
Application.persistentDataPath + /settings.json is path
You would also have to stop calling MovePosition during the addforce
that will be cumbersome because you cannot use MovePosition every frame to AddForce
All of that code after the if will run no matter what
That should all be in else
Hi
Or return inside the if statement
Is there another way to move the player around without MovePosition, should I use transform.position instead?
Definitely not
not at all
Use rigid body or character controller
wait... i forgot.. ok thanks
Use velocity, addforce, or moveposition
Can some one tell me what the uses of comment in python
no character controller in 2D and they have rb already
O I didn’t know 2d
Wut...?
idk this is a c# unity channel
I meant python
What are the uses of comments?
ask python server
This is a unity server. So that is off topic
Yeah can you please tell. Me
To comment
isn't it #
Actually I'm newbie
anyway this isn't a python server
Not the issue
So don't know much about this
Commenting uses is to comment
comment the reasonning of why you are using a function for example
don't comment what the function does, cause it should be obvious without comments
Ohk thanks bro
So which code is used in unity
c#
Why?
its not a set rule just an opinion, I mean obviously do whatever is easy for you but I never had to comment what a function does because it pretty self explanatory to me
but at times I do have to comment the reasoning behind the function
I mean, this may be self explanatory in some cases, but you might want to add a summary for someone using this method
But I'm not sure whether you include <summary> in your assumption
sometimes I do summaries sure. Depends if the code will be shared mostly
if i have CalculatePath method, I don't think the summary is required, then I'm just writing sugar
I've finally resolved my issues with mercy invincibility - turns out they collided with components with the default layer
How can I Open the unity console?
the unity console?
the tab in the editor?
alr btw this is a code channel, for next time #💻┃unity-talk
Ah ok.
Damn can I call c++ functions from c# w plugins?
of course
How can I Attach a point light to a Player?
easiest way, would be to create a point light gameobject, add it as a child of the player gameobject, and move it to a spot relative to the player from where you want it to shine
Drag and drop
May want to check out !learn
The essentials pathway will give you a huge leg up
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
you have to drag the light onto the player gameobject
consider a unity tutorial! there's plenty good online, and they help with stuff like that