#💻┃code-beginner
1 messages · Page 454 of 1
All you have to look at is the local position of the "EndPosition" GameObject, that's it . . .
but if u look at the endpositioning, its not higher right?
hi
help me pls, why does i get "MissingReferenceException: The object of type 'Animator' has been destroyed" error after scene reloading? The most weird part is that script actually works but throws this error for some reason
MissingReferenceException: The object of type 'Animator' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Animator.GetFloat (System.String name) (at <9b89611000504a9585efec19be4faf3b>:0) Movement.RunStop (UnityEngine.InputSystem.InputAction+CallbackContext context) (at Assets/Scripts/Player/Movement.cs:141) UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Utilities/DelegateHelpers.cs:46) UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*) UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
How can we tell? You didn't show us the inspector for the EndPosition GameObject . . .
You have to actually click on it and look . . .
the Y value should be higher
this the inspector
what im seeing is the child object is the exact position of the parent object
i could be wrong
brb
Don't ask to ask, just ask . . .
ye exactly
i dont know why the spawner is spawning higher
what do you mean
I asked several times no one answered
where is the page where you see the inputs
like yk "Mouse X"
you mean this? https://docs.unity3d.com/Manual/class-InputManager.html
no like where do I see how many Input options are there?
read the first sentence in the link
thank youu
No one will know that you've asked before unless they were in the channel at that time. Just keep reposting so everyone can see your question and attempt to help. You can't assume we already know . . .
nah I typed it so that I could know if anyone was in the channel because when I asked no one was 😦
how do I make a movement system can someone please send a tutorial
my movement system doesn't work
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
There are tons on Google or YouTube. Just pick one and start. We don't know what type of movement you want . . .
you think I am here without any tend of finding tutorials? I have found multiple but no one explains what they are doing...
that is why I am asking you guys
what kind of movement are you looking for?
wasd fps
This is the information you should provide so we know that. What tutorial are you having trouble with? Which part is not working correctly? We cannot properly help if you don't give us any information . . .
here, https://www.youtube.com/watch?v=_QajrabyTJc&t=851s this is the video and the thing is I want to know what he's doing I don't want to just copy paste his work thats how I learn
Let's see how to get an FPS Character Controller up and running in no time!
REGISTER with APPTUTTI: https://www.apptutti.com/partners/registration.php?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
LEARN MORE: https://www.apptutti.com/corporate/?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
● Ultimat...
Great Brackeys . . . 🙄
everyone says the same thing 😦
he uhm sort of adds the directions then sets it as a vector3...
i don't know much unity but i know in C# a vector3 is used to store x, y, z coordinates.
public void LoadData(GameData data)
{
transform.position = data.playerPosition.ToVector3();
}
public void SaveData(GameData data)
{
data.playerPosition = new SerializableVector3(this.transform.position);
}
I have this class called Serializable vector which basically takes in a vector3 so that I can save it as json. When I try to load, it sometimes does not update my player position to the point where I saved it. I have to load couple times for it to work. Why is that?
[System.Serializable]
public class SerializableVector3
{
public float x;
public float y;
public float z;
public SerializableVector3() {}
public SerializableVector3(float rX, float rY, float rZ)
{
x = rX;
y = rY;
z = rZ;
}
public SerializableVector3(Vector3 v3)
{
x = v3.x;
y = v3.y;
z = v3.z;
}
public Vector3 ToVector3()
{
return new Vector3(x, y, z);
}
}
This is the class
can someone else help me please? check out message i asnwered to
its because the spawn object isnt higher than the other one so obviously it wont spawn higher
you need to raise the object to the position that you want
then check in LocalPosition not Position
I think I figured it out
first do this to your !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 DID IT
but which code you need? i get the error i wrote in that message when a method that uses the animator reference runs, there's nothing special in this part of code
Go and follow the pathways from the learn site. we are not here to answer every basic unity question you have
the error is saying you are using a destroyed object which you cannot do, so whatever script you have that controls this give that
also the posting code bot is a must
You haven't shown your code or anything
I figured it out myself, It works now
I have to spam the load button for it to work. It flickers between the saved location and the current location
i didn't made any script to destroy animator
well when does this error occur?
well, thats what i dont understand, it does spawn higher
after scene reloading, when player dies scene reloads to restart level
oh i misunderstood what you were talking about, after im done with lance ill get to you
so post the !code where you actually do the save and load
📃 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.
Okay, thank u
either its a bug or you are either destroying the animator and readding it or its null like the error said.
but now that i think of it when you reload a scene it destroys everything then adds everything back in i believe so if you are trying to use the animator the instant your script is on thats probably whats causing it
Right. Here https://hatebin.com/alwyjtsdfq
the error occurs when a method that stops player running runs (RunStop()), RunStart(), Jump, other functions works fine and error doesn't occur
I checked the json file and it saves the numbers correct regarding transform
I'm not suggesting it doesn't but it does sound like there is something wrong with your load logic
can i see the script of which you are trying to access the animator?
to see if im correct
entire script or only that method?
Ah this is pretty straightforward
You're subscribing something to an input handler
And you're never unsubscribing it
That's your error
I.e. you did something like someAction.performed += something;
But you never did the equivalent -=
lets see that script, make sure to use this do this !code. use large code blocks
📃 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.
So the problem is in your input handling code
Can someone please explain why when someone hosts, the first method called is OnStartAuthority and then OnStartClient.. but when someone joins the lobby the first method is OnStartClient and then OnStartAuthority?
hold on, i gues i understand what PraerorBlue is talking about
whoops, sorry
From your first picture, if the platform is the spawned prefab, the EndPosition transform is placed at the top of it; that makes sense as to why the next prefab is placed higher . . .
first time when i used InputSystm i watched a yt guide how to do it and it says that i should write for each action something like:
void OnEnable()
{
someAction.Enable();
someAction.performed += something;
}
void OnDisable()
{ someAction.Disable(); }
Yeah and when you do that you need to clean up too
void OnDisable() {
someAction.performed -= something;
}```
yt guides are for getting you started quick but sometimes they skip a step...
if you show your actual code we may see the real problem. but it's something like this
sorry, i didn't finished my message
and i forgot to write runStop.Disable();
so if you do that it's fixed?
let me try
yes, thanks a lot
i won't even think about this
that this is because i forgot to write one line
Maybe it is trying to load too fast hence the flickering between saved position and the current position
It works fine on my inventory though. I can save and load it without a problem its just the player position.
if you dont share the relevant code how can you expect us to help you fix it?
huh?
https://hatebin.com/pirptjthad this is where I read and write data
that's what it means when it says "has an incorrect signature"
wrong parameter type
you can name it whatever you want
aaaah ok, and what makes it spawn further on the x axis then? the length of the endposition transform?
just logically
so where is that called from?
the important part is the type, the name of the parameter is inconsequential . You can literally name it "bread" and it wouldn't matter
y dont say
https://hatebin.com/mcknhttiqt in here
jesus christ this code screams AI
Not AI i got it from a repo
that probably depends on the pivot of the prefab . . .
I know its bad and you guys do not like it as well so I would never come asking for help with AI code 😄
nah just saw that one part the comment looked sus :p seems fine otherwise
Well yeah I tried hard understanding what it does and comments help a lot really.
on that note. maybe instead of commenting each line, you can just comment the function and describe what its purpose is etc.
but yeah comments are good , use them
Good to know. I will do that.
And where is LoadGame called from. My god this is like pulling teeth
Sorry if I cause any trouble. I just call load game on a key stroke. Checking that key in update in my player script
Save is the same too
you know what I think the problem is
You have the objects multiple times in your persistence List
or you have multiple DatasPersistenceManagers
hi does anyone know this extension??
you have only implemented half of the singleton pattern
its not an extension, its a configured IDE
if you're talking about the sugegstionbox/Intellisense
how to get it
!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
follow the instructions 🆙
oh thanks
aaah so it has nothing to do with the code? the code just spawns it at the position of the endposition and the prefab?
Hm so you think I have maybe duplicates that implement the Interface?
Problem is your Awake, you do not Stop the Start from running if there is a duplicate
It throws an error saying found more than one data persistence manager. But Start still runs you say.
of course, DebugLogError does not stop processing
vscode not showing up
the script still exists and still runs
thats because you did not follow the VSCode instructions properly
https://code.visualstudio.com/docs/other/unity#_install
Start from the top
All right so I gotta make sure to throw an error that will stop executing the script
you cannot do that, you need to destroy the script or it's game object
ah okay I can do that
private void Awake() {
if(instance != null){
Debug.LogError("Found more than one Data Persistence Manager in the scene");
Destroy(this.gameObject);
}
instance = this;
}
It remains untouched on load. I looked for the duplicates but could not find any either.
you really do not need to put this. everywhere it wastes your time and ours
All right I wont do that
Well I tried debugging and the serializable vector I'm trying to get the values from is accurate with whats saved in json.
Could it be that I'm doing it in update? Checking for the keystroke? It somehow runs too fast that unity cannot process or something
Uhh how can I tackle this?
what does the error say?
Cannot convert from GameObject to AudioSource, obviously
But how do I find an AudioSource of that tag?
so why are you trying to put a gameobject in audiosource
I don't want to 😂
the same way you get any other component
why are you trying to assign an AudioSource to a GameObject?
I can't reference it directly though. I'm using DDOL
.GetComponent
Ohhhhh 😲
you should know the score by now, show the code for the keystroke capture
you need to look at what FindWithTag returns. make sure you return the correct type . . .
Feels like I'm dumb and smart at the same time lol
if it's obvious, then you should know what to do . . .
any time you need runtime components you will usually be using GetComponent/TryGetComponent
if you only have 1 of something then sstick to FindObjectOfType directly, no tags needed
Yes. Here I had more than one. That's why I had to
yes
if (Input.GetKeyDown(KeyCode.Space))
{
DataPersistenceManager.instance.SaveGame();
}
if (Input.GetKeyDown(KeyCode.C))
{
DataPersistenceManager.instance.LoadGame();
}
This here. These are in update.
though you should learn the singleton pattern and make a nice audioManager that already has what you need
Well actually... we had deadline today 💀. So I had to rush things a little
But the deadline got extended till monday so now at least adding the option to turn volume up/down
Otherwise, it's implemented and works perfectly fine
can you find scripts with this?
Thank you! I'll definitely look into that 😄
yes that would be an Object
check the method in the Unity docs to find out . . .
i did, it said it wouldnt return meshes textures etc, wanted to check if it would return scripts
Guys.. quick question.
Is
int something = PlayerPrefs.GetInt(key, defaultValue)
The same as:
if (!PlayerPrefs.HasKey(key))
{
something = defaultValue;
}
else
{
something = PlayerPrefs.GetInt(key);
}
Or is one better than the other?
no they're different
because the second one doesn't do anything if the key does exist
oh you changed it
Yeah mb I missed that earlier
now.. they behave the same but the first one is much cleaner and more performant
Just when they think they've got the answers, I change the questions
So I was right all along 👑. I saw a youtuber doing the latter and was kinda confused that why not use the overload?
they probably don't know about it?
Youtubers are entertainers first, programmers second.
Hence top hackers not teaching hacking 🌝
Youtube tutorials are often riddled with errors and bad practices
deletes old videos 
I mean... most code is riddled with errors and bad practices, we're all on a learning journey
Literally. Also, they (most) only really teach one way which I find kinda wrong because everything has different best case usages soo... 🤓
I'm learning ECS right now and I'm sure my code is hot garbage
same situation, and I'm sure mine is too
can i use getComponent<> to get the component without specifying its name?
specifically if theres only one component
you only need to specify the type of the component
but you always have to do that
What do you mean by "without specifying it's name"?
actually they probably do mean type
there's always more than one component
Transform is on every GameObject
No, you have to specify which component you want.
the code has no idea how many components there are until runtime
so it won't know what type you want without you telling it
yes but im saying for example
If i have a gameobject with a single child called "somethignscript", what do i put in GetComponent<> to get the script without specifying i want the component with the name "something script"?
"children" have nothing to do with components
use GetComponentInChildren btw to find it on children
you do GetComponent<somethingscript>() to get that script
Maybe consider referencing through the inspector instead, if applicable.
That looks fine, I'm guessing somewhere you are changing the player position, show that code
yes but can i do it without specifying the name of the script
no
as I said 5 times
It doesn't make any sense
im talking from the perspective of there being only one script
NO because there are other components besides your script
if you don't specify the type, how are you suppose to get the component you want? 🤔
You could do GetComponent<Component>() but then you have no idea what component you're getting. Likely you'll get the Transform
this is not possible unless it's only a Transform
yeah, how do i get the script wihtout specifying the name of the script
you don't
there is always more than one component on a GameObject (unles you don't add any scripts to one) . . .
What would be the point of this?
You could probably use some sort of reflection but I'm not going to delve into that discussion.
you cant, so dont try
its useless
YOu could do:
Behaviour b = GetComponent<Behaviour>();``` but then you can't access any of your script data
only .enabled
ooohhh I think I get what you mean
try looking into deriving classes, maybe that's what you need?
you would be wasting your time if you wanted to not get the type
you can get a base class than can be any of the various deriving classes
I'm not sure if that's what you mean or need but it's helpful knowledge
it's called inheritance
no idea at this point what the purpose of this is

i have a gameobject with a script that has name x
i want the script, can i get the script without specifying the name of the script, BUT specifying that i need a script
that exists where im looking
no, because you need to specify exactly what kind of script you need
the code needs to know what kind of script it is before it starts looking for it
No as repeatedly suggested by others
so its name
a script is just a file that holds a class (which is a type). if a class derives from MonoBehaviour, you can add it to a GameObject. a MonoBehaviour is a Component that when attached to a GameObject creates an instance of that component . . .
On a belated note, this looks a little suspect for a singleton implementation - if instance is already set, you do destroy the new game object, but then you overwrite instance with the script on the to-be-destroyed GO anyway.
Neither Debug.LogError() nor Destroy() will exit method execution. You'd need to return, throw an exception, or put the assignment in an else block
what would be the point of doing this
Can you explain why you are asking this? For what purpose would you want to do this?
sounds like an XY question
It's 100% an XY problem
How is it supposed to know which script you want if you don't tell it which script you want
I already provided a couple answers like this but without knowing why who knows if they're helpful
because scripts are their own thing right?
But you at least need to specify what script you want. What if an object has more than 1 scripts attached?
scripts are just files.
I refuse to answer this question because the fact that you're asking it implies you have no idea what your question actually means
Any answer I give could be technically correct but give you the wrong information
because you are coming at this entirely wrong
i specifically mention that im working with something where every game object that i want to refrence using this has exactly ONE script
its a rhetorical question, im confiriming something
And where, in code, do you specify this?
what are you confirming
so you want to grab all the ones with this script ?
How is the code supposed to know that
It can't just "know" that every object has one and only one script
so why not jsut use that script name
unless you tell it that
Each game object will have more than one component if you're planning to add your script to said object.
As far as unity is concerned, every gam object has a potentially limitless amount of components
and as such, the code is structured around that assumption
is it the same script or are they different scripts
guess what Transform is already a "Script" etc.
If only coding languages could directly access what we are thinking when writing something
they are components, so is any script you attach to gameobjects
different scripts
they would need to derive from a common type or share an interface
they already derive from MonoBehaviour and Behaviour, but those probably are not useful to you
you need to create a base class that will have the functionality you need on all those scripts, then make all those scripts derive from that base class
it's called inheritance look it up
and you need to getcomponent that base class
then and only then you can do what you wanna do
So, here's a question. Let's assume that you could get the one specific MonoScript instance as a component on an object.
What the hell would you do with it afterwards if you don't know what script it is?
If you could do Component c = GetTheOneScriptMagicFunction(); how do you intend to use it
all you'd know about it is that it exists
you couldn't access any properties, functions, or variables on it
because you could only access things that Component had
What I noticed is that whenever I start playing and load. It works every single time.
Does anyone know how to freeze the position of a rigidbody in a script
I do not change player position any other place than in my controller.
did you google it
its like the top result
https://docs.unity3d.com/ScriptReference/Rigidbody-constraints.html
Do note that the constraints are bit flags. If you want to combine them, you'd need to use |, not +
Lookup unity rigid body constraints
imagine that..
access the constraints in code and set them . . .
alr
which tells me that somewhere you are storing a 'previous player position' or something similar which should be updated when you do the load
Hi everybody, could someone point me in the right direction on how to center my player prefab while climbing ladders?
This is my HandleClimbing, part of PlayerMovement script: https://pastebin.com/KuE40FUv
I tried to follow "WorldToCell" and "GetCellCenterWorld", but I wasn't able to reference the grid tilemap in the player prefab, when I tried I'd get "type mismatch" in the editor.
Right now my climbing works and all, but I wanted it to be always in the center of the ladder.
Should I be handling this from the "ClimbingTilemap" where the ladders are placed? And then use FindObjectOfType from the player to call a method that centers it? I'm confused if this is the right way, it seems like it should be simpler.
I am looking into it but cannot find any storing I'm doing regarding the player position. I thought maybe I was actually moving when I press load button which causes the flickering. Unity not deciding whether it should teleport me to the saved location or actually process the current movement. I lifted my hands from the keyboard and stood still when I pressed load but nah on 2nd or 3rd loading attempt it still flickers
your code is all sequential, so that is not the problem. you need to look at ANY code that modifies the player transform.position
I used a boolean to disable the movement if its in a loading phasr. It works okay now
My experiment of lifting my hands up in the air was not reliable it seems
then it is your movement code causing the problem
the sphere is parented to another object, it has a kinematic rb
SphericalShell.GetComponent<Rigidbody>().Move(Vector3.up * 10,Quaternion.identity);
IT JUST DOESNT WANNA MOVE, ive been stuck for an hour tryna make a sphere mvoe im gonna cry
the worst part is im sure ive tried every way of tryna move an object in the book
https://docs.unity3d.com/ScriptReference/Rigidbody.Move.html
So, you're putting the object at 0, 10, 0 every frame
yea but it isnt at 0,10,0 is it
we dont know that
yea
you're not reading what they're saying . . .
How could I possibly know that?
mf how the fuck did i not read the docs
I thought you "tried every way"
too busy yappin here
yea
You're getting a type mismatch because you cannot reference a scene object in a prefab. Pass the reference when you Instantiate the player.
thanks! That worked, instead of trying to reference the grid directly in the prefab, I referenced it in the player object that's in the scene! Do you know if there's a smarter way of doing this centering thing though? I'd do it in "OnTriggerEnter2D" but the collider I get is from the tilemap which doesn't have the accurate transform position of the ladder tile, in fact its position is always 0
!ban 1269754182391300157 spam
daring_wolf_85460 was banned.
quick question-I have a player that is an empyt object, inside the player object I have a capsule and the main camera. Which part do I apply rigidbody for physics to work?
again !learn, And I'm gonna keep doing this until you actually do
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
where are the guys from yesterday? you were being toxic and you still are
how am I supposed to locate exactly what I am looking for in this gigantic tutorial page?
this server is NOT your personal tutorial channel
yeah thats why everyone is free to ask!
Basic Roll-a-ball tutorial explains this. This discord is not to spoonfeed you every little thing.
the channel's name is code-beginner remember?
or can you not read
BEGINNER
You're not supposed to find exactly what you're looking for. You're supposed to get general knowledge of how components work to synthesize them into solving your specific use case
Which part do you want physics on
Yes, beginner, no 'CAN NOT BE ARSED TO LEARN'
the player itself
@steel hull Make some effort to learn first. When you are completely blank slate you won't even be able to understand the help you are getting.
So then that's presumably what you want the physics component on
yes, I am trying to but this guy is being toxic
I am trying to be as polite as possible
So start doing courses or basic tutorials on that page and ask questions that show that you did so.
Fogsight was being the most polite i dont see how he is toxic
I am watching them when I don't UNDERSTAND what I watch thats when I come here to ask
not him
stevesmith or sum
same with steve
So then ask specific questions about the concepts you don't understand. That's the kind of question we're here to answer
uhm wait
was this not specific enough?
wdym you dont understand? does he not show what he puts the rigidbody on
You supposed to do the course work and follow the tutorial.
that is not the way I learn I need to know how things work before applying them to my work
yes I do try them to understand first
but before I move on I need to understand the concept of this discord channel should be it, no?
you can try putting the rigidbody on the empty parent object and see if it works. if not then put it on the child with the collider. and putting it on just the camera doesnt make sense
I did, it didn't work thats why I am here
neither way worked?
I will try to send you a video
maybe you forgot the collider then?
the body falls off
I mean, I answered that. You put the physics component on the object you want physics on
but then the empty object stays where it is while the capsule falls off gimme a min
Well, yes. The object that doesn't have a rigidbody isn't going to have physics
@steel hull What tutorial are you following?
wait let me send tou the link
this is the video
wait the video is coming
Let's see how to get an FPS Character Controller up and running in no time!
REGISTER with APPTUTTI: https://www.apptutti.com/partners/registration.php?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
LEARN MORE: https://www.apptutti.com/corporate/?utm_source=brackeys&utm_medium=social&utm_campaign=brackeyssponsor1
● Ultimat...
guys thank you all but I don't have much time
you need to lock the X Y Z on rigidbody
are u combining character controller with a rigidbody. thats bad
using constraints
@steel hull Where do you see in the video rigidbody being added anywhere?
It just moves on the ground no problem
thats why I am here
I am a beginner
Okay, so, why go off-script?
It's a video about FPS controller. It doesn't interact with rigidbodies
okay then what should I search for? how to give empties with a capsule underneath physics?
Do a proper course on !learn so you won't be trying to do impossible things. Where everything explained gradually.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
okay
Yes, the position will be 0 since the transform you're getting is likely the tilemap transform. I can't really think of any solution which involves using the tilemap, but an alternative you can try is making the ladders into separate gameobjects with regular SpriteRenderers. Then their x position would be your players centering position. Another thing you might want to consider are raycasts, which return a RaycastHit2D which has a point property which you could possibly convert from world position to grid coords and back to centered position.
Right, thanks for all suggestions, this has been very insightful for me
is it more efficient to Resource.Load<Sprite> or to use a List<Sprite>?
this is for a pointer to the next target
hello. ive been trying for a long time to blend two tutorials basically. ive finished one tutorial on a 3rd person character movement using enum states and input actions asset. however im trying to add a new action and its proving very difficult. im trying to add a dash. i planned to just take the inputx and input y and use a second tutorial on how to add dashing into your unity game its proving very difficult to mix the two as im not fully familiar with everything that was done in the third person movement controller as i am still pretty new to game development.
3rd person controller tutorial : https://www.youtube.com/watch?v=otqmsZmP4ZI&t=5s
Dashing tutorial : https://www.youtube.com/watch?v=vTNWUbGkZ58
player locomotion : https://pastecode.io/s/kx5x5wbs
player controller : https://pastecode.io/s/59y633v1
In part 3 of this series, we go through jumping mechanics and animations. This includes distinct jumping and falling states with explicit transitions to allow for dynamic scene interaction.
In this series, I'll be going over beginner through advanced topics for building a complete player controller, both for 1st and 3rd person. We'll covers top...
ThirdPersonMovement.cs - http://www.mediafire.com/file/brnb40r95hvxgna/ThirdPersonMovement.cs/file
Brackey's Third Person Tutorial - https://www.youtube.com/watch?v=4HpC--2iowE&t=1081s
This video, i will show you the simplest way to to Dash in a 3D game using Unity 2020. I will be using the Character Controller component to perform the dash sin...
every day is a new opportunity to re-invent the wheel
oh am i doing something wrong?
nah dw i was talking abt myself lol
oh oh alr
making a fsm rn
I would think that in a broad sense they're equally as "efficient" as they both perform the same work, just at different times.
But this sorta sounds like premature optimization - I don't think efficiency should be a factor in choosing one or the other, unless the profiler suggests as much.
resources.load is way worse from what i've read (don't remember the details though)
Not enough information
Resources is worse yes for performance but its something you really do once at the start.
You cant really compare it to a list though, as you still need to populate this list somehow
Trading a performance cost for development convenience is sometimes a worthwhile choice
Especially for a one time cost
In fact we make that tradeoff all the time by writing code in high level languages instead of assembly
Very good point
oh no, its not a one time thing.
this pointer shows the direction and icon of the closest NPC, so it would do this several times depending on the player's movement
i think ill stick with the List for this
Well the resources call would be a one time thing (per resource needed, per runtime)
Then you cache the return value
You would do resources WITH the list
The real question is inspector references vs resources. Not list vs resources
(Also there is Addressables)
Is there any way to set an order or priority of how objects are started in a scene? I would like the void Start() of a certain object to be before another.
Is this a use-case for Awake() ?
There is a way but better practice is to use awake and OnEnable
how do i detect if debug mode is enabled in the unity editor via code? I figured it would just be
#if DEBUG but it seems DEBUG is always defined even if you have debug mode toggled off in the unity editor
Is there a preprocessor for this at all?
i guess not
interesting
What are you considering "debug mode"?
Missed the screenshot 👀
note that having the debugger enabled is not related to the Debug vs Release setting in your IDE. in fact that setting has no effect on the code's compilation because it is the unity editor that actually compiles and runs the code
Yeah I seen that what I did was created an editor script that sets a scripting define symbol in the player settings when CompilationPipeline.codeOptimization is debug
hey, im using visual studio as me IDE, and up until now its been working fine, but today when i went into it its not working properly, anyone know what might be causing it
regenerate project files and restart it, if it still isn't working make sure it is actually configured. there have been some instances of the external tools setting in unity being reset so make sure that hasn't happened
tried regenerating the project files and restarting, didnt work, then i went through the configuration steps in #854851968446365696 and it still doesnt work
show your external tools settings, the package in the package manager, and the workload in the vs installer
actually before all that, just screenshot your entire IDE window with the solution explorer visible
right click the project in the solution explorer and select Reload With Dependencies
that fixed it, thanks
what was the issue? so i can avoid it in the future
the project simply wasn't loaded. there's nothing to "avoid" it doesn't typically happen, but if it does you just reload it
regenerating project files and restarting should have also reloaded it, but sometimes that extra button click is what you need 🤷♂️
https://pastecode.io/s/cimx9w5w
https://pastecode.io/s/uz7s83d3
apparently "isRotatingToTargetHash does not exist in the current context" but im pretty sure its supposed to be fine? ive called it from the player controller script and ive set it the exact same as the others. its referenced at the top with a string to stringhash like i did with the rest of them?? whats wrong
how can i make the particle does not disable when my player flip
Your variable is named isRotatingToTarget, not isRotatingToTargetHash
we need to see some code
Where do you define isRotatingToTargetHash?
public bool Loop = true;
bool firstStart = true;
private void OnEnable()
{
if (Loop && !firstStart)
{
Debug.Log("Test a function only once");
}
}
private void Start()
{
if (Loop)
{
firstStart = false;
this.enabled = false;
}
}``` heres a fun one.. found an old script i wrote when i *FIRST* start learning.. lol its a debug button (click the enable button on the script to call the function)
How do I force a serialized unity event to actually use the value it's being invoked with rather than whatever nonsense is in the inspector (and ideally remove the parameter from the inspector entirely)? ie ```
[SerializeField] public UnityEvent<bool> OnEnter;
public void OnPointerEnter(PointerEventData eventData)
{
var b = true;
Debug.Log("Pointer Enter: " + b);
OnEnter?.Invoke(b);
}
public void OnPointerExit(PointerEventData eventData)
{
OnEnter?.Invoke(false);
}``` when tested the OnEnter does not actually pass 'b' but instead whatever the checkbox in the inspector is set to
EDIT: For anyone similarly annoyed, check the method dropdown in the inspector and check it isn't using static, which seems to completely disregard inputs without any warning.
now im using reflection and Button Attribs (came a long way)
the inspector values take prescendence over values in ur script..
if u (reset) ur script in teh inspector it'll go back to the original values
why u using a public Event if u dont want it exposed in the inspector?
I don't have 'original' values, I just want it to behave like a normal C# event and be completely dynamic
ahh, i see
I want it exposed, I don't want to use the inspector to do anything but grab references for convenience
You need to mark the event as Dynamic in the inspector
Yeah that did it
theres a way to do this i cant remmeber tho..
[SerializeField] private UnityEvent<bool> onEnterUnityEvent;
public event UnityAction<bool> OnEnter;```
something like this maybe?
No you just swap the method reference in the inspector
dynamic will respect the input, static just uses whatevers in the inspector
[SerializeField] private UnityEvent<bool> onEnterUnityEvent; would using private serialized change the result any?
that's just scoping, it shouldn't affect anything
ahh ur right ur right
events outside my comfort zone.. but i need to learn them. so thats why im even replying lol.
but i understand the issue now, that was more than when i first read it
Unfortunately, Unity's inspector doesn't allow you to completely hide parameters for UnityEvent methods while still keeping the event exposed. However, the dynamic method selection in the inspector solves your main issue.
I just use a wrapper for vanilla C# events whenever possible, so this is the first time in ~10 years this has come up
yea, thats all i got from the threads im lookin at lol not really a often asked question i suppose
or i cant word it corrrectly
Yes, if you select dynamic you won't see the parameter in the inspector (since it's being set when invoked)
i'll remmeber that. ive never used the inspector to pass thru variables..
can'y you only pass 1 parameter via the inspector?
ahh, its a design choice
With default Unity events, yes . . .
ive never heard the term "vanilla c#" until just now
i kinda dig it 😄
w/o unity's ~~api ~~ library/namespaces i cant code c# soo..
lol ¯_(ツ)_/¯
Custom Unity events can have multiple parameters, but as mentioned, you won't see those . . .
technically it is an api
imo unity events in the inspector are clutter-some af
I've heard a few people use vanilla c# but most say POCO (plain old c# object) . . .
i just call them c# events vs Unity events
aye, ive heard POCO befor.. i avoid using it cuz ppl reply wdym
aren't they the same? in the most generalist sense
No
UnityAction is similiar to c# action
UnityEvent is specific to inspector/unitys event manager or whatever it is
I agree. I have a ton of custom events for some things. You can clump them under an arrow with custom inspector/attribute . . .
Unity events are serializable, which has a lot more powerful implications than your standard C# event
You can't think of any extra benefits there?
UnityEvent is handy (especially for UI) because it's extensible and shows up in the inspector. But iirc performance was (at least at some point) worse than C# events, and showing up in the inspector is a pretty major double edged sword to begin with (though obviously can be avoided with an attribute)
Kinda: C# events are just through code, and Unity events appear from the inspector . . .
You can't tell which objects are listenting to event, its messy
Serialization allows things to appear in the inspector...But the main purpose of serialization isn't just to make things appear in the inspector. There's much deeper implications to the power of serialization
106 files and i dont use a single action or delegate.. they're all UnityEvents
speaking relating to events btw
I know there is benefits to serialization duh 😛
But is that because you really like UnityEvents or you just really don't want to deal with delegate syntax
lol.. ya, the beginner response is "they expose things in the editor"
but we all know they're much more.. serialization just the word gives it away
i was taught 1v1 for my switch system.
"organize this textfile" 😛
and they taught me w/ UnityEvents for some reaosn
Ultimately, everyone should probably just learn all of it at some point, but UnityEvent is probably more useful for people who want to stay in the unity ecosystem and especially those who tend to handle data through the unity editor
the decent part about UnityEvent they can also be listened in code directly so you dont have to use the inspector (dealing with the UI events like OnClick)
What do you mean? onclick can also be set in code
thought you were implying it couldn't
one thing im missing in this script is.. i have Add/RemoveListener
naaa . My designer friends like those inspector goodness though
but normally im used to seeing += and -=
😄 🤣
Honestly, I like using both. Unity events are great for setting up reactive stuff on the same GameObject . . .
Yeah, they have persistent and non-persistent listeners. There is a difference to understand . . .
i think thats what happened to me..
he wanted everything in the inspector 🤮
I think a lot of tutorials push people towards using the inspector and scriptable objects to hold data just to get things done quickly
i despise when people use ScriptableObject just so it can not go on a gameobject
theres gotta be more to it..
that seems sloppy.. but who am i to say..
I still have never encountered an actual use case for it in all honesty
anytime ive used a ScriptableObject.. its directly referenced via the script anyways
I prefer to keep data in csvs loaded from streamingassets
hey, ive been struggling to fix my player movement, my player keeps getting dragged and moves by itself a lot. This happened after i added in an animator cutscene and im not sure why, anyone got any suggestions ?
The inspector is there to help design your game, and being able to control how events are hooked up in the inspector rather than hard-coding it is actually a pretty nifty way to handle dependency inversion/injection
i use classes and structs
gets the job done ¯_(ツ)_/¯
not without seeing some !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.
whats handy about UnityEvent though is the same drawback it has, you dont have to modify 3-4 scripts to listen to event. If you need to interact with specific components without adding so many references. Good for quick prototype but in the long run..
UnityEvent has its place, for ui its about as good as it gets honestly. Saves needing to make tiny scripts for every little thing
I just put it all in UIManager 😛
well, the way mines massively inspector focused.. i just assign reference via it.. and i never really have to worry about what listening.. only things within the IInteractable is controlled
I've just had enough bad experiences with the inspector losing references on older versions of unity that I don't trust it to hold anything important
Back with the old unity collab it felt like every pull had a 50/50 shot of some random prefab disintegrating
also noticed the invoke order doesnt seem to be specific order ?
Ive been using unityevents for message brokers. Like I'll have a Hittable component that has an OnHit unity event. Then I can hook up the listeners for any specific hittable object in the inspector. And then stuff that I don't need to think about when I'm not in code, like an enemy manager listening to all of the instantiated enemies' OnDeath event, I'll use c# Actions for.
i just hate having inspector values having full control.. soo many times it would be a test i did and forgot to change back my inspector values.. and then i check the script.. and the values inside the script are WAY OFF since i made em a long time ago.. and then im stuck fine-tuning everything
soo. private all the way.. or i tend to use [ReadOnly] alot now
yeah same experience, I don't expose anything these days unless actually needed
Yeah its good that case, but hard to traceback later on. For asset though i would rather use inspector so its "plug and play" (speaking strictly events ofc)
do i just send the link here
hits Reset in the context menu -> every value changes to something ridiculous -> throws pc off the rooftop
yes this is a code channel, thats what its for
yeah just put the code on hatebin or whatever and post the link here
Am stuck pls I need help .
How do I shoot in unity I want to understand not to copy and paste any book or guide
attn Hatebin has a 50% success rate
Way too big a topic
so only happens during the cutscene?
a nifty little debug w/ a passed reference in the context is a solid way to keep track
but remmeber to remove em all b4 build day
or i guess the stacktrace w/ a normal debug would be enough
for some reason it started happening the whole time im playing now not just when the cutscene happens, only happened after i made that cutscene
- Point in direction
- Instantiate thing, move it forward.
Or - raycast
you can use a directive to avoid needing to edit things
could u elaborate?
none of the code you sent moves anything, we need more context maybe show a video
i tend to put a script on the bullet/projectile that just moves it forward AddForce(transform.forward) or AddRelativeForce(Vector3.forward).. and then just instantiating the bullet w/ the rotation im expecting it to point.. (once it spawns it handles itself and takes off)
even this.. i forget this thing exists everysingle time
ill share a video gimme a few
you'll want to read through this https://docs.unity3d.com/Manual/PlatformDependentCompilation.html , but basically you can exclude code that's irrelevant to a production build pretty easily without needing to go through and muck around
ohh i seee..
sorta like the #if editor type tags
imagine putting around every debug.log
ahh nah, nvm thats not similar at all..cuz those would still be there.. just ignored.. or do they get stripped out?
thankyou mate.. i'll give it a read 👍
editor classes don't get included in builds at all iirc?
naw
ya editor classes excluded irrc
I think the whole assembly gets excluded
yea, everything within an Editor folder gets droppped
stripped out if the condition isn't true
if you wanted to keep it when compiled you'd use Application.isEditor or something like that
though i'm not sure why you'd ever do that
// Editor-only code here
#endif``` do too apparently
anything with #if is a directive
im learning stuff today 🥳
now go learn C# action/func/pred 
delagate
I really, really wish that the big tutorial channels/educators would focus more on teaching delegates
they're so incredibly useful
but most self taught programmers seem to not even know they exist
Give me a link
delegates are OP
https://gamedevbeginner.com/events-and-delegates-in-unity/ heres a solid TXT file
the 👁️ pattern
ehh, i should probably avoid classes named Action then i guess 🫣
edit - welp, time to refactor some stuff real quick
using Action = System
See, my issue with that is that, like most info on the subject, it focuses on delegate itself. Obviously foundational knowledge, but pretty rough as an entry and with tricky'ish syntax. I've found it's much easier to get people started with Action
delightfully cursed
I dig the yellow brackets though
Also using capitalized names in events can get you in trouble. For example, if you have an Action that named "OnXXX" and there is another method named "OnXXX", it will conflict. I prefer the non-capitalizated one like "onXXX"
yeah the unity ones don't cover too much intermediate / advanced c# in good detail
they expect you to kinda know all this
delegates are one of those areas where i think it's most helpful to work backwards honestly
i can do that.. already do that w/ my debug class and my random classes
and understanding predicate is really helpful for using linq
ahh, never thought to use camelCase on those
or setting up your own extensions
Idk if I would do it for Action thats too close to home 🫣
linq is a scary word to me
linq is my god
it's also probably singlehandedly responsible for 90% of my cpu time
Linq is good but it creates a lot of garbage and garbage is an enemy for game developers
hate the new sytax they try to use for it
new syntax?
depends on which part of linq
yes its more verbose, i hate it
Naa it already creates it's first garbage on conversion of IEnumerable > XXX.Enumerator
It doesn't really matter 99% of the time, and it's easy to just convert everything away from linq when you're done and ready to optimize
well not new.
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;```
ohhh
I shoudn't say "verbose" but too much close to english, me no likey
wasn't that to make it close to some database query or something
feels pythony
public class Operation : MonoBehaviour```
Well most people know events, which is really just a keyword using for delegates. It's not some hidden secret, people just dont know the name and delegates without event isnt really used much in game dev unless you're working on something unique
I hated databases always and i agree it is uglyyy
yeah its like SQL or any other weird query lang
ill keep my . chains thank you very much
I'm not really sure how you develop much of a game without callbacks, which require knowing delegates, or at least Action. Events are a pretty unique flavor
var methods = monoBehaviour.GetType().GetMethods(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic);``` i got some python-esque code i wrote yesterday 🙂
not quite the same..
not so much the indent
good luck with the error logs 🫡
lol, its my first dive into reflection/editor attributes
What im saying are people know about delegates, they just dont know it's called a delegate lol. Because they use 'event Action' all the time which really will be the most common usage
can someone please help with hand coding😭 the hands on the character is funky
If you want a fun little way to learn
var results = strings.Where(s => s.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList();
var results = from s in strings
where s.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)
select s;```
which do you like ?
try making a console to control your project
thats all im into bro!
oh like dis?
99% of the time i run into issues, its because i forgot the 'ordinal ignore case'
I tried it before. I ended up using someone's extensions instead. The API was like designed by a team which they are just created their needs only
@crude solstice
can only send a short video of what happens after the animation
is that fine
somethings better than nothing
anything helps as long as it shows the problem
oki
yeah, now use it to execute methods via reflection
one mine then itll show the dragging n automoving
lets dooo 1 step at a time boss man 🤣
i add them @ runtime
also if we're going with shoving python into C#, my entry: https://hatebin.com/bojwzoadeb
i believe my static commands do use reflection
but the shell part was robbed from a github
this is all i could send cuz of the limit
weird.. theres a huge limit here.. 100mb + ircc
mine says 50 mb limit
alrighty. now explain. what is it that u wish to happen.. whats not happening.. and what are we lookin at
the first 5 secs is automoving
https://streamable.com is good for big files
second five is when i tried moving right its like somethings blocking me from doing so
I love streamable so much
what is the rigidbody speed when you're slowed
check the velocity
you can also use physics debugger
see if there are colliders or anything there ?
ill check now
havent used debugger before, is that okay?
also another separate issue ive been having is i cant start a timeline, like i press play with a component in and it doesnt run at all , even as a preview
hmm seems like your velocity is matching your movespeed
the normal movement speed is faster than in the clip
the clip is with the drag thing like preventing me from going right and left
i can show the normal movement and how its meant to look if thatll help
are you limiting speed in any way?
i dont think so, i didnt touch the movement scripts at all
before i made my cutscene it worked smoothly, but after it, its been like that
can we see some movement code
the rigidbody is probably fighting the transforms with the animator
or any code that affects velocity
maybe
im p sure no code affects it
ill check
well your movement code should affect some sort of movement
!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.
transform.rotation * new Vector3 🤔
this is a different way to apply movement to a rigidbody 😅
sorry
first unity project
you are not in trouble or anything lol
looool
also any ideas on why this could happen ?
do I need to change this ?
Can you show the inspector for the object when it's misbehaving?
i fixed it
was the dumbest thing aswell oops
now just need to get my timeline to work
what was it ?
i didnt have freeze rotation z ticked
i had a tester world with x and z ticked n movement worked there
did the same for this n it works now
anyone know the visual studio shortcut key that turns my mouse into a yellow block that replaces writing
really bugging me
insert?
Not a VS shortcut
It is from the operating system itself
probably why i couldnt find it then
i've used SOs to hold a static event and method. this allows me to subscribe and invoke the event without needing an instance or a singleton . . .
those are the cases i think ive heard to avoid lol
but who knows.. the misinformation is real sometimes
can you do Class : SO, MonoBehaviour ?
nah . . .
hello everyone, so im trying make obstacle on tilemap, already use tilemap collider and still not working
whats not working? the code?
im still can pass obstacle
i have a DamageTextService SO that allows one to call OnDamageTextReceived(DamageTextArgs args) to invoke an event that displays the damage text to the screen . . .
it's how other systems can talk to it without needing a dependency . . .
ya, i mean it makes sense.. i myself cant see nothing wrong with it.. i might think of that for my own purposes now.. at some point in my journey lol
you've done a lot of things though. bits of pieces here and there that add up . . .
is obstacle got a collider on it? how u intend on you getting stopped by it?
im debating on whether this code related.. or belong somewehre else
yes already collider tilemap, but im still can pass through
how do you move the player??
The PLAYER has a collider too?
i don't get it
I just wanna ask. I have a "private transform target" in a detection tower and I wanna use it as a reference so that another game object can target the object that is called, specifically an enemy. Do i just change it and call it like public transform target and declare it on the other game object??
yup
📃 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.
is it transform.position = .. aka translation..
Show the code you use to move the player
No.
- does it have a rigidbody?
- should it?
.. just a few questions that eventually need answered..
@carmine lagoon The name of the variable is irrelevant.
See here
https://unity.huh.how/references
just show the code and we'll know most of it
aight wait
thanks~
you need to allow other scripts to access the field. since it's private, outside scripts cannot access it. you can create a get only property that allows other (outside) scripts to access it but not modify or assign it . . .
so i make it public and put it in serialized references right?
then use getcomponent?
no, no, no . . .
create a property called Target with a get accessor that returns your private field . . .
then you need to figure out how to reference the script to access the property (using the link from Aethenosity) . . .
okay okayyy, thanks
hey guys. I have 2 scripts in one object I have. The second one. WaveController. I thought that just creating like Private WaveController _waveController, I wouild be able to have access to it as it is already inside the object. But it is giving me null execption. If I turn it into serialized.. I cant drag the script into the field on inspector.. what is the fix for that? Thank you
thats code
I would change private to public if you want Spawn Manager to be able to change and use Wave Controller via code, also does it just not let you drag it in? it should allow you to drag it in if thats all you done to it
it doesnt. I removed the serialized and I am using on Awake cs _waveController = GetComponent<WaveController>();
and its working now
Transform.Translate does not respect physics (like collisions)
Look into CharacterController or Rigidbody based movement
Or recreate your own physics using things like raycasts
so imma just make a get property in the second gameobject, am I right?
Nevermind pedro. I see
I was dragging the script it self but now its working. thank you
for example
get { return target; }
thank you
No, the property is on the same script with the private field; the property returns the private field . . .
ohh okay. I think i get it now. I'll call another variable in the detection tower which is public then i'll make a get property code so I can call it out in other game objects
is that how it works?
!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 don't really understand? why can't I change the transform of the viewport of a scrollview???
Hey guys.. I have 2 classes. 1 - WaveController, 2 - TimeController. Inside wave controler i checked with Debuglog, and time is always starting at 0 and working fine.. but the game is going inside my IF statement where it says time need to be greater or iqual to 120 already at the start of the game. What could it be. ```cs if (_timeController.elapsedTimeGet >= _addTwoMinutes){}{
_waveCount++;
_addTwoMinutes += 120;
}``` Full 2 classes code https://paste.ofcode.org/XDG9gDYYjrsjrGEec6SNAa
wdym you always start with 120
wdym?
like this?
https://hatebin.com/pkvviiwlqo
_addTwoMinutes I always start as 120, but the if says if the time is greater than 120 go inside the if. and the time starts at 0.. so it should not go inside it until the time is 120.
how did you tets its going inside?
where are you checking elapsedTime value
try this
if (Time.time >= _addTwoMinutes){}{
_waveCount++;
_addTwoMinutes += 120;
}
debug.log for _timeController.elapsedTimeGet, it shows correct the time starts at 0 and it goes up normally as time should workl. Debug.log for _waveCount++; and it increased like crazy since the start of the game as well _addTwoMinutes, and the only place they are incremented is inside the IF
Same result
Can you possibly send a screen shot of the whole function?
omg
remove one set of brackets
I didnt see that
oh wow
hahahaha
Lol
now it works hahahaha
not a fan of that style of brackets
Amazing!
yea... programming things lol
what do u recommend?
the c# standard tbh
I love those brackets
{
//
}
i do it like this
if
{
}
haha yeah.. crazy stuff.. I was looking for logic error and it was a misstype error..
That is called cozy curlies, where you have the bracket inline with the if. It is not preferred according to c# standards
do whatever is comfortable for you
I find it ugly as space consuming. I can try using it and get used to it.
They are much more compact like this
void HelloWorld() {
}
now go have a look at Code Monekey's timer tick system where he explains how to use events to do same thing
thank you
can someone teach me what do i do to get the value of the public Target? Thanks
which value?
classReference.Target
Just basic dot notation
thanks~
do I use this at the second game object
I dunno what you are asking
But if I am right about what you mean, yeah, other objects need the reference to the class instance
If you are calling it from INSIDE that class, just write Target
In your script why are you trying to set Target to target?
you can just use target
ohh wait. so basically the code I sent is like a detection tower. I wanted to use the target within the code so that it can be called out in the other game object(basically which shoots the target). That's why they told me to make a get property.
It is a property, best to use it instead of the backing field, even inside that class
I see that
So this
#💻┃code-beginner message
You don't ever want to directly reference the backing field
If you go modify the behavior of the getter or setter, you would have to change a lot of code in the future
It is the whole point of making it a property
Why would that be an issue?
thank you~~~
Why cant he just set the property to public?
so that it is only modified within that script
The property IS public...
the getter is public
the backing field is private so it can only be changed in that script
Looks like the setter is too
yeah in this case they (OP) fdup the point of props
Could just be an autoprop
You can just serialize the field, right?
yea but I think the point here to find it at runtime not set in inspector
How is that relevant to accessing it from other scripts? Which is what they are trying to do
Yeah, for just the inspector, may as well do a serialized private
no clue how they wrote this whole script without knowing how to access it from another script 😅
I didnt know he was trying to get the value from another script
Honestly, I wasn't sure at first either haha
anyone know how i would get this to actually show up green
!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
You're repeating the exact same code. Just call ResetTime in Start . . .
it's my first time to use C# never really used it before T~T
you're literally accessing Props and methods through the whole script
so i'm learning everything rn
You may wanna do this before continuing in unity
https://www.w3schools.com/cs/index.php
Then !learn after
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
The junior programmer pathway specifically
thank you guys
Honestly, I watched the Unity beginner and intermediate tutorials, read RB Whitaker's C# tutorials, and was good to go
As long as you follow along and manually write the code yourself, you'll understand the concepts and terms . . .
why would you not use an event system for a timer functionality?
You can save performance
I mean, you certainly can. There are a bunch of ways to do it
Why not use Tasks? Why not this or that?
Why would you? Is there some special timer functionality that I never heard about?
just curious why you and nav reacted with not like this
Because you recommended Code Monkey
At least for me. Not gonna speak for nav
oh is he bad to reccomend?
I strongly dislike him, and brackeys, and code bro, and that one called dave something that I keep forgetting
not a fan of the videos
I tend to watch them all, glean the good stuff and reject the bad stuff
being passed off as "clean code" when its not
its all over the place if you ask me, but clearly it works for them so whatevs
ok fair enough, just thought the idea of a timer on events was somehow bad
nothing wrong with timers and events
the System timer has a built in event
https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.elapsed?view=net-8.0
Not bad, but certainly a new level of knowledge I don't want to get into. I generally try to fix what someone has, not completely recommend a different method (unless it is REALLY called for, which, sometimes it is)
ok, was more thinking hey if you want to try expanding your horizons, try this next
hey guys. I have a simple code here. I have 2 objects.. both with circle collider 2d.. both with rigidbody 2d Dynamic. One is the bullet the other the enemy. I am just trying first to achieve a simple task. My enemy class name is CircleEnemy and the bullet class is PlayerBullet. Both have tags with the same name of the class. In the bullet script I just have that: private void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("CircleEnemy")){ Destroy(this.gameObject); } } The bullet hits the enemy and bounces instead of being destroyed. What Am I missing here?
Destroy(this.gameObject); destroys hte current object that script is on
exactly.. it should destroy the PlayerBullet
But it doesnt.. and the script is on the PlayerBullet.
private int _playerBulletSpeed = 2;
private int _playerBulletDamange = 1;
void Start(){
}
void Update(){
}
private void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("CircleEnemy")){
Destroy(this.gameObject);
}
}```
perhaps you want other.collider?
I have another game that I made and it works there, i just did the same.. there works but here not. I am missing something I cant find
Oh totally. I wasn't meaning that as a dig against you. I have so little energy lately I just have no desire to get into it sometimes haha
Might need to use OnCollisionEnter
Add a debug to see if OnTrigger is even called at all
The Three Commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 2D Rigidbody on at least one of them
(From digiholic)
Instead of trigger (depending on the collider settings)
Will try that because i did that in another game I have and works find the same way I did here. let me test.
AHH YEAH that is it.. the isTrigger is not ticket.. let me test .. that should be the problem
yes that was the issue. Thank you. I forgot completly about that
If you would rather it not be a trigger, then iLikePizza's suggestion is best
Got it, thank you guys.
Litterally, you can't put too many debug logs in your code, they only help you, comment them out after resolved, leave them hang around a while, remove them later when you are thoroughly convinced you understand the issue
True.. OnCollisionEnter, I do not need to check for Tags correct?
It just fires whenever .. or whatever it collides with a collider i imagine.. that will be more random.. trigger is more specific.
You still would need to validate the collision
The only difference is that it would be for neither object being a trigger
becase CompareTag is not allowing me to check with OnCollisionEnter2D
collision.collider.CompareTag
are you sure you're not trying to do it on Collision type?
Simply have to access the collider from the collision struct
See what I wrote just above?
Yeah, ok thank you!!
if(other.TryGetComponent(out PlayerBullet playerBullet))
...
playerBullet.stuff
etc..```
no need for tags
Got it, thank you!! ❤️
btw Destroy (playerBullet) you're only destroying the component not the gameobject
hello I saw this one video about this guy making a game that deletes itself when you die, just curious how would you do it? I would like to try / understand how he did it, because from what I know, it is not possible to delete an application that is running, but you need it to be running in order to detect deaths and activate the script that deletes the game
https://www.youtube.com/watch?v=nIdO1Z8mD7Q 9:22
Copy the app to a temp folder. Run it from there. Delete the "main" game folder when you die. Smoke and mirrors like everything in video games
I can't seem to get my 2d collisions to report. here's a screenshot showing the code, the project settings showing that the layer collides with itself, and the collider2d and rigidbody 2d settings.
ah, just realized I am comparing tags and looking at layers, but even after fixing that no dice unfortunately
Hey guys. More newbie questions for you. In my past game I used scriptable object to manage my enemies Damage and Health. Worked fine.. Now I am trying different ways to see if that works too. I have this code for the EnemyHealth where it says if the enemy health is 0 or less he will be destroyed. It is working fine. But the issue is. I am using it on 2 dif enemy prefabs. So when I hit the first enemy all the other enemies in the screen that were already instantiated will be 0 HP too. Is that a way to fix that simple or I really need to use scriptable object to achieve that? https://paste.ofcode.org/SaADfF2peHfRCi3vQiVwEv
I am confused about the issue. Let me look at the code more, but to start with, you should absolutely NOT use scriptable objects for current health.
Treat scriptable objects as immutable
I used for my past game worked like a charm even tho prob is not the correct way. But I hated to use scriptable objects to be honest and I was trying a more direct simple way.
Show EnemyHealth component
so "hit" doesn't print ?
Did it work even in a build?
Also, even if it works, you are still making a whole new asset for every instance of health. It is terrible and should not be used
why is there a rigidbody on a image component
What's the other object you're supposed to be colliding with?
because I am dragging and dropping UI elements within the canvas, they are hitting each other in theory
imagine a MMO hotbar, I am building the "drag to another ability to swap" part of that
Why would you build that with physics?
That's not right at all
I wasn't aware there was another way
Do you set EnemyList in any other script?
That is an.... interesting name for health
Physics is for game world stuff, not UI. Use the event system drag and drop stuff
Yes, in my SpawnManager where enemies are being spawned.
Then that is the issue
Show that script
I am actually using event triggers for drag/drop stuff
how would I check if I am hovering over the right place though if I don't check for collisions?
So I should have access to this in SpawnManager I guess: enemyPos1 = Instantiate(_enemyPrefabList[0], new Vector3(randomPositionXXR, randomPositionYR, 0), Quaternion.identity); _enemyList.Add(enemyPos1);
With the event system pointer enter event
dont forget to disable raycast target on the thing you're dragging so it doesnt mess with your raycast dropzone
What is _enemyList?
That is something different than what I was asking about
I wanted to know about the EnemyList property you made in EnemyHealth which sets _enemyHealth
Line 26 of the script you shared
Ok, I'll give that a try, thank you!
Physics and UI don't even live in the same coordinate space. It's just completely the wrong track. Look up some drag and drop UI tutorials
Oh now.. that name is wrong.. there should be public in enemyHealthGetSet my bad
Ignore that name that is there now.
public int enemyHealthGetSet{ get { return _enemyHealth; } set { _enemyHealth = value; } }
I would not use the words GetSet in all these properties at all. But that is neither here nor there
I believe that is the issue.
See what happens when you comment out that line
I am not using this Get set anywhere for now.. just commented nothing happened. I am controlling the lost of health in the same script..