#๐ปโcode-beginner
1 messages ยท Page 683 of 1
You seem to make a distinction between "importing" the controllers, and having attached components for attack and ability. This is confusing to me.
Do you not intend on having your controllers as components?
I don't know. Wouldn't the controllers be separate for each prefab if I add them as components?
Or is adding the component the same as an import statement in script?
When you add a component, an instance of this class is created for you. The reason you make it a component(so a MonoBehaviour derived class) is because it makes it extremely convenient for this class to interact with the unity API.
Notably, it will have access to a managed transformation matrix via the transform component
magic methods awake/start/update/etc will be fired on this component, allowing convenient synchronization with other objects in your scene.
Now, if you create 1 controller class, and you add it to 20 objects, yes it is a bit like importing a library but with the exception that each instance can have per-instance data.
character stats -> usually best as a scriptable object
model -> the various prefabs for the model
base prefab -> has all the controllers/ components on -> spawning just assigns the model prefab and relevant data
Ah so I can add the controller as a component and if I change the controller each component will be updated accordingly
awesome, thanks
and thanks everyone else too
Hello guys can anyone point me to a resources or tutorial on how to connect ui buttons to new input system .Thank you
I think if you have the new input system set in your project settings, creating a new Event System will automatically set it up for input ๐ค But the people over at #๐ฒโui-ux and #๐งฐโui-toolkit will probably know better, and have suggestions for resources
Hey guys, i'm following a video of codemonkey to make a "kitchen chaos" game: https://youtu.be/AmGSEH7QcDg?si=xg9RQ5qcii3cWt-t&t=12141
To give some context, he made a Tomato and CheeseBlock prefabs, and their related ScriptableObject. I don't really understand/like that he make a reference to the prefab in the scriptable object, but also make a script attached to the prefab to reference the related scriptable object. Is there a better way to do this ?
๐ฌ This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
๐ Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
โค Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
๐ฎ Play the game on Steam! https://cmonkey.co...
The fact that the prefab is referenced in the SO, and vice-versa it feels like something wrong ?
Not really wrong. Does the prefab need to know about the SO, and does the SO need to know about the prefab? If so, then there needs to be a reference going both ways. You can have an intermediary entity that maintains bilinear bindings if you want
Things that exist in your scene need to have a MonoBehaviour to have some functionality. The SO reference is so that you can keep the "definition" of that object separated from the scene for easier modifications, mainly.
alrithy
You can absolutely just put those same fields like, the name and such on the MonoBehaviour itself and skip the SO entirely.
Hmm ok good to know then. I'm new to this concept and was a bit lost ^^
It's a matter of organization (and preference), really.
But generally speaking, if you're defining the information of an object, such an items, characters, use SOs. It'll just be cleaner.
That way you don't need to have a prefab for each food, instead you can have a generic food prefab that you "dress up", with the contents that the SO has (icon, name, model reference, etc.)
Oooh
Like the SO is a kitchen object constructor ?
But in the video he does have specific prefab and SO for each food right now
Maybe he gonna refactor it later in the video
Just to save the time and effort of dynamically preparing the objects at runtime I imagine. I haven't watched his course.
I see. Thanks for help ๐
Generally if you put the data into SOs, the prefabs become more generic and grab their specifics from the SOs. Like there's a general item prefab with universal item logic, but things like stats and visuals come from an SO it references.
Is the old input system better if m targeting only one platform?
Depends if you also need multiple maps for gameplay.
Yes and no. Depends what you need out of an input system. Like remapping controls is easier with the new, and swapping from one set of actions to another is easier in the new. But the old is quicker to get up and running with.
Fortunately it's not a huge undertaking to switch, especially if you don't sprinkle your input listening code across the whole project
Yes like the new one is good if i have like humanoid controls n also some kinda car or boat controls but if it has only humanoid controls then is the old one better?
If your game's needs are pretty simple then sticking with the old is totally fine, plenty of games shipped using it
cz m new to the new iput system n having problems on hooking it with ui buttons
i mean i dont really know how to without making a script which in the end is same as the old input sys
So if you press a controller button it should "press" a UI button?
yes like move left button or move right button
If the problem is that moving left and right isn't navigating a button menu properly, that's not specific to new or old
i mean i have key mapped in the new input system for movement i want to have ui buttons for that but cant seem to understand how to hook them
Though in the new input system there's a specific component you'll need to make sure it passes the actions to the event system for UI. There should be tutorials on using UI with the new input system
#๐ฒโui-ux or #๐งฐโui-toolkit will probably have links if you ask
yes m having trouble finding one so m annoyed from using the new input system lmao
this sounds more like a question of "how do i hook a UI button up to my movement" rather than anything to do with the input system
Oh, so you want to press a UI button and it acts as if you moved left on the controller?
i mean is there a new input system way of hooking buttons
yes
Ah, that's different. Whatever code is listening for the input action reference needs to also be linked into the OnClick unityevent of the button
you are thinking about this incorrectly. the input system is irrelevant here because UI buttons still work exactly the same
so theres no benifit on using the new one on this specific case?
None, its the same work flow to make a UI button do something in this case
yes thats all the answers i need thanks i was wondering if it makes the work easier if i use the new one on this specific task
Hello im completly new to coding and i would like to know why some lines are blue, green and white, and how you can change them if you can change them ?
colors are used a lot for highlighting stuff, what exactly are you referring to?
the color of text, colors on the left of the line, underlines, etc
For example im following a old tutorial were the line "using UnityEngine", "using" is blue, so is my line, but the "UnityEngine" is white in the video and green in my code. I was wondering why
i copied the same script but some of the words are in different colors than the video
and i have a error message so i suppose it has something to do with the color not matching?
the actual colors used in the syntax highlighting are dependent on your theme and/or IDE
so the colors do not matter ?
if you have an error in the code it is not related to the colors. but it should be underlined in red and if it is not that means your !IDE is not configured
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
tokens are colored by function
keywords are a certain color, types are a certain color, numeric literals, string literals, functions, variables, constants, etc
IDE is the thing you are coding in
ok thanks
you do know that google exists, right?
and a 5 second search will tell you it stands for Integrated Development Environment. aka your code editor (which should be more obvious from the bot embed directly above your message)
so visual studio in my case
considering you said that "UnityEngine" was green in your own code it sounds like you're using vs code not visual studio
no, colors are just to help guide your eyes
they don't affect the actual code
but if he did not change the colors it indicates that his IDe is not configured correctly as boxfriend pointed out already
(he said the colors did change)
Hello ๐
If I have a question regarding Skinned Mesh Renderer being invisible for me, is this the right channel? Or is "Animation" more correct?
Apologies if I wrote in wrong channel
First time trying to animate my player object. Making a 3d game. Ive set animations, set the correct one as default and I can see it running when I start. Initially I had mesh renderer and my "skin" was showing but, animation wasnt playing. After googling, Ive read that its due to Mesh Renderer shows static skin and that I should use Skinned Mesh Renderer.
Cant get it to work. My character is just invisible.. Tried googling it and asked gpt and gemini, Ive done a lot of different steps including dragging my mesh on the scene and applying material which causes it to appear. Cant seem to figure out why its invisible on my player object
im more likely to memorize when talking to people rather than internet. And passing knowledge like this is well more human id say
#854851968446365696
it just creates useless noise in the channels when you ask easily googleable questions instead of putting in the effort to actually find out the answer yourself
i understand that i need to use OnTriggerEnter2D and OnTriggerExit2D to make text appear when you walk close to the item's "range" but i have no clue how to correctly implement it and i've scowered the internet looking for a solution and can't find one
i know i explained that poorly
this is not a social space.
lmao
those messages require trigger colliders, does that give you a hint?
this doesn't have anything to do with c#
you need trigger colliders to specify the range to get those messages
not what i'm talking about at all, no
oh so a gameObject to specify the range
no, a trigger collider
if you don't know what i'm talking about, ask, don't assume
i'm happy to explain or link to more resources - i'm just not gonna explain everything off the bat since i don't know if you already know or not
ok please send me some resources
so i don't go to assumptions
tyty
you could also use Vector2.Distance if you just want to do something while in range
in your case you would add a trigger on the interactable thing
i can't exactly tell what was wrong im my code but my project is working thank you guys !
what is the checklist for Jump is not working?
spacebar is detected, but not working
Debug.Log your isGrounded
Was it working prior to adding isGrounded?
yes
How does your isGrounded check look?
Where do you set isGrounded
Got it working because of you, thanks a bunch!
u know the difference between OnTriggerEnter and OnCollisionEnter?
is there a trigger on the player?
odd setup i figured OnCollision would be enough
and check for ground
anyway.. put DebugLogs n collision and n ur if statements
print out what they collide with
Does this object ever pass through a trigger on an object tagged "Ground"?
ya seems weird to me.. b/c the code is checking for ground.. which implies its on the player..
but then the POlygon collider of the ground..
isnt marked as isTrigger
probably because it should be OnCollisionX2D
nice catch, yeah i also assume they want OnCollisionEnter instead
okay i have to be doing something wrong ๐ญ
how come every time i try to use the input system even if i follow a tutorial EXACTLY it says something comes out as null
-# gonna need some more info to go off...
The trouble with the new input system is there's like ten different ways to do things and if you're following multiple tutorials you've probably crossed the streams somewhere
This was more for testing but i literally copied code and only changed variables that i had to for it to work and it still didn't work
using System.Collections;
using UnityEngine.InputSystem;
public class BasePlayerScript : MonoBehaviour
{
CharacterController controller;
PlayerInput Playerinput;
InputAction MoveInput;
float BaseMovementSpeed = 5f;
float SetMovementSpeed = 2f;
float Velocity = 0.01f;
void Start()
{
GetComponent<CharacterController>();
Playerinput = GetComponent<PlayerInput>();
MoveInput = Playerinput.actions.FindAction("Move");
}
void Update()
{
CharacterMovement();
}
void CharacterMovement() {
Vector2 Movedirection = MoveInput.ReadValue<Vector2>();
controller.Move(SetMovementSpeed * Time.deltaTime * new Vector3(Movedirection.x, Velocity, Movedirection.y));
}
}```
People said i literally had to use the new input system for somme reason
yeah i was typing it
ok, which is line 25
oh sorry forgot to put that, its the controller.Move line
start with that or include it with your grievances, rather than sending just the greivances first
controller is null, you never set it
Instead of InputAction use InputActionReference and make it public or serialized private, then you can skip the FindAction and set it in the inspector
Won't fix your problem, but its an easier workflow
it show error on using OncollisionEnter2D
yeah i did its set up at the top
where?
that's declaring the field, that doesn't give it a value
why did it work for the tutorial but not me then ๐ญ
because it set it somewhere else lol
check your Start
you have a GetComponent that isn't being assigned to anything
Tutorial videos are edited, they can make garbage code look like it runs sometimes, if they' want to
did the tutorial also have a hanging GetComponent that didn't do anything?
hey atleast this time it wasn't the input system
GetComponent<CharacterController>(); that's missing an assignment there
well i thought the "CharacterController controller;" set it
it does not, no
yeah i just thought it got the component i didn't know i had to set it there
characterController = GetComponent<CharacterController>(); is what you want
do you know the difference between float x; and float x = 5;
yeah i changed that part already cause i saw it but
controller = GetComponent<CharacterController>();
why do i have to put "CharacterController controller;" at the top if im already getting the component and labeling it as controller in the start area?
because that's how c# works
you have to declare variables
this is, indeed, how most languages work
Because you arent getting it. You are making space for it and saying its existing but, you still need to set the value to it
the exceptions being js and python, as always
Difference between declaring a variable and then assigning it. If you don't declare it before you use it, c# compiler won't know what you're trying to do
I mean yeah i kinda thought that i was declaring it and setting it to controller in the same line
what errror?
You can't just say bob = 5 because you have not declared what bob is. Is it an integer? is it a float? is it an enum? compiler doesn't know
the message parameter has to be of type: Collision2D
yeah i didn't know it only declared what it was i thought it assigned it too
declaring and assigning are two different things in the beginning everyone gets confused on
but yeah anyways thanks for pointing out my stupid mistake ๐ญ
the character controller might not exist at the time the field is declared
or it might be intended to get some other object's controller
c# doesn't know what you're trying to do, it's not gonna assume something like that
Well yeah but i thought it was like how you do "float movespeed = 1f" or something like that and it declares it and assigns it in the same line
Well, without it, where do you intend to put it
You can do that for some item sure
Yes but, you said the name but, didnt assign. So you must assign later
let instellisense do the work, if you type OnCollision it will give you the correct suggestion
You get the component in start, but it's gotta go in a box. You can't really hold water without a cup
if you didn't have the declaration, well that wouldn't be valid in c#, but it would be in some other languages
in those other languages, the variable would then only exist inside the function (or the scope), so you wouldn't be able to use it in other functions anyways
anyways i am gonna go back to coding cause somehow i broke every single bit of code in my previous script so im rewriting all the code ๐ญ
the = is the assignment
you don't have the assignment here
That line contains a declaration: float movespeed; and an assignment movespeed = 1f in the same line
this works because you aren't calling a function in the assignment
You can't do CharacterController controller = GetComponent<CharacterController>() because you can't call a function outside of any functions
(a declaration and an assignment in the same line is sometimes called an initialization, or more broadly, a definition)
even if you did
magicNumber = 3;
it has no idea what magicNumber is unless you declared it
but some types can be inferred such as
var myNumber = 40; then var is now a int
the reasoning here is simply not correct
How dare c# not let me make magicNumer = 3;
Okay, you can't call non-static functions outside of a function but I didn't want to confuse the matter by bringing statics into the mix
its a good thing being statically typed
then make it static ๐
(im ngl im never touching statics unless i have to this was sarcastic)
this is still not true?
Nothing wrong with statics
i dont care i don't like what i don't understand
statics are like seasonings, you don't want to over do it
this is valid c#, just doesn't work with getting components because of how stuff is initialized
they can be pretty powerful you'd be missing out
i tried seasoning cereal before and it tasted bad
Static just makes it so you dont have to initialize a class in order to call a function. Quite helpful if function isnt accessing any instance data
try cocoa instead of salt 
how did you know i used salt
it's the only seasoning that would make cereal taste bad
We use statics all the time. Mathf is static
i'mm sure i could find a way
and that way is fish sauce
In all fairness i haven't used Mathf once
Singleton walks in the room
some Vector2 and Vector3 stuff are also static, like distance
You see, I always assumed it was the GetComponent itself that made this not work. Turns out it was the implicit this.
"There's only one of them! Gang up, we can take 'em!"
So, yeah, you're right. I thought you just couldn't do these UnityEngine methods in an initializer
aw man that means i've used static things before ๐ญ
yknow, that's fair, i assume error messages/causes without checking all too often lmao
Yeah, I had an intuitive sense that it wouldn't work and didn't actually question it after finding out that it did in fact not work
So I never considered why it wouldn't work
there is nothing to be frightened by them, they are like every other type except only 1 of it can exists through the whole program which is a good thing
i always just consider that my code doesn't work because i make it ๐
It's funny how code beginner often devolves into more advanced discussions because we get pedantic over someone simplifying an answer ๐
๐โญ The more you know
well yeah i know that i just dont like them
atp i know more about advanced stuff than simple stuff because of this
you will once you realize the benefits in your own code
often its just hitting situations older devs never hit since they think more inline with how the language works
just because i will use them in the future doesn't mean i will like them
fair enough 
so realistically its ok for me to use keycodes for jumping because i don't like people who dont use space for jumping right
you mean enums keycode vs strings ?
realistically? your first game probably isn't going to get enough people for it to matter
ideally i would just use the new input system and tie jump to a action
You can learn a lot of physics by assuming spherical cows in a frictionless vacuum.
Sometimes the simplifications can actually reveal novel ideas
then it can have multiple buttons and easier support for rebinding later on
yeah but ideally i dont like people who want to change jump off of space bar
KeyCode / Numerical values are always faster than string lookup ofc
yeah and like who would wanna use something other than space for jump you know?
speed runners and people that found out how to abuse your physics and bunny hop around
depends on the game I suppose, hence why rebind as an option is always really nice feature to put..
I put my jump to my mousescroll for bunny hopping and stuff
or simply for accessibility reasons
consider Mathf.Max(a, b, c)
if it weren't static, it'd have to be like a.Max(b, c)
now if you want to remove a from the possible options, you'd have to rewrite the entire thing instead of just.. removing it
statics make way more sense for symmetric stuff like that
funilly enough i was planning on making bunnyhop a feature of my game so that if you press jump within enough time before jumping you would bunnyhop instantly and not get any ground friction
well that api would suck best to just have it as a regular static function, also this lets you easily have overloads to support all the int/float types
keep in mind true bunnyhop is a side effect of specific movement controls
i accidently made a character controller that supports it
yeah but replicating bunnyhop does seem kinda easy
a lot of speed runners put it in now as a feature yea, idk about easy but good movement can take months sometimes to tune nicely
the OG
my idea to make good mmovement easily is to make it so bad that its good (obviously not bad as in a buggy way though)
at work i had to make the controller for a 3d platformer and yeah it was like a months work to get all features we wanted working and provide intuitive parameters for design
most of what i exposed is rearranged equations to expose more design friendly terms
instead of the actual physics of it
yeah character movement really can make the game, if a game has poor movement I usually don't play it lol . Source games nailed it after quake imo, idk much of recent times whats good.. I guess Apex and such
newer games are more restrictive even atfter all the parkour-ish mechanic like climb walls ala COD
still makes me dizzy
yeah goldsrc and source are my standard for what feels good for fps movement
haha yeah dude has probably years of experience, I can maybe move half that speed
is the keycode for space Input.GetKeyDown(KeyCode.Space)
good choice!
back when i played the og quake.. i didnt even know u could move like that
edit: my gamepad certainly wouldnt have allowed me to do that..
yeah I accidentally discovered it because you can't help it since it happens while you look one way while you press forward + strafe another
well quake is the grand daddy of most of this movement tricks, and also the reason they work in a lot of modern engines
ya, it was a gem i wasn't even aware of.. ofc iwas in my Tween years
quake with a gamepad! blasphemy
a lot of engines were derived from or stole from early idtech engines
i wasn't as professional of a gamer as i am now ๐
one of the first gamepads i seen on the market..
had the big printer port on it
midi port
COM connection
remeber my first joystick i had to attach to the soundcards midi
even had a little joystick u screw into the dpad ๐
with the gamepad i wasnt aware of all the movement mechanics u could unlock
like bunnyhoppin
I had this one
didnt know bout that until the very first time i seen someone speedrunning it
big as a house
lol
the "original DUKE"
too young to have seen this in person but every time i see a pic i feel like it could be disconnected along the diagonal and reconnected into a different shape lmao
yeah i was big into QWTF, then Q3A and then TFC back in the day and learned all the movement tech
back when microsoft made good hardware
back when most hardware was still Beige
so thats what this is?
i mean i remember it coming thru the com ports
thats COM port yes
back when u had to set up ur inputs before the game started
MsDOS games were the best
midi usually is like a round thing looks like PS2 connector (not playstation, i meant he mouse)
yup
im actually working on a rebind system like that
where u start eh game.. and then it asks u for each bind
so u can use any device
might be what i actually do today
are a few forms of it, this thing you could plug a game pad into, or with a dongle it breaks out into the midi in and midi out
with the round plugs
oh yea.I haven't played much with MIDI besides music
for rebinds would u store that info in a data file to load? or would u do it every time u launch?
the round midi ports are too big for a single height card
im thinking like a fpv drone simulator.. where u can use rc remotes and etc
file
any device
File.WriteAllText
boom done
yeah was used for games, since there was no good system for low latency inputs before, but music already solved that problem since its more important to music then general computing at the time
this is what i got so far :).. lol
then it would go "Rebind Action: Blank: -> Bound to X -> Confirm
yeah that makes lot of sense, since MIDI is really good at keeping instruments synched and latency free
yup, back when PC's were magical
and my dad was a wizard
now its reversed ๐ and i help my father build his stuff
yeah since otherwise it was use a serial port which sucks, and the ps/2's were only for keyboard and mouse with the limitations of those
new Input System ? that should cut a lot of work ๐ช
USB did not exist yet
thats the plan..
with InputActionReferences
dark times
is this the defacto way ? cause I use C# Generated class but have no idea how I would rebind that
also those round midis are still used, my audio interface has them and it can talk to my outboard gear via it
id ont know.. but its the way imma try
i have vague information from a big-head around here that thats how they do it
so i figured id be a poser
Yeah same I still use those for my MPC pads and stuff, much better than USB for me since they can be connected to analog instruments
its possibly Contrivance ๐
heh
There's so many ways to use the new system, it's a strength but also a learning curve
makes sense.. Yeah that might be the way cause I'm not sure how I would even rebind things with a generated class
there is runtime support for adding inputs to actions
really the hardest part about it is making a ui for it
There's a helper in the new input system for rebinding, which makes it super easy. You turn it on and it listens for what the user does, and maps to that. And you can filter out certain inputs too
I think there is a github project unity has for rebind example ?
ah yeah was thinking something like thi existed
could've sworn i did see it
I forget where in the docs it was, but searching through for rebind should find it for you. I tried it out once and it was very simple
one thing you gotta give unity is eventually they do make decent utils classes to easily work with their new features
I'm not sure how to save the rebindings in the player prefs, but it should be possible somehow
im hoping i can just do a prompt for each rebind
that way theres no UI really..
unless ur meaning UI navigation rebinds
maybe there is a JSON schema or something ?
You can. The rebinding helper has no UI, it just waits for player input of some kind and assigns that to the action
niice
followed this guy's tutorial (https://www.youtube.com/watch?v=OQ1dRX5NyM0) on enemy FOV and this ``` private Vector2 DirectionFromAngle(float eulerY, float angleInDegrees)
{
angleInDegrees -= eulerY;
return new Vector2(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
}
``` is showing errors, saying top-level statements must precede namespace and type declarations and the modifier "private" is not valid
In this video ,we're going to be taking the 3D Field of View system from my previous tutorial and converting it to 2D! Good huh?
Join me and learn your way through the Unity Game Engine, the C# language and the Visual Studio editor. Remember, if this video was useful then DROP A LIKE! ๐
๐ฏ Want to help me out and allow me to keep making t...
i just mean the general UI for showing all binds and supporting multiple binds per action often gets complicated to do in a non rubbish way
ohh u mean that
you put this inside another method did you
yea, that will be a dedicated UI panel
also if you want to support different sets for controller vs keys/mouse
i hopefully get it setup where u can use 2 devices at once.. if u felt like it
also the swapping of UI elements for controller vs keyboard mappings
like bind ur Joysticks for movement..
check your curly brackets, also make sure your IDE is configured @lapis parrot
alright
it probably is that lol, my code is super messy
Also the rebinding supports multiple keys, like shift+F11 to do something
bind shift+alt+print screen to jump
You can prevent it, the rebinding has filters
public class Foo{
private void Method(){} // valid
}```
```cs
public class Foo{
private void Method()
{
private void Method2(){} // error cause of private
}
}```
ya, i might ignore it for now
if i see a reason to need hotkey type stuff ill figure it out
i already made an Editor hotkey system but it uses the old input class
and nested ifstatements
I think the big win with having a rebind system that accepts any input is accessibility devices will just plain work. If someone gets one of those special multi button controller for accessibility reasons, the system will just figure it out for you
You can export rebinds to JSON and import them back later IIRC, there are methods on the input actions
ahh nice so I assumed correct
yes!! this is what finally made me turn
i have an RC controller.. and uses HDMI or w/e the basic periphial port thingy is..
but its inputs are ALL over the place
so a rebind system is about the only way i can remedy that
w/o manually hardcoding everything
makes cause when you do Generate C# class on the Actions Input it generates a JSON schema inside that class that you don't touch and gets regenerated, I suppose for rebind is you saving the JSON part
Is there a way for something to check if the controller is grounded once
boolean flag?
*groundedOnce = true, false
it'd be the exact same way u do for multiple jumps..
i wanted to do a boolean flag but i don't know if i should make random boolean flags for anything i dont know how to fix without one
canJumpAgain = true
most times you will be using bool they are the most common and useful types in any logic
yeah ik my current issue is that i cant jump because it sets the velocity to -1 when its groundedd
well when u jump stop that
hell before I learned a proper FSM everything was bool flags xD
when u jump u should zero out ur gravity anyways
its the common way to do that... that way ur jump force isn't cancelled out by any of it
ive still not learned proper fsm
well ig i'll just add a boolean for it
its still a switch statement...
i dont know what fsm is ๐ฅ
1 step above if else chains
finite state machine
ur controller would work based on states..
Yeah I mean no reason to overcomplicate it if you can just enum based
idle -> moving -> running -> attacking etc
the main reason i chose to completely redo my old code was cause i had 300 lines of just if else going on and on ๐ญ
well, to be honest i'd like to master Stateless state machines
but ill keep dreaming for now
Infinite Stateless Nonmachines
dont even ask how i did it i dont know myself
we know.. we all been there
have you tried new Behavior tree unity has?
well when i nail state machines then ill try out the behaviour tree
i still need to mock up a good one w/ Enter and Exit states and all that
Unity lets you do custom nodes so its pretty powerful
pretty much
well.. i assume the conditions would be codebased but yea
bookmarked ๐ช
most of them do what you want
ill give it a look thnks
unity has this concept for behavior to "tell story" through action
so like "Enemy waits 4 seconds then moves to target"
rather than a bunch of variables and code clouding the whole thing
check out Llama academy he has a whole series on Behavior, its really good. Hopefully unity doesn't abadon this too cause I heard most of the team got axxed and now this project is kinda in limbo...typical unity shit lol
i just realized my code wasn't working cause i set a float to a bool what the fuck am i doing bro
do you have a configured IDE... it should be underlining red when you do that
i didn't even need the bool for if the character was grounded or not i genuinly just fucking had the jump power as a bool
thats the problem i didn't even fucking notice until i scrolled up ๐ญ
it was giving me errors and everything and i didn't even notice
i need to go to bed bro ๐ญ
are you looking at the error in Unity console or the actual IDE / code editor
there are errors in both ๐ญ
ok good at least IDE is configured
u shouldnt be able to even compile that
back to VSC squad ? ๐ช
what does compile mean like turning your code into something unity can use
you know it!... recorded a few videos with Studio.. then recorded a short moving back to VSCode
now studio is ๐จ
yea for a lack of a better term
when u save u code and click into unity,
that little progress bar is it compiling all the code
what progress bar
if u have something that wont compile u get that error..
"Fix all Compile Errors before entering Play Mode"
umm this one?
oh
every time you mess with the ingredients they have to be correct otherwise unity cant bake a delicious cake
i never notice it
I don't think unity can do that..
humble flex
bro got windows 40k
hopefully it bakes cakes faster than lights
maybe next time i shouldn't ignore the "fix all compile errors" and i should think thats the reason my movement completely broke and not the fact my jumping wasn't working
ur game wont even run w/ compile errors
well you wouldnt be able to even hit playmode if it can't compile
yeah i didn't notice the fact it literally wasn't running i just assummed it wasn't working ๐ญ
it will give you a warning popup tho
i am way more dumb than i thought
yup compile errors are errors in the code itself (like code that wont work at all)
runtime errors are code that works but may not work correctly
runtime errors will show during playmode in the console..
compile errors will not.. (b/c it cant compile to know whats wrong)
that why we then refer to the IDE
and let it help point out the errors
so like things that are set to null? (so far aside from setting a float to a bool for some fucking reason that has been my only real error)
ya, those would be runtime errors
makes sense
yeah the thing i've gotten i think like 7 times now
i dont think im good at coding
happens to all of us at some point lol
5 years in and im still not good at coding
but i can make things happen!
just not Optimally
Well you can be horrible at coding and still make a good game it just takes longer and isn't as good
its a good thing, it tells you at least you gorgot to assign something.. Some people do put Null check which hides an error showing up but item might still be NULL and not what you want..
true... players cant see ur code ๐
as long as their concerned it either works it doesnt
Undertale is horribly coded. But a great game
i would argue that Celeste is also coded horribly
The player is a god class, if I remember correctly?
yeah my only issue is that idk if i can make a 3d game thats supposed to also have good graphics with horrid code
the entire game lives in the player class ๐
from what ive heard
idk how much bad code affects performance so idk how much i have to focus on it
good graphics and code completely different topics
never focus on optimizing unless u have to
yeah but if the code is bad enough i wouldn't be able to run the game at all so like
thats the word around here
it can affect it at a lot, but not something you should worry in the beginning
ok im gonna welcome 300 if else statements back into my code that i dont even understand ๐
Well there's bad code because its impossible to understand and maintain, and bad code because it's doing the work all wrong and inefficiently
if statements are cheap, last thing you should worry (performance wise)
well u have to use a bit of common sense
make it 150 and ill call it good
1500 take it or leave it
ur entire class should never be that big
also you can't make it illegible and confusing for you and your future self, thats what also makes good code
if it is.. ur doing something wrong ๐
back when i first started i had a character controller that was 2500 lines long
Good point
well
that does sound like what im gonna end up having but
ahhh the memories of Monoliths ๐
My level builder editor tool is around 2000 lines, but its just editor code so I don't care
I mean some of Unitys classes go over 2000+ lines
Is it at all possible to import/use an image larger than 16k via code? (ie. read the image directly from disk or something?)
So quick question for later should i make different selectable characters have my base player script as a parent or should i use the base player script and hope that 2000 lines of code doesn't break the game
a level builder i wouldnt expect anything less than 500 lines
2000 lines wont break the game.. it might break ur sanity
u basically want to worry about readibility at first
make it readible.. make it understandable
dont shoot urself in the foot
good enough i'll use one player script to control like 12 selectable characters this will only turn out good probably
it just makes it difficult to debug if you cramm so many things in one spot
I have done this before
well i dropped a knife on my foot but basically the same thing since its an expression
theres no way someone can forsee every issue or bug
well no im being serious
superhuman ๐ฆธโโ๏ธ
You can only learn by making mistakes and correcting them
yeah i've learnt to never hold a knife loose
well.. then u should practice trigger safety
well like i said it was a knife that i dropped and not a gun but still
anyways i am gonna go back to coding though since i have a lot more code to rewrite
๐
have a good day guys im getting off discord for now
lol make an automated knife that slices you every time you make a code error
u do the same
ngl.. that'd be some really good reinforcement learning
The rule tile in earlier iterations was a monstrous beast of a class that was defnitely over 2000 lines
doctor, i dont need to go to therapy.. thats not what it looks like.. im just a bad coder
rule tile.. as in tilemaps?
Its mostly a lot of boiler plate, since all the hoops you have to jump through when working with editor inspectors
i figured thats abunch of classes
Yup
๐ i bet thats a crazy looking class
It is now, a lot of it got moved out into the base class. But I remember when all of the conditions for neighbours were in it, plus it was doing some funky bitmapping to generate the inspector icons, so that you didn't need separate texture assets
You can with override tiles. The rules can be anything if you code them into the override tile implementation. In the basic rule tile it's just if the same tile is a neighbour, and where it is in relation to it
i have total respect for anyone building tilemap based games
not my cup of tea.. but impressive
sounds like that algorithm.. whats it called...
wave collapse
something
My 3D dungeon crawler uses tilemaps to automate the arrangement of 3D assets in each cell of the map. Its super useful for that, but only that, as there's no 2D sprites
that's for procgen, which isn't a requirement for most tilemap games
ahh
But it does use rules, so its related
okay.. for whatever reason i think of the two as being similar
probably the most intimidating algorithm/function ive encountered so far
The rules for wave function collapse are a bit more extensive, since you're not just determining what variation of a tile fits that position, but what other tiles are allowed to be near it
like shore can be next to water and land, but water cannot be next to land
Im returning to unity after a few years and ive tried to make a first person controller but I cant for the life of me get a camera controller that 1 is smooth (and not choppy/lagging behind) and 2 is compatible with the player (if I look in a circle and hold W down the player should move in a circle, not a straight line) could anyone please help me?
@fiery swift
Quick question about Visual Studio Community 2022, Why does it keep telling me to make random things readonly?
because if you only assign it at initializer then it can be readonly since its not assigned in other places.. its not a big deal if you don't
Oh
micro-efficiency
- prevents it from being touched accidentally from other places so its also a form of that
Yeah i dont really see much of a point in that but i might use it in the future if i ever have to i guess
makes sense
basically you're saying (in code) you can only assign it here (initilizer / constructor)
im not using the character controller, I tried to make my own rigidbody movement
fine
this is a pretty complex topic
not really
then why are you here lol
because idk how to fix it
is there a specific reason not to use premade character controller
yup
i feel like the rb gives you much more control
yes but I want to use it because Im trying to preserve and move physics and momentum between different places like in portal
imo Dynamic Physics based RB is less control because you're dealing with outside forces affecting it
those are things that most controllers simulate rather than relying on inbuilt physics
wdym
pretty rare for characters to have dynamic physics based rb, thats usually done for Active Ragdoll type controllers
things like momentum and velocity / acceleration can be easily coded but you're more in control of it rather than the physics system
but I want physics
the whole point is to make it realistic and physics based, it wouldnt be fair for the player if I could magically alter the characters velocity
what specifically about physics though ? more things need to be considered with dynamic bodies especially the execution order of events and where certain thiings are called
"realistic and physics based" this is vague
solutions like KCC exist for a reason lol
why comment on how I want to make my games? If you cant help me just say so, pretty unnecessary to slander my stuff if youre not going to help me
if you believe Im slandering instead of trying to understand what exactly you want to do idk what to tell ya bud
how's that slandering ?
using the word Realisitc in a video game is pretty hilarious, what does it even mean lol
...what slander?
okay maybe not slander, but not help either
Your statement is vague. "Realistic and Physics Based" describes basically nothing
i think you know what realistic means
It's a request for more information in order to answer
i cant help if I dont understand the exact features you deem "Realistic" etc
Unity's built-in physics aren't "realistic", they "realist-ish". If you want realism you're going to be doing Kinematic RBs and computing the math yourself
dude youre acting like an ai who cant think for himself. I already explained this. preserving momentum and velocity is not the kcc's strong suit
well if you look at the channel name were talking in, you can see it says "codebeginner"
KCC handles momentum quite well, actually. It returns the velocity as an out vector after doing any processing on it so you can store it wherever
well I dont think so ๐คทโโ๏ธ so id rather use a rb
Yes? Which is why you were suggested easier methods than doing all the math by hand
But you don't want to do those
KCC is still a rigidbody, is just kinematic where the forces are done for you to have more control
i think you misunderstand Rigidbody is not necessarily dynamics only
yes believe it or not, I dont want to recode my entire movement code. Id just like a camera controller, but now you two are making it about something else for no reason at all. Why keep up with this if youre not going to help?
the movement code plays a big part on how the camera behaves
especially the jittering thing
I don't even know why I'm trying to argue with you about how better to phrase your own problem, if you don't actually want any answers I don't know why it would matter to me
@fiery swift could you summarize your constraints and goals
forget it
very strange..
not really
Mate you have the maturity level of a teen, look i get it but its not gonna get you anything to be that way to others who are trying to better understand the problem / possibly offer alternatives
In few seconds in this clip, my camera script applies a weird "snap" motion. It always does this when I enter playmode once, but after that it works normally. What's up with that?
get offended or thinking someone is being critical just by asking some question is a weird flex..
You can see on the inspector I read the mouse delta values and rotate the camera based on those
Probably because it's sort of "queueing" a bunch of mouse movement from the time it takes to load play mode
if it only happens on startup, I wouldn't really worry about it
Yeah I thought it might be something like that
you should probably show the code as well
yeah it might be accentuated by Time.deltaTime
well if you look at my original message I explained my problem and asked for help, you told me to use an entirely different controller which would be a big workaround and then got defensive for some reason when I explained why I wasnted to use a rigidbody instead
Yeah, the first frame is gonna have a really big deltaTime since it takes a while to load up
the reload domain actually occurs after some loading so the deltaTime is gonna be way bigger than normal
weren't you asking for a different controller in your original message?
void Update()
{
PlayerMove();
}
void PlayerMove()
{
var inputDirection = gameInput.movementInput.normalized;
Vector3 velocity = (transform.forward * gameInput.movementInput.y + transform.right * gameInput.movementInput.x);
transform.Rotate(Vector3.up * gameInput.mouseDelta.x * Time.deltaTime * mouseSensitivity, Space.Self);
transform.Translate(velocity * movementSpeed * Time.deltaTime, Space.World);
float cameraTilt = Mathf.Clamp(gameInput.mouseDelta.y, -0.5f, 0.5f);
playerCamera.transform.Rotate(Vector3.right * gameInput.mouseDelta.y * Time.deltaTime * -mouseSensitivity, Space.Self);
}
yeah, don't use deltaTime with mouseDelta
your mentioned a few things but it was very vague, also suggesting using a premade controller is totally valid. since some people want something that "just works" rather than having to recode an entire controller.
most controllers are not that unique and can be easily extended on instead
nope, just a camera script/controller. not new movement
spoiler alert : Movement is related to the camera
it won't solve the issue (it wasn't really an issue to begin with, just first-frame things) but that's just a latent issue that happened to make the effect stronger (and it'll make mouse input inconsistent with different framerates)
Yes I know, thats why I had the issue... Even though theyre related theyre not the same thing
like, just the rotation aspect? im confused what exactly you're looking for
they're not but how you move the character and how you rotate the camera very much matters
You will probably need to change your math a bit, your mouse sensitivity number probably needs to increase
(probably the opposite, since it had to counteract deltatime before)
Should I use FixedUpdate() here?
I had a rigidbody based movement and a separate camerascript, but no matter what I did the camera either 1 jittered or 2 didnt update the player rotation.
no, input is framebound
you should not be using the input.x directly
you should use a separate value you add onto
Oh, right. I am not firing on all cylinders today
mouseDelta is the distance the mouse moved since the last frame
rotate( mouse.x * speed) // no good
//better way
compoundedValue += mouse.x;
compoundedValue = mathf.clamp(compoundedValue, min, max)
rotate( compoundedValue * speed)
is it common to use a Struct to grab input / frame? and then read from the struct?
ive now seen this twice..
it seems to be a common thing in tutorials, ive seen it a lot of times
well, not a struct, but an intermediate class that grabs the input
public struct FrameInput
{
public bool JumpDown;
public bool JumpHeld;
public Vector2 Move;
}
ah okay.. just curious i think i may start using my inputs like that
seems clean
private void RotateCamera()
{
// get our input
Vector2 inputValues = new Vector2(Input.GetAxisRaw("Mouse X"),Input.GetAxisRaw("Mouse Y"));
inputValues *= lookSensitivity * smoothing;
smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x,inputValues.x,1f / smoothing);
smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y,inputValues.y,1f / smoothing);
currentLookingPos += smoothedVelocity;
// Clamp the vertical rotation to limit the angle
currentLookingPos.y = Mathf.Clamp(currentLookingPos.y,-verticalLookLimit,verticalLookLimit);
// rotate the camera on its X axis (up and down)
transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y,Vector3.right);
// rotate the player on its Y axis (left and right)
controller.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x,controller.transform.up);
}``` heres mine... as example / code review *putting myself out there*
mm... I think the usual approach to inputs is to have 1 class that does stuff (say character movement), and another one that gets the inputs and converts them to whatever the first class needs... idea being that if you wanna do AI, it won't use inputs, but it'll tell the same class that does things what to do
ya, the reason i asked.. b/c the structs in the same class as the movement... it just assigns it to a struct it then reads from.. during the input() loop
Yes I do that as well
yeah this is mainly why I just make methods that accept a value rather than referencing input classes
public void Move(vector2 input)
this can come from player Input, AI etc .
yes this is a mistake that i realized a few days ago lmao
my player controller is tightly coupled with input and i had to make a "mirror" kind of enemy with a completely separate script lol
had to then sync some changes that affected both
i guess if i wanted to use the input from another class it'd make more sense
if you just use the struct as a replacement of a few fields - it's almost the same, so up to you I guess (I wouldn't bother with a struct unless I wanna be sending those around together as one thing)
ahh polling, its been a while..
ya exactly.. okay same page
Tarodev's platformer code
nice to stretch the legs.. and poll every now and then ๐
lol
not that it matters, but wouldn't a class be increasingly more performant as the amount of input actions grows
not one every frame, just one that has fields reassigned to
yes, but to clarify, that vector should (probably) be world space... not the x and y input axes
isnt the Struct more performant since its all on the stack ?
all the fields are value types anyway
ya, if i were to grow the struct i'd probably just swap to the input system anyway
events > pollin
struct is more performant until you need to copy a very large one
true dont make it too big
coo.. coo..
with a struct you would have to copy all the values around the stack every frame
only my savedata structs are any bigger than 3 or 4 values
but maybe you can create smaller structs, I see thats what unity does a lot
and those get loaded in at menu screen
struct within struct
with a shared class reference you only have to copy that once to share the reference
structception / structursive
I do use some large structs, but because I'm less concerned with speed and more about garbage, because I use and throw these structs away at a fast rate
As classes they'd spew garbage constantly
generally the performance considerations should come after profiling and detecting issues... everything else is kinda guesstimates, it really depends on usage
yeah to be clear i'm talking about like 3 extra MOVs
nothing that matters, just theoretically
-# ai 2cents
there isnt really a reason to use a struct there. you dont really need structs in many cases at all
cool cool.. thats all i was really wondering about...
yours falls under a few of those categories but does not "logically represents a single value"
i dont see it very often.. but when i do its liek chris mentioned.. and its usually in tutorials
(is there interest to discuss at this level? i feel like a containment thread would be appropriate lol)
or github code
I'll just note that one should treat these more as guidelines than strict rules.
structs are must if you're doing Netcode
they are optimal to send over the wire
you don't want to be sending reference types over the wire
RPC did not support class types
I'm 97% sure you can extend it (implement some interface or something) to handle classes... but also my approach is: just go with what's easiest, until you have a reason to be "smart"
well yes, this is under the "design guidelines" section
Fair, I just feel it's always worth reminding people there are no strict rules in programming, and there are many valid ways to do things ๐
ahh now that makes sense
why is yvelocity not resetting to zero?
That is zero... kinda ๐
no idea what and how is setting it.. but yeah, that's (most likely) 0 with a bit of float imprecision
that's a value that's very very close to zero
if i had to guess, it's the amount of gravity that can be applied within 1 tick
but that's kinda a poor guess without actually seeing code
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
but yeah it's probably just this
is there a really easy work around to get enemies to follow a predefined path instead of calculating rays around them all the time? im trying tomake a pacman ghost ai but it would be so much easier with a path
-# i mean if you re-implement the original AI that'd probably be easiest, with everything being on a grid and such
true story..
good watch regardless ๐
if u use normal pathing it wont be similar to the original.. it'll be soo much more predictable
yeah this is what i was thinking of lmao
well, maybe skip the skewed randomizer lol
well i take that back. (normal pathing would be fine)
but u'd still want waypoints and some kind of behaviour tree
to have the ghosts move unique from each other
how do i fix this?
Switch the input to old if you want to use the old Input class, or use Both
what is new input class and how do i use it, i'm just doing what i saw on the unity essentials guide
its just updated system, it has better features but a bit of learning curve cause has multiple ways to work
most tutorials still use Old if you want to use new there are guides to do so, and documentation. Having it on both you can learn a bit of new one
how do i use the new one
thank you
how do i switch the input
it tells you in the console message, Player Settings
where is that, very new to unity sorry
yes make sure to google as well for these.
Edit -> Project Settings -Player
oh lmao i just found it right before you sent that
am i blind i can't find input handling ๐ญ
nvm
why doesn't this work, doesn't Transform have a position property?
bruh I forgot the index
nvm
Transform does, but Transform[] does not 
Hello friends, I come for humble guidance once more.
I'm making a game that uses projectile physics to interact with enemies.
Projectiles have weight, bounciness, and speed
Enemies have weight as well
I've set these up as custom fields either in scriptable objects or monobehaviors, but I'm sitting here looking at the fact that some of these concepts are mirrored - projectiles and enemies have RigidBody2D which has weight.. and now I'm learning about PhysicsMaterial2D, which has its own bounciness.
Since my game IS physics-based, I'm somewhat thinking I'm hurting myself by recreating physics concepts, and I should use the built-in stuff.
What do you think?
yeah lol I forgot to add [i] after spots
Depends on how physics based your game is but i'd maybe prototype using the built in stuff and see if it's neccasary to roll your own stuff or not
Yeah that's.. kinda what I'm leaning towards
no reason to believe it doesn't work for me
plus I don't have to worry about keeping my scripts & editor in sync
lets say i have a room list for players to join, currently its 50 at maximum, ofc i need to refresh it at a constant rate , maybe 30sec or so, what ways u guy recommend, performance wise
- destroy and respawn
- object pooling it and do 1
- store them in a list in first invocation and then modify the element in the list (which is what im trying to do)
3 for me should be the cheapest method among others
If you do 1(in 2), it's not pooling. 3 is a basically pooling.
What object here are you refering to, considering for pooling?
2 is object pooling, but will recycle instead of destroy directly
ok i think i gonna do 3
ty i think i know what to do now
๐
Isn't this out of game? Performance is unlikely to be particularly important.
Hello, has anyone faced the issue where when building for Android just stops at first scene? Like there's no errors or anything but build just freezes and in task manager it says editor not responding
It just shows "building scene 0" endlessly
You can check the editor log, see if it has anything interesting. But other than that - no idea.
How to get that when editor has freezed mid build ๐ซ
Even cancelling doesn't work, have to restart the editor
Wait wat? I thought we only get it in editor, gimme a second I'll check
In unity I am using HDRP 17.0.4. My project is a flight simulation and terrain is from cesium. I have implemented volumetric clouds in my scene. Since it is unity then I have to origin shift the whole environment. But the volumetric clouds are not origin shifting properly as they are jumpy each the origin is shifted.
Below is my script that I have implemented for origin shifting the whole environment including clouds.
What's a simple way to do local avoidance in 2d with Vector2.MoveTowards?
Is there any way to find an available path to the left or right of an obstacle?
Or do I just throw out several linecasts until I don't hit an obstacle, then move that way?
Or is it possible to do a ShapeCast and then calculate the best new target position from that?
the overall idea is to split the area into a grid. check which grids have obstacles in the way. then use an algorithm like A star to find the shortest path
It's a little difficult to explain over discord, you might want to look into pathfinding in 2d
that's not what I want to do at all ... my units know where to move, I don't need pathfinding
I want them to go around moving obstacles on the way (this is called local avoidance)
what this means for my game is, my units are moving to a fixed point with Vector2.MoveTowards, this works
but other units are also moving to that point and back, around it, ...
I just need a simple way to make them move left or right a bit, so they look like they're avoiding each other (read: not all my units are stacked on top of each other)
doesn't need to be perfect at all
if we're talking about some arbitrary obstacles, then this is an issue with your pathfinding. they shouldnt be trying to move into arbitrary unknown obstacles in the first place.
Otherwise its entirely up to you how this avoidance should work while making sure its still going to be on a valid path after taking a detour. If you want it to just move left or right, consider changing the direction based on the normal of the surface infront of it. theres no guarantee this is a valid path though
it would also be very easy to draw up cases where this fails entirely
yeah that's exactly what I'm asking, how do I "change the direction based on the normal of the surface in front of it"? I don't really know what that means or how that works
I've looked up some tutorials, but none of them work with Vector2.MoveTowards
and I'm extremely bad at understanding the logic/math behind movement
I'm not sure what MoveTowards has to do with this. Its just a function to manipulate a vector. It doesn't move anything.
The normal is the direction facing outward from a surface. You can get it through the physics casts
the tutorial I watched just made the unit move forward and adjusted the rotation
which doesn't work for my game
but how does that help me alter the target for Vector2.MoveTowards?
2d game?
why not raycasting?
Again idk what MoveTowards has to do with this here. You aren't restricted to using this alone and it affects nothing about the actual problem
I'm using raycasts now to detect if another unit is in front, then move the target a bit to the left, but it's very hard to figure out where to move the target
Hey, I added two more lines to the manifest.json file
"com.unityfx.outline": "0.8.5", "com.unityfx.outline.urp": "0.5.0",
And I got this error:
What did I do wrong?
You've presumably got 1 too many commas in your file.
The last item in an array shouldn't have a comma.
looks like a space in front of the 1st line?
wdym you don't see how MoveTowards has nothing to do with it? It's how my units are moving???
I'm not suddenly going to use another method to move them? I'm using MoveTowards for a reason.
MoveTowards has a start & end location.
My question is how do I properly figure out how to set the end location so it goes right next to any other units in the current path
Thank you.
Currently I'm using raycasts with a loop that moves the end location left a bit each time, but that's obviously bad
How do I get a list of vertices of a mesh that touch another (specified) mesh
why not find the position of the raycasted enemy, go to that position with some offset?
idk if thats what youre doing already
it's not moving towards an enemy, it's moving towards a fixed point on my map
but other units often cross paths and I don't want them all stacking on top of each other
but the units would, after adjusting their path, still have to move to the initial location
my unit are spawned in a building, then they move towards a resource on the map, they harvest the resource and then run back to their spawn building to deposit
a building can have several units, so right now they're all stacked on top of each other, I just want to make it look a bit better
and have it work with other buildings & units too
why do you think this isn't pathfinding
you can call it whatever you want, but I have set checkpoints on my map and I'm using Vector2.MoveTowards to move between the checkpoints
the vector2 movetowards part here doesn't matter for your question
well you can use A* algorithm
and add each enemy as an "obstacle"
A* is terrible for stuff that constantly moves around
I've had a good experience with Unity's navmesh agent avoidance stuff in a 3d context
me too
its solid
I'm working with Quantum, it doesn't support any of that stuff ...
Quantum?
it's a multiplayer framework for unity
it doesnt support A*?
what doesn't it support
A* doesn't solve my issue ... I have 100s of units moving around, they know where to move so I don't need A*
I need local avoidance to avoid other units crossing a units path
Because it doesn't matter if they use MoveTowards. Maybe reread points i said above. This is just a method to manipulate a vector. The function Vector2.MoveToward is NOT moving the transform.
Anyways the main answer to this is what is still what I said initially. #๐ปโcode-beginner message
You either fix the pathfinding or modify your movement vector based on the normal of what your physics casts hit
thats what pathfinding is for
but you never told me how to modify my movement vector based on the normal of my physics cast hit ...
which is exactly my original question
i know unity navmesh has a radius property
creates this bubble around the object
quantum 3 doesn't support moving objects with navmesh
and you set the radius so other objects move a certain amount around them
not saying to use navmesh
im saying you can do something similar
you don't need to move an object with navmesh to sample it
How can I get a list of vertices of a mesh that touch another (specified) mesh?
You modify it literally however you want. Like rotate your movement vector towards this normal using the built in vector functions if you want.
I have no idea what any of that means ๐ฆ
๐คทโโ๏ธ then maybe multiplayer is a massive overscope. You can also very easily Google stuff youre unsure of like what the normal is or how to rotate a vector.
maybe trying to help ppl in a beginner channel is massive overscope for you
Great, will take note and block you so you dont need to suffer with my help then. If you cant google to try understanding a term, and wont specify what you struggle with more than "i dont understand anything" then I suspect others wont have much patience either.
Posting a problem in a beginner channel doesn't mean it's a beginner problem
I'm confused how it's Bawsi's problem when you don't know the terms
I wanted to say that I would personally Google these terms as is done with plenty of other things, but this was already pointed out
how do i make an object constantly rotate in the z axis in unity
i want an object to constantly spin
nvm i figured it out
Is it just me or why does this seem to happen constantly now in this channel? Beginner getting frustrated and aggressive at help given.
it's not really a new phenomenon
First of all, don't snap at people trying to help you.
Second, using pathfinding like A* or even more rudimentary one will certainly make collision avoidance much simpler.
But if you are using a naive approach and just want an object take evasive actions you were advised already, raycast the obstacle, and if it has a meaningful shape that can help to figure out which way to star avoidance, start turning that direction. If you are dead set to using MoveTowards method, you'll have to give it an arbitrary point to move towards for several frames to clear the target.
I had that kind of naive collision avoidance in one of my previous school projects, and honestly while it was easy to initially implement, it was horrible to expand on and had bugs all the time (objects getting stuck, overlapping with each other etc.)
Now I would bite the bullet and implement a proper pathfinding algorithm right away xd
Yes, it will get very messy when more objects are introduced.
To manage traffic you need to act on some amount of data, can obstacles clear eventually, how long would be to go around and is it worth it, etc.
I did try to bring that up from the start. #๐ปโcode-beginner message
It did seem like they were asking about going around another AI but I had doubts since the movement seemed purely based on going towards an end point
It definitely has been happening for awhile. Anything that isnt a direct solution to a problem leads to more frustration. Maybe relating to the same mindset a lot have with "its just this ONE problem then I'm done!". Beginners also seem to take realistic advice as a personal attack a lot of time. Being told a feature isnt realistic (usually multiplayer) does seem to get a lot of hate back
Hey, what negative differences have using an Int and an Enum State for States apart of readability. Cuz now realizing i have found some good uses for Int Method but im not sure if is a good idea
enums are just integers with names
the main benefits of having an enum are the type name and each member's name
enum members show up as a dropdown by name in inspector fields as well
The readability is pretty much the big purpose. When you want to reference a value, you dont need to know what int value is associated with a certain state
you can cast an enum to int
There isnt really a reason to use ints as states imo because you're not going to be doing any math on them anyways. Any negative effects (if we're talking performance/memory) would be almost 0 in relation to the whole rest of the game
Oh. How?
There is very very very very very basic support for combining multiple enum values as flags, but it's really horrible in Unity as it's behind on its .NET version and not optimized in the slightest. Right now you should really just use enums for readability, but you are right that it's questionable if you should even use them.
Also note that enums don't define a clamp of numbers. If your enum goes to 5 you can still define 6 and it will be valid. There is absolutely no security here
You can't because that information is not provided by any existing API
Technically you could make one, but it's very unlikely to be worth the difficulty and performance cost
There's a reason why mesh colliders are avoided
wdym, it's just bitwise operations
HasFlag
I mean cuz this also means i can make a flexible function for detect states
I mean.
If i need an animation event or external script to change this script states, if i used INT i could just change it. But i dont know what to do with this
Or just various operations in general involving enums. Modern .NET has massively improved its performance, it's really bad in Unity
how is a lack of that "really horrible"?
it's just a single bitwise operation you can very easily write yourself
That's my point...........
you made it out like enums can't be used at all lmao
I have a sneaking suspicion an enum would never cause a performance issue in relation to literally anything unity related.
This feels like a bit of an exaggeration
"very very very very very basic support", "it's really horrible"
when it's just a & with a name that's missing lmao
It is if you excessively use it like many other things. It won't matter if you just use it once in a while
You are misunderstanding my message
or you only read half of it
And also a function in the Enemy base that puts a delay (wait until timer =< 0) and then changes state. Is hard to do so if the base doesnt havd the state.
But each enemy has it own stayes
please, do tell me what i'm missing
It's totally fine if you just avoid the bad APIs that box, which is very easy to do with some basic knowledge
Enums and their functionality have bad performance in Unity, because it's not optimized. That's the whole point I am making
HasFlag and such
and HasFlag is more optimized?
Point is that you should just write your own API instead because you don't have all the edge cases being covered
it's a single bitwise operation, it's not gonna matter
HasFlag would be less optimized with the function overhead lol
performance is nowhere near a concern for this
HasFlag doesn't box in modern .NET, that's the only enum API I'm aware of that sucks in Unity
But guys. What i should do?
An external script can call a method and pass an enum. This doesn't change compared to use if you used int
You can just use enums, just know about the performance issues that you can encounter from excessive usage of functions like HasFlag and GetValues and such
So i better use Int then?
I do wonder how many thousands of times id need to call it to see a performance issue
Per frame
ahh i see what you were trying to say now
the "very very very very very basic support" led me to think you were saying that the method didn't exist lol
& is always still an option, so idk what the issue is
No it exists, yes
I mean that like LINQ in Unity, there is a point to be made about performance
about GC?
Enums are backed by integral types, they're practically the same except named, so choose what makes the usages clearer as necessary
For this it sounds like it'd be easier if your states were classes. That's usually more common for state machines
Brrrr, thanks okay but is it possible to, with a shader to discard dots that are inside another object?
You mean function?
Or anything like that is impossible without dark magic and demon summoning?
I saw that method but i felt like was slighty complex
Also how u would do the animation thing?
In C# you generally talk about methods
You don't really have functions in C# because a function is always part of a class, making them a method.
Possibly
Can you describe more what you mean by "discard dots" or what the effect should look like ultimately
How they look like?
Everytime i said method i meant how to code
I rarely use animation events so honestly dont know there. There is the option of attaching behaviors to animation states too for custom logic
What a method looks like? Like Start or Awake in a Monobehaviour. Those are methods
Atleast for what i been told is similar to call another script function
Anything with a body of code that gets invoked is a method (or a property)
You can call them functions, everybody will understand what you mean with that
It is, but its more modular. Not every state needs to be hardcoded in one class. You can have an abstract state and other classes derive from this, implementing whatever they want.
But C# doesn't really have functions, because functions are not part of a class instance like what we have in C#.
Oh
Like C, that language has functions I believe
Because you don't put them in a class
The term is very broad, you can just call them the same. I only mention this because you thought they were different here, but in C# they are the same pretty much
But the true name would be methods
IMO they suck. They are super annoying to debug and somehow the whole system feels outdated.
So basically I have a fluid in a glass, its a slightly modified cylinder, and I already discard all dots (cut off alpha clipping) on every dot that is under a plane. I give the plane coords every frame using a script. It kinda works, but the side that gets "cut off" is invisible, so I want to make the plane visible in place of the missing side
isn't that a free function specifically, methods are also functions, no?
There are numerous liquid in glass implementations that deal with this challenge among other related ones using shaders and renderer features
I'd look for them as examples
It's possible to do boolean intersections in code, but rarely worth the trouble especially every frame
It's kind of a hard topic because people find methods that do not modify any state to be a function. Like an Add method, a pure function. From what I learned you just don't have functions, period.
If you Google it now you will also have half of them saying they don't exist in C#, and half saying they do exist in one way or another
that sounds like the distinction between functions and procudures rather than functions and methods
Thank you very much
The effect was really popular a few years ago (mostly thanks to HL:Alyx's bottles) so there probably are assets and implementations that are ready to use as is, not just as reference
Its my first project so I wanna learn to do stuff, but still thx ill look into it
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(BoxCollider))]
public class Projectile : MonoBehaviour, IDamageDealer
{
public float damage { get; private set; }
public SO_ProjectileConfig config;
public void DealDamage(float damage, Idamageable target)
{
target.TakeDamage(damage);
}
private void Start()
{
damage = config.projectileDamage;
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.TryGetComponent<Idamageable>(out Idamageable newTarget))
{
DealDamage(damage, newTarget);
Debug.Log("damage dealt!");
}
}
}
I put this together to create lots of different types of projectiles. It works but I feel it could be a bit more modular still. I have to "manually" create the prefabs with this script attached.
I wonder if there is a good way to spawn the projectiles at runtime with different prefabs, but still using this same script. I hope this makes sense lol.
I thought maybe just change the mesh of the object, but that messes up the materials also.
so does anyone know why this is happening
you set your camera's clear mode to None
set the clear mode to Background and fill it with a solid color
okk lemme check
should i change the opacity of color?
still happening
@spice mist go to #๐ปโunity-talk and show the camera inspector
Oh wait, how about spawning whatever prefab and then using AddComponent() to attach my script to it?
So, you want to add the Projectile script during runtime to the prefab? AddComponent is pretty slow/intensive . . .
You're issue is creating the individual prefabs with the script from the editor?
I'm making this needlessly complicated tbh
What you have is fine. The only thing the script needs assigned is the SO . . .
I'm not sure if that's even needed
I could probably just set the damage value etc. directly
You can create a list of SO_ProjectileConfig attached to a separate SO class. When the projectile prefab is spawned, randomly select a SO_ProjectileConfig from that list to assign a different one . . .
It's similar to what I do (have done before) . . .
I usually have 1 profile prefab in this context and then the scriptableobject is in charge of spawning it and giving it the data that might make it different etc.
That is also another option. The SO can have the actual prefab that is spawned as a field. When you select the random projectile to spawn (based on the SO_ProjectileConfig), access the field to instantiate that prefab . . .
And have the projectile script attached to said prefab right?
Yep . . .
You need an Init or custom method on the Projectile script with a SO_ProjectileConfig param that assigns it to the field on the Projectile. This happens during the instantiation . . .
This isn't the best but for a bunch of prototypes i've done something like
public abstract class ContentBehaviour : MonoBehaviour
{
public abstract ScriptableContent Content { get; }
public abstract void Initialize(ScriptableContent content);
}
public abstract class ContentBehaviour<T> : ContentBehaviour where T : ScriptableContent
{
public T ContentData { get; private set; }
public override ScriptableContent Content => ContentData;
public override void Initialize(ScriptableContent newData)
{
ContentData = newData as T;
}
}
public abstract class ScriptableContent : ScriptableObject
{
public abstract ContentBehaviour PrefabObject { get; }
}
public abstract class ScriptableContent<T> : ScriptableContent where T : ContentBehaviour
{
[field: SerializeField] public T Prefab { get; private set; }
public override ContentBehaviour PrefabObject => Prefab;
public T SpawnContent()
{
Prefab.gameObject.SetActive(false);
T newInstance = GameObject.Instantiate(Prefab);
Prefab.gameObject.SetActive(true);
newInstance.Initialize(this);
newInstance.gameObject.SetActive(true);
return (newInstance);
}
}
This puts the scriptableobject in complete control of spawning new content and the function it uses to do so injects into the newly spawned prefab asap
(i turn the prefab asset off and on between instansiating it in order to delay the awake call until after the so is in the instance)
I did some googling and apparently using AddComponent() vs already having the components attached is a pretty small difference
Sounds good
Anyone have tips on how to get started on coding or any resources I can use to help guide me on my journey.