#💻┃code-beginner
1 messages · Page 582 of 1
what is rayhit hitinfo
Perhaps you are unclear on what this means:
out RaycastHit hit
You are declaring a new variable here.
- The type of the variable is
RaycastHit - The name of the variable is
hit
In your code, you declared a variable named rayhit, with a type of RaycastHit.
You then tried to declare another variable named hitInfo with a type of rayhit
These two rayhits have nothing to do with each other. The first one is the name of a local variable. The second one is the name of a type (which does not exist)
hitInfo is the name of the parameter of that method, its not what you need to name your variable or put that there
ok no errors, gonna see the output now
now i feel so stupid after annoying u all that much
you can name your variable hitInfo, of course
it's just not mandatory
i was fairly confused reading that
so uh
does anyone have any leftover patience to help me with a (what i hope to be) simple fix?
ask your question and someone might be able to help (:
This question cost you 4% of my patience
Just ask :p
okay but don't just Debug.Log the hitinfo, that will debug the object itself and not values of each property (I don't think unless you use debugger)
Debug the specific collider/name you hit
that was just kind of entertainment
i think output is joking now
The default ToString() implementation just gives you the type name
why is it yellow
I just said that would happen
You will need to log a specific member of RaycastHit
playmode tint
oh sry
such as collider or gameObject
If you do not know what I mean by this, you should ask (:
also when you click the Pink hyperlinks they explain
pink hyperlinks?
the what?
oh that
you can inspect the RaycastHit type, yes
you can also check the Unity documentation for a list of its members
sure, what does it mean... xd
and its still same
A member is anything that's part of a type. For example, RaycastHit contains a bunch of fields -- variables that are members!
what did you log?
after adding the .collider in the end of hitInfo
Classes have members, either variables or functions you can access with the dot operator: .
You can view the members of a class by looking it up in the !docs
public class Foo {
public int field;
public int property => 123;
public int Method() { return 321; }
}
fields, properties, and methods are the most common kinds of members
Then your raycast has not hit anything
then why is the player stuck
ik that part
send the updated code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
well looking a hitInfo when something is not hit makes no sense
A tool for sharing your source code with the world!
anyway. i am having issues with movement and the camera. I have a 3rd person game and its basic WASD movement. I have it set so if the player moves their mouse, the camera and the player will follow the position of the mouse (like in marvels rivals) but for some reason it wont look up or down.
A tool for sharing your source code with the world!
So, why are you checking what object the raycast hits, only on the condition the raycast has hit nothing?
btw you shouldn't multiply your mouse inputs by TIme.deltaTime
because its supposed to point if its hitting smth so player can move? im not sure myself why im doing all that
can you explain why? i thought that was the best course of action so itll be more smooth
Right now, you are setting canMove to true if the raycast hits nothing.
Then, you're checking if canMove is true, and if it is, logging which thing the ray hits.
Do you see how this doesn't make sense
because Mouse inputs are already framerate independent
Time.deltaTime is meant for keep things consistent through different FPS.
oh okay didnt know that thank you
oh, i will just add ! to canMove or make just like that Physics.CapsuleCast
as to the rotation problem , debug your xRotation values
see whats happening in the inspector etc.
no output... does that mean the player is hitting nth? why is it not moving then
ill try it again
also mixing new input system with old input system is weird lol
why are movement keys in InputSystem but the mouse uses Input class
dude its been rough. i havent ever used the input system so when i wanted to use it i kept getting videos from like 3 years ago and sometimes itd work and sometimes it wouldnt
alr. cause mouse you can also use Vector2.ReadValue
see thats what i had before but then the camera wouldnt follow for some reason
ill update the link with the previous code
so the problem here is in another script?
thats not what they said
no one said anything (I can't see a message replying or anything)
this one ?
#💻┃code-beginner message
i changed the value and made it not !
updated
show what you wrote..
if its not logging then the conditions arent true
go into playmode , open the Physics Debugger and set it to Queries , lets see where its going
this? debugger?
thats not named Physics Debugger is it?
its named Debugger
i cant see Physics Debugger
oh so because it has debugger in the name you figure, just grab any
Window -> Analysis -> Physics Debugger, also please google things if you're not sure where to look.
ask if the search yields nothing (unlikely)
i think i lied ngl i didnt have it set for the mouse
wat?
when you said that i could use readvalue<> I thought i did but i didnt
okay, well dont worry about that rn. Did you debug the values ?
i dont have Rigidbody or the other thing
mate. please read carefully when i say something
is that the Queries tab ?
oh there are tabs, my screen is just black in some areas i couldnt see it
what after it, it says Spheres and stuff
but besides that, i still dont know what to do with the camera. everything rn is moving except for the y axis on the camera but im not too sure how to implement a fix into my code
ok now you dont need to touch anything else, GO Into play mode and enable gizmoss
okay
screenshot in playmode , lets first see where your capsulecast goes
you want Y axis to move? I thought you said its not looking up and down
is this in playmode ? make sure you smash some keys for movedir
cause I aint seeing a capsulecast rn
its playmode
make sure movedir has some values so we can see
i will try to make it [SerializeField] or smth for now
oops sorry yes ur right on the x axis it doesnt move
I cant make it public/ Serialized
idk what to do now... its been like 4 hours trying to figure it out
can you tell me how that changes antyhing?
Add a [SerializeField] Vector3 testMoveDir;
And add this to your Update cs if(testMoveDir != Vector3.zero) moveDir = testMoveDir;
Now you have a separate variable for testing
You can remove it later
i was gonna change its value in Editor
okay
I mean all you needed was to press your movement keys but ok
did
the player rotates head
like he is moving
but doesnt move
i thought it would be the mathf.clamp(xRotation) line and change the parameters all to -90f but that made my sense like thirty times faster for some reason.
ok but if you had values in the moveDir you can see where the cast is going
Why are you doing custom collisions btw
Not the first thing i'd suggest to a beginner tbh
me?
Yes
xRotation yeah that means its Up/Down , idk what you mean by Y movement
Like the Y axis of the mouse ?
im following a tutorial... i dont remember who here recommended it to me
i corrected myself earlier i didnt mean to say the y position. but basically i need the camera to rotate on the x axis based on the mouses y position. like if i move the mouse up, the camera for the player will look up but not the actual players body
yes yes, but what is happening now? did you debugg the values
can u explain more... idk what to do
i will try reverting what i did and go back to normal Raycast
I don't see how you can explain any more clearly than that:
- Add a field to your class named
testMoveDir - Use it to set
moveDir(instead of using keyboard input)
if it works then its fine
first part is ok
i dont understand the 2nd part
what about this statement is unclear?
if (testMoveDir != Vector3.zero)
moveDir = testMoveDir;
do i just add that
to your Update method, yes
ok
presumably after the existing moveDir calculation
i mean i did the debug.log(xRotation) but im not too sure what im supposed to be getting from this.
you should be evaluating the values, ideally checking if they are what you think they are
this will let you provide a constant "move input", even if you aren't actively holding a key on your keyboard
i get this error when making the [SerializeField]
just show what u wrote
'SerializeField' is a type, which is not valid in the given context
oh god did you put in update..
i wrote
[SerializeField] Vector3 testMoveDir; before update
time to ask ChatGPT to help with u
You cannot declare a field in the middle of a method. That would not make any sense.
but its not in update
Show me what you actually wrote, then.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
its returning values, yes. but what am i supposed to do this? im still new so theres some things i dont know how to do on my own just yet
A tool for sharing your source code with the world!
testMoveDir does not exist anywhere in this script file
I want to see what you actually did
That looks fine to me. Are you sure you were getting an error?
Perhaps you had a typo, or you originally wrote something like
private [SerializeField] Vector3 testMoveDir;
Right; I'm just trying to think of ways you'd have gotten that compile error
So im working on a tycoon game where u build stuff like a city builder and was wondering what would be a good way of retriving the selected building to build? Although i do not have any way of selecting it currently still early in development but i wanted to know what would be the best and efficent way of doing it
well its private anyway
there is a typo right there
my hands stopped working for a bit
programming is an exact art. If you cannot be exact don't do it
gonna just reset the code to what it was before the part of CapsuleCast
@rich adder come back
i think i will start from the start of the Raycast part
are the values correct then ? in the logs?
if they are its likely issue with rotation itself
thats the thing i dont know what they are supposed to be
send code again
A tool for sharing your source code with the world!
ok so are you getting a value between -90 and 90 ?
yes
is parented to main player?
could be overriding it with this rb.rotation
Can someone tell me why the hell this doesnt work??
using UnityEngine.Click;
public class SwitchSceneOnClick : MonoBehaviour
{
// This method is called when the player clicks on the collider
void OnMouseDown()
{
// Load scene 2 when the object is clicked
SceneManager.LoadScene(2); // Make sure scene 2 is in your build settings
}
}
What doesn't work about it?
Is the code actually running? Are there errors in the console? What's happening?
Its supposed to sietch to scene 2 when I click the object, yet nothing happens
No errors
when i comment it out theres no movement at all
Debug.Log to make sure the code is actually running
but uh
if you're using the new input system, OnMouseDown is not a thing anymore
rb.rotation = Quaternion.Euler(currentRotation); is what you are talking about right? @rich adder
yea and are you for sure set reference to correct object? did you look at inspector if values change for it
yeah idk im lost man
idk what the issue is
ok so i gave up, i will start from the beginning again
log in mouse down to see if its calling
and i imagine you have a collider on that object?
Does anyone know why the transition is getting spammed?
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
put a log in Jump() just to make sure it isnt being called every frame
A tool for sharing your source code with the world!
ty
myb im new to this
ight
only gets called once per jump
Any State to Jump includes transitioning from Jump back to Jump as long as the transition condition is true
is there anyway i can exclude jump from any state?
no because Any State refers to any state.
yeah
damn
ok i just deleted the transition and remade it and it works now
idk why
but yipppie
in the future there's an #🏃┃animation channel
I just did that, it's not calling. I have no idea why
Did you read what I said before?
#💻┃code-beginner message
Yeah raycast doesn't work either
wdym raycast doesn't work either?
Are you using the new input system?
If you are using the new input system you should be using IPointerDownHandler
I don't think so
Don't guess - check
How do I check?
go to player settings and see what "Active Input Handling" is set to
or just... like... how do you not know lol
all your input handling code would be different in the two systems
I wanna have like a Dictionary for each Enemy prefab that basically holds the list of players and the "aggro" value they have on them (this being different for each enemy, so it's not like a value of the player itself). My question would be, if I want to do a loop to check for the highest aggro player, would this be okay to do on the Update method if the enemy and player count can reach like 20 each or would it be like kinda too much processing to do on each frame?
I always advocate for event driven code over looping in the Update
If you set a hard limit to only do it in one class and never have too many instances, probably ok
yeah event drive definitely better than looping each frame, however that's not a lot of looping being done so there likely won't be much impact on performance
I'd recommend making it event driven and generic so that you can reuse the code later if need be
So how would I do it event driven?
Like just update it whenver aggro is changed?
Cause that's probably just gonna be each frame anyways
yeah on aggro changed probably
Ya, this is meant to be like something like WoW, where basically any and all action just updates it so.....
You're talking about "threat" level in WoW?
Basically, yeah
so you can have tanking etc
you can look at how MMOs handle threat:
- each mob has a list of players who have threat on them, which you do probably need to maintain regularly
- only when one of those players becomes the new 'top threat by x margin' does the mob actually have to decide to swap targets
The concept is basically kinda of an autobattler where u are like a raid leader managing a bunch of idiots
nice yeah, just copy that 😄
It would be great if I knew how they do it XD
I expect it's just a list of values which get updated when 'threat causing' events are processed
Honestly, this whole concept seems like a nightmare to code with how little do I know
you need to be updating things like health constantly anyway, which threat levels are tightly related to
which part sounds like a nightmare? honestly just do the naive appraoch and you'll probably be fine
sounds like a priority queue would be a good data structure to use
It would be when an ability or effect is read from the stack or queue. I wouldn't think it's necessarily every frame unless you've got something going on every single frame 
Well, basically I would want to make it so the player can like basically customize what each member of the team is gonna do on each fight before hand, si kinda of superbasic AI but highly customizable
in an autobattler, I'd expect there to be a lot going on every frame while the battle is happening
Yeah, I don't know how to do that
this sounds like a different problem than managing threat levels
It is, yeah, I am just like thinking way too in advance
So basically almost each frame anyways, cause dots and stuff like that does exist
There are more frames than dots if you're referring to something other than game frames per second
The easy answer would be when an ability or effect is read from the stack or queue
yeah, none of this is going to be so heavy that I would worry about it initially
you'll have enough going on that 'every frame' seems like a reasonable enough starting point for processing any of this
So maybe I could have like a method that is called each second to Update the aggro, and calculate dots and all, those kinda of things don't need to happen each frame
both in terms of keeping the threat list up to date and retargetting, neither of which will require many resources
A 1 sec margin of error I would say is fine
I mean how many characters would even be involved in a fight?
You can just have Dict<character, float> for each threat level and then the enemy can, once every 100ms or something, jsut iterate over the whole dict and see whose threat is highest.
What would there be like 40 max?
Just calculate it when argo or threat is added
Hi I'm looking for someone who knows very well in vehicles I have a problem it's been 4 hours that I've been on it ^^
I would have anything which does a thing that generates threat also apply that threat at the same time
update your threat list when you do the damage
and then also have this
I mean, I am kinda just managing smaller numbers rn, but the idea would be like usually you would be dealing like a one big enemy (maybe able to summon a bunch of goons) and like... 10-20 players and MAYBE like 5 pets or something like that?
right, none of this will be so much that you need to worry about scale
you should just do it and see
exactly so we're talking about iterating over a list of 50 elements at worst
my advice would be to skip all of this
if you have dozens of characters on screen, each with individual threat lists and all interacting with each other, that's going to be a soup that the player can't parse anyway
this system will be invisible
and your real problem (which you have identified already) will be giving the player control of this in a way that feels like their decisions matter
so I would actually start there
You'll need to ask your question appropriately and in the correct channel. This is the beginner coding channel. Looking for an expert isn't a good question.
If you've asked prior, relink to the initial post when asking again else https://dontasktoask.com/
WoW's threat system is designed around a very different kind of gameplay than you're going to have and probably doesn't make sense for your gameplay goals
Well, the idea would be that the player would be able to issue commands like "if X enemy type is on screen, give them aggro priority"
But they would just target whatever is closset/has less health if they have like no command
So players would not follow the same aggro rules than enemies
if I think about other autobattlers like TFT, everyone just attacks their closest target until it dies or they get stopped from attacking in some way (e.g. CC or they go out of range)
and the way that players do what you are describing is by trying to position their people so that the closest thing is the one they want
or, knowing that this character will jump to the backline, so positioning them to do that optimally
you might be able to design around it, but generally 'who should this character be attacking' is either an obvious answer that you can specify beforehand (healer-dps->tanks), or super dynamic (like an RTS)
which is maybe fine, but I bet you could start with a much simpler system that accomplishes similar goals more directly
e.g. what if you can put your people into control groups, then tell a specific group to target a specific enemy/area?
no need for any kind of threat lists at all
anyway that's not really what you asked, but this proposed goal is not one that a threat system like the one you're talking about achieves
if that's what you want, assign tags to the types of units and let the player set the prioriites of those tags, and then you can do targetting based on them without needing any kind of threat list
The idea is that this would not work either like tft (where you just drag them near their preferred target) not like a rts where u can just issue them commands over the game
You have like extremely limited control during the actual fight (like maybe u have like 4 buttoms with commands like "these players move to the previously marked waypoint") and the rest must be issues before the fight begins
The gimmick being that organizing them is the actually challenging part rather than creating a team comp
this is something i've come to realize: the player ain't going to notice
maybe i don't need an elaborate exposure-based vision system where enemies can see you more clearly if they're dark-adapted
I think the next question I'd ask is 'what's fun about what you're describing here?' but I also don't want to dissuade you from just giving it a go
It's kinda of a... complex puzzle solving?
the players will never truly comprehend our genius 
But ya, maybe I can just scrap the whole aggro system and say that enemies just swap aggro between tanks while there are any and else they just hit whatever is closest
usually puzzles have a specific right answer, is that the case here? like if you pick the correct 4 waypoints and time them right, that's the right answer to the puzzle?
if I were you, I'd try to prove out this core mechanic
answer this question through prototyping, but you want to do that in a way that is moving in a direction
yeah, I would start with something super simple like "they attack whoever is closest until that target is dead" and then add layers on top of that for the player to interact with
give them a button where they can select a tank to AOE taunt
or do a big stun or something
sort of like minion masters/clash of clans, where it's an autobattler, but you also have various buffs/spells that you can throw out
and if your gimick is realtime zone and aggro management during the battle, I can totally see that (have the spells create walls or push units around which causes them to 'retarget nearest', or push/pull them into an area or towards a unit/trap, etc)
I just thought it would e funny to have stuff like, if you have like a overgeared dude that is popping out to take away aggro from enemies just like would happen in any of those games
So you have like sorta of a extra layer of stuff to think about
But maybe having a whole system just for that is kind unnecessary, and also not really that fun of a system
right, it's good to keep stuff like this for your final vision! but if you're still just testing out your mechanics, you need to build a whole character, gear, stats, and threat systems in order to get something like that working...only to find out that with all that complexity, it's hard for the player to tell that their actions through these varying systems combined into this specific effect in the battle
instead you could just be like 'this is the high damage archer character and their attacks have a 50% change to pull aggro' and now:
- the player understands directly from that description how this character works without having to infer it from emergent interactions between multiple complex systems
- you can implement that quickly to see if it's even fun or interesting and then iterate from there
you could also try it more systemically 'if a character takes more than 10% of their health in one blow, they switch to that target'
go for the simplest route to the outcome you think you want so that you can see if that's true and hone the specifics
is there any way i can put the object that is coliding with this object into an array but without tags and that?
just add other.gameobject?
tnks
use a List not an array, and just Add in that and Remove in Exit. or you could use physics queries like overlapbox and the like if you just need that info at specific times
Let's say:
I have a public variable in my code --> my code works
I change that public variable into private, and suddenly my code doesn't work and I get an error thrown about some object not being referenced
What's weird to me is that I'm only changing it to private so I don't have to look at it in the editor, I don't reference that public variable in any other script. Is there a reason why changing a variable from public to private would do this?
public variables are serialized
private are not
what do you mean list ? i want to add the object to an array and when the array size is 10 i would jus do a foreac loop and destroy them is that not good?
but why does that change whether the code runs
Since it's no longer serialized the value you set in the inspector is no longer there.
It doesn't change whether any code runs
Show us the code and explain what's going on then, your description is missing context
arrays are fixed size, you cannot add and remove from them, only assign to the elements of it. if you want it to be able to change size then use a list
For example - what error are you getting? On which line of which script?
ok ill try
The error I get: "Object reference not set to an instance of an object"
The error happens somewhere in the RemoveButtons loop. When it's called the first time, moves_to_select.Count is 0
Because when it's public it's serialized
as an empty list
when you make it private, it's not serialized so it remains null
also keep in mind that = new() is only applying to the second one
Ah, that doesn't apply to both
Ic
Thank you
I am getting an error that i cant delete objects inside prefabs i tried searching and i cant find any answers just more poeple with the same problem ?
you're trying to destroy part of a prefab
don't do that
You need to destroy whatever you've instanced instead
based on this code - you've presumably dragged and dropped a prefab into the list in the inspector
though it's weird that your list would have anything but instances in it
i am doing that but what i instanciedted is a part of a prefab
It would be helpful to see the entire stack trace
The only way I can see this error happening here is if you dragged and dropped a prefab into the list in the inspector, or if some other script added one to that list
The script hasn't been saved
so what we're looking at is different, so perhaps the list is public
oh that too
and has something assigned in the inspector
its saved i have a prefab with 4 objects in it and i want to dellete the part of the prefab that collides with the trigger so i put them in a list and del them after the list size is 10
show the full stack trace of the error as vertx asked for before
If you saved it and it's the same as what you showed above then it wouldn't be firing errors
It might even be a totally different script causing this error
whats the best way to make a player shoot in a 2D space following the mouse? cuz i made this script but the proyectiles dont follow a normal speed, i mean, for example when the player falls from a high place with a lot of speed, when i shot the proyectiles down they go up instead of being shot down due the speed of the player falling
btw this is the script
void rifle_shooting()
{
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
riflebullet.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed;
}```
Try adding the player's rigidbody linearvelocity to the bullet.
like this?
void rifle_shooting()
{
Rigidbody2D playerRigidbody = GetComponent<Rigidbody2D>();
Vector2 playerVelocity = playerRigidbody != null ? playerRigidbody.velocity : Vector2.zero;
Vector3 mouseposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseposition.z = 0;
Vector3 shootDirection = (mouseposition - transform.position).normalized;
GameObject riflebullet = Instantiate(rifle_bullet, transform.position, Quaternion.identity);
Rigidbody2D bulletRigidbody = riflebullet.GetComponent<Rigidbody2D>();
if (bulletRigidbody != null)
{
bulletRigidbody.velocity = new Vector2(shootDirection.x, shootDirection.y) * rifle_bulletspeed + playerVelocity;
}
}
sorry if its wrong, i just i didnt fully understood how...and due how slowly the game test runs due my shitty cpu i wanted to make sure before testing
Looks good. It should conserve the player's momentum.
Probably change velocity => linearVelocity in the future, as velocity is deprecated.
oh, right, i forgot
But it does the same thing, it was deprecated in 6.
ah, makes sense
well, thanks :3
em...for a strange reason when i jump the bullets go up, why this happens?
i mean, i guess is supossed to maybe the values of the player changing for make it jump...but how do i fix it, also this is a hypothesis
Are your bullets being childed to your player?
idk, maybe?
i mean cuz is a prefab that spawns
so technically aren't in the player arquitecture
but comes from it
so...maybe?
Check your scene tree during play and see if your bullets appear at the root of the tree or under your player, if so then when the player jumps the bullets will also jump with them
nah they dont
Could someone explain to me why the 'bundle' bar does not appear and what to do about it?
mmm and honestly, the script still doesn't work at all, the bullets still dont follow very well the movements, better than before, but not perfectly
and at this point i dont know what to do
Is it like a run and shooter platformer, like Contra? Or a top down shooter like Asteroids?
first
its like a run shooter plataformer
where the bullets aim to the mouse
i mean, you aim to the mouse
and also an important detail of the game is that you move, a lot
Got it, I have a small prototype like it, let me copy the code.
is more like a Doom Eternal/UltraKill but in 2D
interesting :3
Hi im new to unity and im trying to get my script to recognize the prefabs i made but its not being detected. Below in the picture is the error im getting
What is ExtraPoint in code?
Sorry if im unclear im still new
i made a prefab extrapoint is a target that will spawn in and give you extra points when clicked
its a 3d object
Those are the names of GameObjects, but do you have any scripts named DontHit and ExtraPoint?
I dont i was trying to attach it to my main script which is game manager
should i write script for those individually then link them back to the game manager?
So, the Type of a variable needs to be a class, either one you wrote or one Unity provides. The names of GameObjects do not exist in C#
Is there a script of any sort on these objects you intend to be using?
ohh okay so if i write a script for it i can then refrence it to the other scripts
First off, you should decide what you are going to need these objects for
Do they just have to, like, exist? Or are you gonna need them to do anything?
For context you just click targets and get points
I can paste the whole files but they're rather big.
I think removing the player's velocity from the calculation could be a start. I was thinking from an Asteroids perspective when suggesting that. You might need to adjust the speed of the bullet to start. Maybe like "bulletSpeed = playerVelocity.magnitude + initialBulletSpeed"
they spawn randomly and those prefabs are supposed to be dsifferent targets one gives you extra points and disappears faster and the other takes away if clicked
You might be confusing C# Types with Asset Names. Just know that usually Prefabs you want to instantiate are of type GameObject or Transform. That will fix your compilation error.
omg xd you're right
Mainly, you'd use the type you need to avoid calling GetComponent. There's no reason to use a GameObject variable . . .
// the private backing field
private int _maxHealth;
// read-only, returns backing field
public int MaxHealthReadOnly => _maxHealth;
// equivalent to:
// public int MaxHealth { get; private set; }
it says to use expresion-bodied properties to "shorten", but isn't the second method shorter?
This is from Unity code style guidelines.
I always felt like specifying a backing field manually is more code, is there any benefit to it that you can't achieve with a 1 liner?
The only reason I can imagine is to make sure that it's clear to other coders that this field is meant to be readonly.
It's easier to expand functionality later. That's basically it
Only because you used a shorter name
Also yes, you could just call them both MaxHealth
Wait sorry the second one IS the expression -bodied member
I just copied it, but I didn't notice that, it makes sense now that I look at it 😄
member => expression;
This is what I found, so I assumed it's the first one
I misunderstood what you meant by first and second here
I was considering the field alone as the first
by first i mean first 2 lines of code since they belong to the same property
// - Use the expression-bodied properties to shorten, but choose your preferrred format.
// - e.g. use expression-bodied for read-only properties but { get; set; } for everything else.
This is actually interesting, because that's the code I got from someone here in the past for "serialized readonly property" 😄
public string WeaponName => weaponName;
[SerializeField] string weaponName;
I mean, the comments say it all "choose your preferred format"
Yeah, I just got confused when it says "to shorten"
They probably imply that you can define quite a bit of logic in getters/setters, which would indeed be longer.
The auto properties approach would be the shortest one no matter how I look at it.
yeah I think they referred specifically to this:
member => expression;
It's just that their example uses a backing field
There's a difference between using a backing field or not, and properties vs auto properties.
And separately + expression bodied members.
What do you mean by separately?
But wouldn't that mean that I should never use: public int MyProp { get; private set; }
I mean except but choose your preferrred format., but I am trying to see their point 😄
actually it's referring to shortening, next line:
// - e.g. use expression-bodied for read-only properties but { get; set; } for everything else.
Enforces that I use expression-bodied for read-only if I want to follow their style guidelines
Well, it would be more correct to compare these 2:
public Type exprBodiedMember => backingField;
public Type normalProperty
{
get { return backingField;}
set { return backingField;}
}
Yeah that definitely makes much more sense
and I can see a shorthand version being easier to read, especially as you add more of these properties 😄
This would be an auto property. A separate concept not covered on that docs page. And it's fine to use it.
Where do you see that anyway? I don't see that on the page you linked.
They do mention it, just not as read-only
I get it from this book(from unity clean code guide)
https://cdn.bfldr.com/S5BC9Y64/at/5v473vn8kz7p85275gw8vnph/2022_WritingCleanerCodeThatScales_EBook-v6-Final.pdf?#page=1
Page 10
the movement now works but now the animation freezes even when the z key is released and it stays in the run blend tree without switching to the walk one and the freezing animations are now also staying for longer like one state is being repeated for 3 keys or so script - https://paste.ofcode.org/Ftdf37bDpS8fGPqRz2VNDZ pls help fix it
tried this but the run animation isn't being played and the walk animation is extended from 4 frames to about 6 to 7 frames https://paste.ofcode.org/LSGKYjku8sq7bhGyXJWUy5
Add Debug.Log to each if block and see if your animation is set properly or if specific code block is executed more than it should.
Also this is just a guess, but this code will become a pain to maintain as you add more states.
Check out some state handling guides out there.
Once you add jumping, attack you will have to handle these while your character is: idle/walking/running and later crouching/sliding or w/e you add.
With so many if/else statements it's difficult to read as well.
for example you can return after line 85 and remove else block
to reduce 1 nested block
It says run animation is set but then is moving comes and is running doesn't
I just want walk and run
I will refactor the code later once I get this right
You have to debug more, if you debug you will find a reason why it breaks.
if your character is supposed to be running, but the animation doesn't play then something is wrong with your code(or with your animator setup)
My suggestion is to simplify it:
Remove all code and simply make character play running animation when you press A then make it play Walk animation when you press S then with D you play Idle animation
See if that works
If that works then you are good to go, if it doesn't then it's an issue with an animator(probably)
yup that works
Also did u use chat gpt to write this code?
it looks like it
You shouldnt have comments on every single line of code
Never write comments that are useless, it makes it difficult to read code
I do that because I am making a devlog on this
ok so when I use the z key and move it shows only moving and not running
also the frames which are of 4 are extended till 6 or 7
private void UpdateAnimator()
{
if (isMoving)
{
animator.speed = 1f;
return;
}
if (isRunning)
{
AnimatorStateInfo currentState = animator.GetCurrentAnimatorStateInfo(0);
if (currentState.IsName("Run"))
{
animator.speed = 1f;
}
}
else
{
AnimatorStateInfo currentState = animator.GetCurrentAnimatorStateInfo(0);
if (currentState.IsName("Walk"))
{
animator.Play("Walk", 0, currentState.normalizedTime);
}
}
}
Not perfect, but it should do same thing and be a bit easier to read
the run animation isn't played and the walk animation's freezed frames are extended in walk
Because you never play run animation in your code
oh right lemme implement it real quick
I think what they meant is comparison between the first 2 props with backing fields:
ok implemented the run anim but now the run animations freeze which I don't want I want the animation frames to freeze in the walk animation https://paste.ofcode.org/pwuaN8B34d5ZC7w9dBrB7u
You should use chat gpt only if you can write your own code.
Or ask chat gpt to fix your code.
Or debug your code properly.
If you are able to play animations separately then there is an issue with your logic that freezes the animation.
I checked the code and looks fine to me not getting what the problem is tho
That makes sense now that I look at it.
So { get; private set; } is basically "but choose your preferred format"
no idea, you showed 2 different scripts twice already
are you copy pasting whole class from chat gpt each time?
yeah that is the modified one I got it when I was experimenting randomly the excess frames are removed with it
That part is a bit confusing, because this is not what the expression bodied one would look like if you were to turn it into a normal property. They probably assumed you can write and compare the correct alternative with a backing field.
Basically the "equivalent" is sort of a lie
I thought they do the same thing which is to make this property a read only?
I always used the second one, unless I needed to do explicit setters(for null checks and what not) then I'd have to make my own backing field anyway.
They don't show much for these examples tho, so I am still lost on that part, but maybe there is more in the book.
They do that indeed, but there are more ways to do the same thing. The main difference that makes them not equivalent is that the first one uses a backing field and the second one does not(the compiler would create one during compilation, but that's a different story).
An actual equivalent is the one that is below that comment with a backing field. Aside from the part that the setter is public
I see
Btw if a property getter/setter would span multiple lines is it still a good idea to use a property?
I can probably use some math functions usually or ternary operator but if I want to do some checks, would a method be a better choice?
I can still use expression-bodied property and call a function right?
maybe I am confusing it with something else, I can't find that example now
It's up to you. Usually it's advised to not contain too much logic in the property. Especially if it modifies the returned/assigned value.
Yes you can. But you can do that in a normal property as well
So clamping a value would be modifying it, but I'd still keep it in a property probably
Other than that I think any logic would be used to modify the property or throw an error maybe?
If there is logic in a property then it will modify a property, otherwise what is the point of it(other than to throw an error/warning)
Maybe I am overthinking it, but any logic is modyfing something 😄
Validation usually. But again, it's a lot of a convention and preference thing, so you'll see different people/teams/companies using it differently.
The rule of thumb is be consistent in your code.
Everything else is up to you
Also one example might be if the backing field stores the data in a different format. For example, packing a vector into an int/float or something
Makes sense, I did realize that I follow a lot of these guidelines already, but that's probably VS helping me along the way.
I am glad that I don't have to istall Eslint or other things to get these benefits 😄
The conversion logic could be in the property
so getter and setter would be of different type?
hey everyone, I'm using transform.up and a direction in my 2d game to have an enemy object always look at the player. but when i'm crossing over the southern cardinal direction, the enemy flips it's rotation. how do i prevent this?
or you mean a backing field specifically
here is my code
transform.up = direction;```
So you have to convert back and forth, I can't imagine a use case for it atm, but I suppose there might be one
maybe using same backing field with multiple properties?
No. They can be of the same type. Just the backing field would be different type and getter/setter would convert from publicly available type to the one that the field has.
One use case could be implicit serialization. For example, the property is on a save data class that is supposed to be serialized, but the runtime type is different. The property would handle converting the runtime type data to a serializable type.
And vice versa
Yeah I just asked chat gpt to give me an example and it converts a Vector3 to an array of floats.
wdym like its too fast ?
no, i think i solved it with this code
transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);
which replaced
transform.up = direction;
it was previously flipping the transforms left and right vectors when it looked south..
oh right was going to suggest something similar , did it work ? otherwise you can use the X axis pos
yes i'm not seeing the issue anymore.
the code was attached to the snake enemy on the right or the picture. the yellow dot represents it's right side, and green represents it's left side. when i was crossing a cardinal direction, it was flipping those two points.. and resulted in 'flipped' enemy behavior
the red point is the enemies relative point for the other two
Hi im having trouble solving an error
show code
seems pretty clear you're trying to instantiate a null reference
are you trying to Instantiate an object that was destroyed?
{
[SerializeField]
private Target targerPrefab;
[SerializeField]
private DontHit DontHitPrefab;
[SerializeField]
private ExtraPoint ExtraPointPreFab;
[SerializeField]
private float spawnTime = 0.5f;
private float spawnTimeCurrent = 0f;
[SerializeField]
private int points = 0;
int count = 0;
// Update is called once per frame
void Update()
{
spawnTimeCurrent += Time.deltaTime;
if(count < 100)
{
if (spawnTimeCurrent > spawnTime)
{
count++;
SpawnNewTarget(Random.Range(0,3));
spawnTimeCurrent = 0f;
}
}
}
private void SpawnNewTarget(int type)
{
if (type == 0)
{
Target temp = Instantiate(targerPrefab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
temp.gameManager = this;
}
else if (type == 1)
{
DontHit temp = Instantiate(DontHitPrefab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
temp.gameManager = this;
}
else
{
ExtraPoint temp = Instantiate(ExtraPointPreFab, new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), 0), Quaternion.identity);//create a temp version of this object
temp.gameManager = this;
}
}
public void addPoints(int additionPoints)
{
points += additionPoints;
Debug.Log("Player points "+points);
}
}```
{
public GameManager gameManager;
[SerializeField]
private int myPoints;
private float timeLeftOnScreen = 3f;
void Update()
{
timeLeftOnScreen -= Time.deltaTime;
if (timeLeftOnScreen <= 0)
{
Destroy(gameObject);
}
}
private void OnMouseDown()
{
myPoints = -50;
gameManager.addPoints(myPoints);
Destroy(gameObject);
}
}``` This is the code for one of my other objects
are one of these prefabs dragged from the scene, or they all from project folder?
Im trying to refrence them from a folder
but its seems not to be working and im a bit confused on that aspect
I have a prefab folder with the prefabs in it
but my main script cant find them
completely unrelated to your issue, but you could use an enum rather than an int for that type parameter you pass to SpawnNewTarget
enums are basically just named ints so it makes the intention more clear and you get the benefit of using compile time names rather than needing to remember which int you wanted to correspond to which "type"
can you show the inspector for object this script is on+ hierarchy ?
Sorry if I'm a clueless is this what you're referencing?
you didn't assign one of the prefabs
looks like object is missing , so its null
See how they say "missing" - yeah that's your problem
and that means you deleted them or destroyed them
these might have been scene objects, they don't look like prefab. shouldn't they be blue
Yeah I would guess they weren't actually prefabs in the first place
No those are fine
this is my prefab folder
but you need to drag those into the slot
yes but did you put these in the script?
not ... something else
Like add a component to them? Because i did write a script for them
no, what did you drag in here
show that
i cant drag the other two prefabs i made into it
show what ur trying to drag
screenshot the whole window dont crop
Do the prefabs have the appropriate components on them?
You need the DontHit and ExtraPoint scripts on them, respectively
I would guess you don't have those
show the inspectors of the prefabs (ideally the whole unity window with them selected)
Seems like you had them at one point and deleted them
So just for my clarification the reason why it wasn't working was because i didn't have the right components attached to the prefab?
You had a reference to the component on the prefab originally
later you deleted the component from the prefab
so the reference was broken
Also you weren't able to reassign it because the prefab now was missing the expected component
ooh thank you that makes sense
i def not be making that mistake again lol thank you so much! @wintry quarry @rich adder
hello so I have this code which has all the movement needed but the issue is that I have an animation freezing system and the walk animations freeze and after 4 frames they should reset the walk animation but they continue by repeating for 6 to 7 frames and then are switched pls someone explain how to fix it all the animations are of 5 fps
Are you messing with the state time or something? Or is it a performance issue?
no Idk why but the 4 frames are extended to 6 to 7 frames with some frames being repeated before the the animation is completed like the blue progress bar is filled
How do you know that it takes 6 or 7 frames?
I count the number of key presses it took for the blue bar to be filled
Wdym? What key presses? And how is it related to frames count?
Also, your UpdateAnimator() method definitely seems suspicious. Why would you need to modify the animator speed? It's really sketchy.
the walk animation plays with the the number of keys I press like when I press the up key the up walk animation plays and then I notice that the frames are repeated
to make the animator pause and unpause to freeze the animations
This is gonna be very unreliable.
This is gonna be very unreliable as well
The animation is not updated by frame. It's updated with delta time.
but I noticed something that when I set the blend tree's speed to 2 the animations work perfectly but the animation is sped up when used
oh right thx for pointing that out I forgot lemme try it
Honestly, just don't use animator
It's not meant for frame precise control. Change the sprite via code or something
I removed delta time still nothing but now I have strived a lot and don't plan to change anything now so any idea why that is happening
Update frames don't have to correlate with animation frames. That's what's happening.
Besides, it doesn't look like you're too far in to refactor your system.
so how do I fix it? I tried using fixedtime instead of delta time but same effect the speed just goes out of the boundary and still frames are being repeated
You don't fix it. Animator is not meant to be used like that.
but I have spent way too much time doing the run and idle anims and don't want to revamp the code
there must be anything which can be done right?
Sometimes that something is to realize that your approach is not gonna work and rework it.
can't I use AnimationState.time?
If you really wanted to, you can do that I guess. But I wouldn't recommend that
what would you recommend then?
btw the frames work as desired when the speed of the blend tree is doubled can anything be done?
As I said, implement a simple system that increments the renderer sprites.
This just happens to work because you more or less matched the animation frames to actual game frames. This is gonna break as soon as the frame rate changes(on other machines or in the build for example).
So I replace the whole script or just the animation playing part??
You can implement it as a separate script and call it's methods from your script.
hey why is this returning null?
private void OnCollisionEnter2D(Collision2D other) {
if(_hasHit) return;
_hasHit = true;
other.gameObject.TryGetComponent<IDamageable>(out var damageable);
Debug.Log(damageable); <-- NULL
}
Because the object you are colliding with doesn't have an IDamageable component
yes it does. look at the screen shot
How does that prove that the collided object has it 🤔
because there are only two items in my game rn, 1 = the bullet, and two the snake
Try Debug.Log($"Collided with {other.gameObject.name}", other.gameObject);
Generally, you see what is null, then you try to figure out why it's null. You claim the object has the interface, which is fine, but now you should check if you actually collide with the object that has the interface
Also, a Try-method exists because it does a graceful attempt at something. The boolean it returns indicates if it succeeded, and one or more out parameters return a valid result, assuming the boolean returns true. In this case you don't check this boolean at all and assume that whatever you hit has the interface. You should definitely check this.
-other.gameObject.TryGetComponent<IDamageable>(out var damageable);
+ if (!other.gameObject.TryGetComponent<IDamageable>(out var damageable))
+ {
+ return;
+ }
If you don't do this you might as well be using the original GetComponent method and get a more clearer exception
I am actually wondering, if an interface is found by getcomponent at all?
Yeah it is
That's the reason that Try/GetComponent doesn't have a where T : Component constraint
To support interfaces
Using this so rarely, I actually forgot if or if not, thanks 🙂
I think damage dealing is pretty much the only place I use it 😁
In this script the running animation works and all but upon freezing the sprite and pressing the button the next sprite isn't played as instead of the walk frames the idle frames are displayed pls someone help here is the script https://paste.ofcode.org/mZcUDYjMKTipzcfEw3EVnR
https://youtu.be/Kgjth3nRsFc?si=BFxLMqZsMBB00je5 17 mins and i cant look around https://paste.ofcode.org/iDZcZjDZQjGLYbaPCDEBhd
Learn how to create your own classic First Person Shooter in Unity!
Get the assets for this series here: https://www.dropbox.com/s/juihs7yq93x1aon/GPJ_FPS_Assets.zip?dl=0
Don't forget to hit that like button and if you'd like to see more gaming goodness then subscribe for more!
Support the show by pledging at http://www.patreon.com/gamesplu...
Do i need an older version to allow it to work?
But you can move?
What is your mouseSens set to in the inspector
im checking hold on
Roger that. Holding on.
It is 1
which is what the dude in the video has
No other components? No animator?
Just making sure that nothing else is modifying its rotation
Nope nothing
Try changing transform.rotation = ... to rigidbody.MoveRotation(...)
That's the correct way anyway
When you have a rigidbody
Okay i will try
It will only take the Z angle btw, not XYZ
Its a whole lotta red
You replaced rigidbody with your own rigidbody variable name, right?
Debug.Log the moveInput before you rotate the character
Also make sure you haven't constrained the rigidbody's rotation in the constraints tab
Where would i find this
like how would i find the constraints tab
In the rigidbody inspector.
Theres nothing on
Hi, I have a problem where my player doesnt play the hurt or die animation when taking damage
public void TakeDamage(float _damage)
{
currentHealth = Mathf.Clamp(currentHealth - _damage, 0, startingHealth);
if (currentHealth > 0)
{
anim.SetTrigger("hurt");
//iframes
}
else
{
if (!dead)
{
anim.SetTrigger("die");
GetComponent<PlayerMove>().enabled = false;
dead = true;
}
}
}
this is the code for it, im just follwing a tutorial
Ive debugged and heres what happens when i move mouse around
Ok, just had to check that it isn't an input problem
Did you confirm that this method is being called? With a debug log for example
And have you set up the animator properly to use those triggers
would u think its a problem with me using a later version of unity
Nope
Cuz the video uses 2019
None of this has changed except for velocity -> linearVelocity which you already changed
This is needed for my cs project and i cant find any tutorials that work properly
Oh btw I misspoke, I meant debug the mouseInput not moveInput
Are you clicking the game view to focus on it?
yep
It won't detect mouse if you dont
it is getting, called, if it wasnt then the health barwouldnt go down
i think
Well now we know the reason - mouse input is zero.
I gtg but perhaps someone else can help debug it further
😭
Ugh
Okg bro
this is a code channel, delete and ask in #archived-lighting
ohh sorry thanks
In this script the running animation works and all but upon freezing the sprite and pressing the button the next sprite isn't played as instead of the walk frames the idle frames are displayed pls someone help here is the script https://paste.ofcode.org/mZcUDYjMKTipzcfEw3EVnR
Quick question, the || here is kinda redundant right?
Well you would have already gotten a null reference exception by then
Not redundant. Having a null list is not the same as an empty list
It would work if it was arranged the other way around
But you should change the order
I am wanting to check for "as long as the list does exist and it's not empty"
Just reverse the order of those checks
You can also just simplify that a bit
aggroTarget == null && heavyAggroPlayers != null && heavyAggroPlayers.Count > 0
No need for the negation and parentheses etc
Ya, seems better, thxs
heavyAggroPlayers?.Count == 0 would be the proper shorthand for your case
By default if it is null, then the null conditional with ? automatically returns false
It's the same as checking null, and then doing the operation, so the result is the same.
Mmmm, I guess, I just find it easier to read with this one
So if there is not much difference I am gonna stick with that one
There are differences when gameobjects are involved. Not here, though.
i have this code but my player doesnt move or anything is there something wrong
using UnityEngine;
// Controls player movement and rotation.
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f; // Set player's movement speed.
public float rotationSpeed = 120.0f; // Set player's rotation speed.
private Rigidbody rb; // Reference to player's Rigidbody.
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody>(); // Access player's Rigidbody.
}
// Update is called once per frame
void Update()
{
}
// Handle physics-based movement and rotation.
private void FixedUpdate()
{
// Move player based on vertical input.
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = transform.forward * moveVertical * speed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + movement);
// Rotate player based on horizontal input.
float turn = Input.GetAxis("Horizontal") * rotationSpeed * Time.fixedDeltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
The way you phrased this though is exactly how my example reads
Can you please format the !code properly? I also posted the bot message in the other channel
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Preferably just use one of the paste sites with this much code
wdym correctly
Properly formatted and using a paste site when you use large code blocks
See bot message
oops
Okay, this is kinda of a dumb question but, what's the thing that I am wanting to use here?, cause I do remember there was a thing for this, I just don't remember the name to look for it
no idea
A thing for what?
an enum?
an enum?
284?
@keen sierra Don't crosspost. And if you're not actually helping anyone or asking a question, don't post.
ok chill
hey guys! i was looking to make a platformer, i was wondering how would i be able to tell in which ground my player would be stepping in? as i want to make a special effect depending on what the player is stepping on
should i make a script and apply to every ground, then use a onCollisionEnter to check if the ground's tag or name is something in specific? or is there a better way?
A more robust way is to do a raycast downwards when you want a footstep to happen
and to use a custom component to store the data
You can then get a component or a tag or something that stores which type of surface it is
The raycast could be triggered by an animation event
I would do a component that references a scriptable object with the data (sound, effects), tags not so good
what is a raycast? i see a lot of people talking about it
well, its one of those troll platform games, so if you step in x platform something happens to kill you but if you step in y platform it actually helps you
thank you very much!
how can i know whats the best way to do something? is it just experience?
or how can i debug my code to find the best practices/best performance optimization
You can use the profiler to see what is slowing your game down, but don't worry about it until you actually have bad performance
alright! but how can i find out what is good practice and what i can do to write better code?
i was thinking of using leetcode but i'm not sure
ha not really gonna teach you what you want atm
in this script I included a function to freeze animations and play them to complete them frame by frame but I want it for only walk and not for run but the run animation freezes and doesn't switch to the idle animation frames which I want pls help here is the script https://paste.ofcode.org/8F5y2sKHDeDp4UHvBXZ6gu
I am a little confused as to how co-routines work
I have a script which waits for 5 seconds (yield return new waitforseconds(5))
but while this 5 seconds elapse the other part of my script can still execute
how does that work?
I thought waiting these 5 seconds would halt the whole script
nah, coroutines are single threaded. If it halted completely unity would freeze on you
basically what it does is exits the code at the point and picks back up when those 5 seconds are up
so each cycle it goes there and checks if 5 seconds elapsed?
pretty much
well, you can think of them as mini update loops.
mmm i see
they have independency from each other and have less overhead of a gameobject*
private bool isRunning;
isRunning = Input.GetButtonDown("Run");```
i made the keybind in input manager, but it doesn't seem to change weather I'm holding shift or not, it's always false.
Suspecting that isRunning = Input.GetButtonDown("Run"); is my mistake
that's going to only be true for one frame
GetButtonDown only returns true for one frame. it resets each frame . . .
Really? It's inside the void update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
public float gravity = -14f;
public float jumpHeight = 1f;
public Transform groundCheck;
public float groundDistance = 0.2f;
public LayerMask groundMask;
private Vector3 velocity;
private bool isRunning;
private bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
isRunning = Input.GetButtonDown("Run");
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if (isRunning == true)
{
speed = 8f;
}
else
{
speed = 6f;
}
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 move = Vector3.ClampMagnitude(transform.right * x + transform.forward * z, 1);
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
yes really
Read the documentation for what GetButtonDown does
How do I fix that
Use GetButton instead probably
doesn't matter; at the end of each frame, the value is reset. then the next frame it checks again . . .
in this script I included a function to freeze animations and play them to complete them frame by frame but I want it for only walk and not for run but the run animation freezes and doesn't switch to the idle animation frames which I want pls help here is the script https://paste.ofcode.org/8F5y2sKHDeDp4UHvBXZ6gu
Hey can someone help me understand what would be the best way to make enemy ai for a 2D top down game
"best way" means different things to different people, what exactly do you mean?
like that i can have good controll of the states and behaviours mostly that and not tooo hard to implement
Way too vague of a question.
"Enemy AI" could mean anything from attacking your player with ranged attacks to.. writing nastily worded letters at them.
- be able to describe exactly how you want the AI to behave
- program that
it sounds like you should spend some more time on 1
you might have better luck watching the video
does anyone know how i can freeze the game for a couple frames
Simplest way is probably a coroutine that sets timescale to zero, waits a bit and then resets it
interesting
Unless by freeze you mean actually freezing the application lol
Is this for an impact effect when you hit?
the video of 10s got above the limit of discord TT
Think you can use Streamable
so let's say I have a bunch of balls dropping down from somewhere and I want to add an explosion force on mouse click on mouse location that would affect all of the balls
do I need to add them to an array and get all of their rigidbodies and then add an explosion on mouse position?
seems a bit strange
no you would probably use Physics.OverlapSphere to find those near where you clicked.
(or Physics2D.OverlapCircle if 2D)
but I still need to get their rigidboides, yea?
Yes...?
Like I said, you use OverlapSphere
so you can get to the RB from the collider
yea yea, I get that, it's just weird because
ah no wait I get it
explosion force creates a position
and adds a force to the rigidbodies I reference
you would call AddExplosionForce on each Rigidbody you detected yes
You could also just calculate the force manually based on distance etc and use regular AddForce
in impulse or velocitychange mode
nah this is ok
I was like how can I add the same force to each
but I get it, it's automatically applied based on distance
Actually the code example here is pretty much exactly what you want to do:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.AddExplosionForce.html
is there anyone here that uses snake_case_for_anything?
I think the only times I have is when I have some placeholder property with a descriptive name
its not really a naming convention I like looking at, so thats a big reason I avoid it
i use it in python but that's only because it's the standard for that language
I use it for any hand-authored IDs
I often use it in HLSL
looks valid for hlsl since its similar to c++ syntax
in C# i use it only for consts, capitalized snake case
ahh, okay.. yea thats when i use it too i was just curious if there was other standards.. or somewhere else i could utilize it
"screaming snake case" 🤣
SCREAMING_CASE, indeed
hilarious that thats a legit terminology 😄
if you rly want to use it for something then only native functions may be the appropriate place, so you know instantly what you deal with when you see it
Hello, I'm having an issue trying to assign a game object in my inspector, no matter what game object I pass it it says "type mismatch"
you can't drag scene objects into prefabs
pass the reference to the instance of the prefab at runtime: https://unity.huh.how/references/prefabs-referencing-components
is it possible to do like a little camera shake on a cinemachine follow camera when the user does a specific action?
nvm
figuring it out
i think i'd rather just reference that variable in another object instead, thanks!
what's wrong with this code
https://paste.mod.gg/ovtflwpyineb/0
A tool for sharing your source code with the world!
It gives me this error when i run it
NullReferenceException: Object reference not set to an instance of an object
PlayerMovementScript.OnDash (UnityEngine.InputSystem.InputValue value) (at Assets/Scripts/PlayerMovementScript.cs:211)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
Your error is in PlayerMovementScript.cs
not the script you shared
CinemachineShake.Instance.ShakeCamera(5f, .1f);
Assets/Scripts/PlayerMovementScript.cs:211
Line 211^
this is the line i use in my player input script
CinemachineShake.Instance is null
Which means most likely you simply don't have one in your scene
i have it tho
nvm
i figured it out
public static CinemachineShake Instance = new CinemachineShake();
changed this line in my CinemachineShake script
uh no
this is a terrible idea
how come
You can't new a MonoBehaviour
This is not the CinemachineShake component
You need an object with the CinemachineShake script attached to it
I do have it
(and your script also requires it has a CinemachineCamera on it too)
the follow camera
that isn't the singleton pattern in unity
oh
it seems to be an actual unity camera
mb on the screenshot
the main camera has cinemachine brain
the follow camera is cinemachine camera
good
but you just changed all that it seems
so... pause the game, make sure the scene is saved with the correct setup
and try again
what should i do abt the line
public static CinemachineShake Instance = new CinemachineShake();
revert that stuff to what you had here https://paste.mod.gg/ovtflwpyineb/0
hey everyone,
i want to know what the correct approach is to solve my logic.
i have a snake enemy that has body parts in a List<BodyPart>. each bodypart has an id for order.
when one of the body parts is removed, how do i correctly update the id's of the body parts so their is no gaps in the itterator on every frame.
body parts can be removed in any order or random selection.
should i ditch the id strategy? what are your thoughts?
What do you use or need the ID for
the List itself maintains the order
hitting me with a similar issue
NullReferenceException: Object reference not set to an instance of an object
PlayerMovementScript.OnDash (UnityEngine.InputSystem.InputValue value) (at Assets/Scripts/PlayerMovementScript.cs:211)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)```
show the playermovement script
that really seems to be pointing to there not being a CinemachineShake in the scene, assuming Awake actually ran on it
i suppose i don't need the ids? idk. the id is becasue when the body part is hit, it runs a method telling the parent which 'bodypart(id)' is the correct one to remove.
should i have used start instead
Why not just pass itself to that method?
Then you can do cs public void RemovePart(BodyPart part) { listOfParts.Remove(part); }
does this: listOfParts.Remove(part);
cause a loop? or is it fast?
it's a loop
It's linear but it's fast if the number of parts is not very large.
if you don't actually need any ordering you can use a HashSet instead
it is fast
it will be faster
so using an id is faster?
You only use a List if you need an ordering
no
not if you need to do a loop to recalculate all the IDs
Again, use a HashSet here if order doesn't matter.
order matters
How many body parts are there in the list?
Is it more than 100?
If not, don't worry about it.
well technically with a list it's T(n) anyways because it has to move all the entries forward
anywhere between 10-30
but there can be 10-20 of those on screen. (all sperated)
Yeah but how many are getting hit in a single frame?
so 600 parts? not really an issue
sounds like you're hitting premature optimization
um can be anywhere from 1 to maybe 10 at most per frame getting hit
if you don't have issues, no need to hyper-optimize it
just don't make it overly bloated
Start with the list, if you run into problems and the profiler points to this being an issue, you can optimize it then
ok thank you
the list is gonna be pretty readable anyways; that's gonna be more important
How can i get gameobjects to attatch to a specific spot on other object, lets say attach a circle tp the corner of a square vs the center
You should not just change behaviour from running in Awake to Start to fix a bug. That makes a massive difference
Maybe share some context since, at least for me, it's not clear what the issue is
@wintry quarry
i'm getting this error: MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
pointing to this code:
var dir = (_tail[0].position - _player.position).normalized;
_tail[0].rotation = Quaternion.LookRotation(Vector3.forward, dir);
_tail[0].position = position;
for(var i = 0 ; i < tailLength - 1 ; i++) {
var a = _tail[i];
var b = _tail[i + 1];
dir = (b.position - a.position).normalized;
b.rotation = Quaternion.LookRotation(Vector3.forward, dir);
b.position = a.position + dir * constraintDistance;
}
}```
oh wait i think i know what the issue is
I think the error is self explanatory
it really is
i did exactly what you said, and you said the list protects itself from this
Seems like you did Destroy(something);
What I said was:
myList.Remove(something);```
you destroyed something without removing it from the list
so now you have a stale reference to a destroyed object in the list
what i did was this:
var item = _tail[1];
if(item != null) {
_tail.RemoveAt(1);
_tail[0].position = item.position;
Destroy(body.gameObject);
}
else {
Debug.Log("Snake Dead");
}
}```
you're destroying a different object than the one you're removing from the list
omg im destroying the wrong object
Also you should probably do some bounds checking in that code
for?
oh yeah, i will. you mean if tail[1] doesn't exist?
@wintry quarry
so from this code public void DamageBody(SnakeBody body) { var item = _tail[1]; if(item != null) { _tail.RemoveAt(1); _tail[0].position = item.position; Destroy(body.gameObject); } else { Debug.Log("Snake Dead"); } }
the line here: _tail[0].position = item.position; isn't working.
i have a manager that is running the snakes movement in update. shoud i move that to late update to get the position to change? or how would you solve it..
i would just declare array that can fit max size of snake tail, and store there gameObject which would be activate/deactivate, so you dont have to destroy them or remove list entries
that was what i was originally trying to do, the problem is that it becomes pretty complicated becasue of my snakes movement code and how it's bodies are dependent on the previous
ok new question unrealated, should be pretty easy but im not sure what to look up..
Quaternion.LookRotation(Vector3.forward, dir);
when i calculate dir (it is correctly working). how do i clamp the direction to be a maximum of x amount of degrees? to prevent turning to sharp
How is private not valid (I changed it to public and it says public isnt valid either)
Consider looking into finding a reference: https://unity.huh.how/references
Choose the best way to reference other variables.
because its stuffed inside another method
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i have no idea what that means
if only there were some sort of bot message that would give context
Your editor is not configured. It's supposed to help with these things. Pick the bot link related to the editor you use and configure it
IDE = the code editor you use to write code, in this case Visual Studio
its not configured because it should underline the error red and also help you identify issue
do you think it may be helpful, or do you think it is helpful. lol
it didnt work
you can read and find out yourself if it will be usefull for you, spoonfeeding is bad
Also there is hyper link to Quaternion.RotateTowards, which may be even more usefull