#💻┃code-beginner
1 messages · Page 663 of 1
I haven't broached Saving/Loading in Unity yet, but I've yet to hear the word "Serialize" used as a verb outside of "[SerializeField]"
Probably an area I need to research specifically before getting too far into development. I just want to make sure I'm not setting myself up for failure.
serialization is the process of turning your data into a format that can be written to disk. that's what the SerializeField attribute does, it tells unity to write the value of the field to the yaml file associated with the gameobject
Ahh, I thought SerializeField only made that field accessible in the editor.
well he's just asking
it being writable to the yaml file is what facilitates editing it in the inspector
Ok. That makes sense. Thanks so much for your help!
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Internal.InputUnsafeUtility.GetAxis (System.String axisName) (at <8464a637132d4cf7b07958f4016932b9>:0)
UnityEngine.Input.GetAxis (System.String axisName) (at <8464a637132d4cf7b07958f4016932b9>:0)
EasyPeasyFirstPersonController.FirstPersonController.Update () (at Assets/EasyPeasyFirstPersonController/Scripts/FirstPersonController.cs:94)
help me plz broders
It's the first line of this, you're trying to use the old input system when you only have the new one enabled check your project settings
I fixed it, I just had to set Input Handling to Input Manager (OLD) because I had it set to NEW.
What are possible reasons why VS fails to recognize a bunch/all unity concepts and is redlining them?
I tried closing and relaunching VS but it still redlines
do errors show up in unity Console
They don't
oh so def VS issue.. have you tried regenerating project files?
Unity is able to compile, its only VS
I haven't, like deleting the Library folder or something else?
Preferences -> External Tools -> Regen Project Files
if fails then yeah I would try Library deletion and regen that too
Unity > Edit > Preferences
Oooh not in visual studio, gotcha. Yes that fixed it, thanks!
if i have a array of users which all have value of ID, how can i get the id's and put them in a list?
List<long> BlockedUsersIDs = new();
foreach(UserProfile value in BlockedUsersArray.value)
{
BlockedUsersIDs.Add(value.userId);
}
Is this the best way?
That's as simple as it gets . . .
okay nice
Isn't there a ToList() method?
wouldnt that allocate memory more than just iterating?
and i cant do ToList
im getting values from the array itself
Okay
you should at least give a start capacity to the list so it doesn't resize while adding elements.
no idea what ur saying 😭
True, I would set the capacity when creating the list . . .
When you create the list, there is a method overloading to assign the capacity . . .
do List<long> BlockedUsersIDs = new(BlockedUsersArray.Length);
then the list internal capacity is the correct size to begin
otherwise it may need to "expand" and it will be copied elsewhere in memory and be a waste
cant do that, BlockedUsersArray is local
and it changes after load
Ah well your example doesnt tell me that
dw about it then, you can give it a start capacity you think is smart
That way, the list will not create a new internal array and copy the current array to the newly enlarged list every time you exceed the capacity . . .
ig i can just do that right?
List<long> BlockedUsersIDs = new();
async Task GetBlockedUsers()
{
ResultAnd<UserProfile[]> BlockedUsersArray = await ModIOUnityAsync.GetMutedUsers();
if(BlockedUsersArray.result.Succeeded())
{
BlockedUsersIDs.Capacity = BlockedUsersArray.value.Length;
foreach(UserProfile value in BlockedUsersArray.value)
{
BlockedUsersIDs.Add(value.userId);
}
}
else
{
Debug.LogError("Cant get blocked users");
}
}
you can actually set capacity later on a list with .Capacity
ah so like this
BlockedUsersIDs.Capacity = BlockedUsersArray.value.Length;
got it
thanks
also try to migrate to UniTask or Awaitable instead of Task
i actually dont even need to make it a task lmao
void is fine
i dont have to wait for it
You can still set the capacity. Just use a reasonable number . . .
So you know, non awaited Tasks that throw exceptions wont get reported reliably in the console. UniTask provides .Forget() and UniTaskVoid to solve this.
Does anyone know/can guide me how to create a roguelike dungeon generation system inspired by Lethal Company?
Idk if that's true, just passing on the message
Can someone help me think through what level of chopping up of Scripts I should be doing for a 3D First-Person Survival game? I have a FirstPersonController script that manages player movement, camera, and converts system input into actions like swinging a sword.
But then there's sprinting, which is based on a simple Stamina system. Have stamina? You can sprint. Out of stamina? You can't sprint. Stamina regenerates after a small delay when the player isn't sprinting. And all of these elements can be affected by in-game features.
maxStamina can be increased in various ways, items can affect the rate of stamina drain, etc. And a lot of these mechanics also apply to Hunger and Thirst. I've seen some tutorials that create a SurvivalManager that manages Hunger, Thirst, and Stamina (but not health) And Stamina feels like one of those features that straddles between a "survival element" and a "player movement" element.
What questions should I be asking myself to help determine whether Stamina should be inside of the SurvivalManager class, or inside of the FirstPersonController class?
as a beginner i made singletons (gamemanagers playermanagers) that way i could for example call a method to add or remove stamina from anything in the game.. w/o needing to find creative ways to get the references i needed to give stamina, or give health, or this or that..
the more i designed the more i'd need to fine tune what i was doing, or maybe discovering something else entirely.. like interfaces, sending events, that kinda stuff
but i let it happen as i needed it to.. or else i never really retained that kinda information..
i knew things exist but not really when and where to use them.. (i still struggle with this, but dont we all lol)
but at first it was all singletons 💪 😈
S part of the SOLID principles
- should it need to know about it?
- should it manipulate it?
- what is it's real job anyway?
Yeah I'm avoiding singletons for player elements because this will be a multiplayer game. But the S-principle actually helps a lot. The SurvivalManager's job is to manage a player character's state of survival - their Hunger, Thirst, Stamina, potentially Health (I think that makes sense), and probably any boons/debuffs on the player that affect these things.
And so the FirstPersonController is responsible specifically for player movement, but not for player "state". I'm gonna refactor the code to reference the SurvivalManager's values for Stamina.
I have a FirstPersonController script that manages player movement, camera, and converts system input into actions like swinging a sword.
I would split that into three different scripts
Movement, camera, actions
Why's that?
Cool, thanks!
a good rule of thumb is to keep things that "dont know about each other" separated.
Youd probably wouldnt ever need the camera to know when your character checks if theyre on the ground. As those two components will never "talk" to each other, and considering how very different they are, its practical to separate them.
A good reason for doing this, is that if your camera code works, and you accidentally break your movement code; the camera system shouldn't be at risk of also being broken
Thanks, that makes a lot of sense.
Though this is where "sprinting" throws me off. Because technically the First Person Controller needs to know IF the player can sprint.
But there will be many other interactions with the player's ability to Sprint - if the player has a debuff that prevents it, if the player is in a realtime cutscene that prevents running, if the player is out of stamina.
well in that case, you could have a public bool in the movement class like isSprinting or canSprint, that way the camera is stil able to read what the state of the player is
Ok, that's what I currently have.
I have both actually. isSprinting tracks whether the player is actively sprinting, and canSprint is almost an "override" that can be toggled on-off to prevent sprinting in certain situations.
id say try splitting it down into the individual components, dont alter any code right away, just move your code to the different components. The problem doesnt sound too hard to solve, and you may find that this kind of refactor could make it easier to spot the issue
Cool, thanks!
yeap, or a public getter private setter property for it
i used a offical unity tutorial and idk why its not working (I swear to god if its my IDE)
also !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
we need a new counter for this input error 😆
wanting to make a katamari-like game, i was gonna just go with a URP project but whats the difference between URP and the built in render pipeline?
planning on doing everything myself, however long that takes
in godot, i would have autoloads/singletons with signals, i could have scripts connect their own functions to those signals, then have other scripts call those signals to trigger them remotely
is there any way i can do something similar with unity events?
it seems like i'm almost there, but i cant figure out how to properly access a public class
make a reference to that class then access your property/field that way
so a reference is always necessary?
yea to access the instance
that means i'd have to add a serialize field and assign game manager to every single script then huh
or use a Singleton pattern for game Manager so you can at least access the field/property/methods through that
that would work mhm, but how do singletons work in unity? from what i saw they're just public classes that delete any other instances of themselves you accidently create
i want to add a walljump mechanic, i have a p good idea on how to make it work, when the player isnt grounded and presses the jump key, a raycast is cast infront of the player, and if it hits a wall, it takes the face normal
the specific part i dont know how to do is taking the specific face normal that the raycast hit
singletons are a concept not necessarily related to unity
yeah, in my case i'm only interested in the global accessibility trait of them
the basic gist is making an Instance of that class Static so it can be easily accessed through that
ahh so it's a public static class and not just a public class
yay seems to be working now
now next step, how can i pass on a variable through a unity event?
ie add a function with an argument as a listener for a unity event
then have another script call that unity event, and attach a variable
is that what UnityEvent<> is for?
yes iirc only supports specific types? been a while... to me UnityEvent is mainly useful if you plan on adding subscribers through inspector, otherwise I would suggest go with Action or other Delegate
yeah it seems like the purpose of unity events is for inspector assignment
i skimmed thru a lil bit of info about delegates, sounds like unityevents are delegates but with inspector integration added on
for prototyping and testing, i want to slap artificial delays into my script (as placeholder until animations are ready)
is this a good way to do it?
just have every functiont hat will have delays be an async, then add in these awaits?
should work but async void does have its own problem
in Unity generally recommended to use Awaitable or coroutines .
VS Code version: 1.100.2
C# Dev Kit version: 1.19.63
C# version: 2.76.27
.NET SDK version: 8.0.405
C# Dev Kit logs: https://basedbin.fly.dev/p/e9lJem.txt (its not a link to download its pastebin)
help my C# dev kit is not recognizing my .editorconfig but when I use dotnet format it does recognize it
content of .editorconfig, I only defined a few rules to check if its working:```ini
root = true
[*.cs]
indent_size = 4
indent_style = space
trim_trailing_whitespace = true
insert_final_newline = true
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
mkay i'll try it with coroutines first
hm, i'm getting a null reference exception when referencing this static class
does it need to be declared in this funky way?
show the complete error
or maybe it is working partially, like it doesn't insert a newline in end, it doesn't sort system directives first but it does import groups if I set dotnet_separate_import_directive_groups to true but only when imports are sorted and not mixed up
are you invoking the event ?
well the error happens before i can get to the part of the logic that invokes them
so no
why is it static UnityEvent anyway ?
yes because you made game manager a static class instead of a component so most likely the UnityEvent isn't initialized and you're trying to access a method on it
ah i see, so would swapping to delegates solve it?
so now the syntax is like Gamemanager.tileDrop += functionName
then just call Gamemanager.tileDrop
don't forget to add null check on event before Invoke in case no listeners
Gamemanager.tileDrop?.Invoke(myNumb)
whats error say
did you actually save changes when you switched tileDrop to Action ?
What would be the proper channel to ask for the configuration of a line renderer? vfx and particles??
also for ambiguous reference on Random you can assign UnityEngine namespace to it
using Random = UnityEngine.Random
hmm, this ide is a bit odd and seems to autosave whenever it can, but it works properly for this syntax so i think it's properly saved
weird..are you using rider btw ?
mhm
can you hover over tileDrop and show what it says
it's not just an ide bug it seems
so its saying only GameManager itself can invoke it?
ohhh you're trying to Invoke from a different class?
mhm
can event actions not do that?
is there a form of delegate that can? or do i just need to have a unique public function for each event action
event keywords prevents that, I'd probably make a static function that invokes it then
oef that's gonna be alot of functions
public static void InvokeTileDrop(int number) { tileDrop?.Invoke(number); }
GameManager.InvokeTileDrop(numb)
pretty easy lol
yeah i guess in practice it just makes it 2 lin es of code instead of 1
mm, so using coroutines doesnt delay the function int he way i hoped it would huh
it will simply call insert delay and print wait every frame
you could technically just remove event and it works fine invoking from other class
oh okay
but there are also other implications there, mainly the whole encapsulation thing and all
so for coroutines to work, it'd have to have a separate delay function that calls another function?
no calling it does not delay the synchronous function
also you're missing StartCoroutine()
so anything delayed goes in the IEnumerator itself under the yeild
btw unity has some functions already as IEnumerator such as start
IEnumerator Start(){
//yield wait
//do something after delay, such as calling another function
mhm, which means i have to have a separate ienumerator with logic inside of it for every delay i want to have, which is inconvenient
is there a more convenient way to insert artificial delays? one that works midway through a function?
wait should i just have my main function be an ienumerator and use yield return new WaitForSeconds()
just make the function IEnumerator if it needs delays between calling functions / running codeblock.
that would be the same as doing async void/Task MyFunc anyway
Awaitable is also an option
hmm, i'm trying to check if it's working by having it print, but instead the console is getting spammed with this
is it something i need to worry about or is it just unity jank?
oh my god im learning of so much very quickly, dont know if too quickly, started with looking up what a string is, now im learning what access modifiers are
those are the basics yes its fine, quickly doesnt mean bad per se if the information sticks why not
can be bad if you're not following structured path though
access modifiers are the very basics so yes its important stuff
ah im at least glad im learning the stuff i should be early then
for now its mostly just escaping my mind but im writing stuff i learn into a powerpoint doc
imo the microsoft website is one of the best places to learn c# basics
reading can be hard sometimes ngl, so what im basically just doing is para phrasing everything i learn into powerpoint
not really sure if i got these right so apologies if things arent technically correct
time.deltatime confused me, still dont fully get it
deltaTime is the interval between each frame rendering
so rather than moving an object based on framerate you're moving it based on seconds
yeah i assume it's editor bug, this project is waay too small to be having ?memory leaks?
ohhh, see i thought time.time was every frame and time.deltatime was every second
could be or you may not be cleaning the listeners , make sure you unsubscribe events, this is very important for static ones
Hello there! Sorry to interject but I have an issue I was hoping someone experienced could help me with. I am following a YouTube tutorial on how to create a Platformer, and I have been doing pretty good! But I just hit a spot where it gave me this error:
"UnassignedReferenceException: The variable animator of PlayerMovement has not been assigned."
And well, I don't know if it is something I did wrong/missed in the tutorial, or if it is because the tutorial video is in an old version of unity, so maybe there is an extra component I am missing. Any insight would be greatly appreciated! Thanks for reading.
so did you assign the Animator component in the field
You'll have to be a little more specific, I am extremely new lol.
make sure you drag and dropped in the field the component
https://unity.huh.how/references/serializing-component-references
why isnt this looping? (only prints once)
Coroutines cannot be called like this
you need StartCoroutine
You're only telling it to wait 1 second, print a message, and then start. There's no loop
also if you need to repeat itself you should use a while(true) loop
In fact, recursively executing that way is a bad idea in a coroutine.
yeah best use a regular loop instead of recursive calls
more of a chance shit going bad
I assume it's this at the top that I have missed?
A better option is to make a separate coroutine that does what you want, and that has a loop with a 1 second wait within. And then startcoroutine that coroutine from your Start() method
well i'm just using a loop to test if the coroutine is working how i want it to
this isn't the component instance
this is just a script file
Instance its when you put the script on a gameobject
it becomes a component
You need to look at the gameobject which has the script attached to it. If you don't have one, then you missed the step of creating one and adding the script component to it
well that would require another function, what i'm hoping to do is be able to slap a line of code to tell the logic to pause on that line for a specified amount of time
i'm doing this for prototyping purposes, so ideally it's fast and easy to incorporate
Ahhh, so up here?
yup. See its set to None
hence the error
it doesnt know Which exact Animator you want to do stuff on
Ahhh I see. I think I get it now, thank you.
I understand, but doing this you're going to stack overflow in no time, so best not to make a habit of it for prototyping.
now Im not surpised you had these lol
well it's not gonna loop, i'm just trying to figure out how to make it wait
the wait is there and calling another method is fine, but trying to call itself is a recursive function, without an exit condition you will stackoverflow
mhm i know it's bad practice
but uh how do i make it actually wait for the 1 second
its used in very specific times
it literally is already
StartCoroutine("Start")
why in the hell would you ever use string for calling function
is it just terminating the loop coz the engine knows that's bad practice?
Yes I'm well aware it has a string signature its still a shit way to call function , they should've never put that..
then stop recommending unity docs to people
with common sense one knows to use a Type safe method call
oh weird, yeah it does seem to work, i guess unity was just exploding coz it hates loop
again it was not a loop lol
recursion?
recursive functions are not exactly loops
well maybe its a technicality in naming, but loops generally I would associate iterating
recursion consume lot more memory cause of the stack
IEnumerator FancyLoop()
{
while(true)
{
yield return new WaitForSeconds(1);
print("print after 1 second forever");
}
}
while(true)
{
yield return new WaitForSeconds(1);
Debug.Log("I LOOPED");
}
That's a loop.
Damn, beat me to it 🙂
nice
Ideally you'd create and cache the WaitForSecons outside of the loop and just reuse it, rather than make a new one every loop, but that's for another lesson 😄
true
or do what i do and skip creating a new object at all
while(true)
{
float t = 0;
while(t < 1) // ideally you don't make 1 a "magic number"
{
t+= Time.deltaTime;
yield return null;
}
print("print after 1 second forever");
}```
I have a checkerboard marked in x and y coordinates, how can i access the first row or the first column of the checkerboard.
I also do the timer loop, but mainly because I often want to be able to exit the loop before the timer runs out if other conditions are met.
is the checkerboard just a big image tho?
or are they separate cells
They are seperate cells
Yeah.
var cell = myGrid[x,y]
Shouldn't I be matching the sorting layers and rendering layer mask to tell which masks affects each sprite?
I'm unfamiliar with how sprite masks work, I'm sure the documentation says
This is a programming channel
Where do I ask that, on 2D tools?
Sure
why is this update funcitno not running?
we don't know just from this snippet lol. Also where the most important part there missing.. a Log lol
what does yellow underline mean on Rider anyway? I'm guessing it doesn't like camelCase methods
mhm
just wanted to check that i'm not crazy and it's spelled right
ah nevermind
hm, how do i tell it not to expect a return value?
You have to use StartCoroutine to start a coroutine
I have no idea but again you don't call Coroutines like this
ah
also calling StartCoroutine every frame will create a new coroutine each frame btw
probably not something you want
hm and they dont automatically terminate themselves?
nope
oh annoying, i was hoping to just use them like regular functions so i can insert arbitrary delay
well they do after its done but Starting one wont end another , thats what I meant lol
oh well that's fine then
Coroutines will automatically become garbage in memory if they don't loop, it's unwise to do them every frame due to the memory overhead and eventual garbage that needs to be collected
even after they finish?
Its allocating space in memory for them, every single one
oh well i guess it's just an if() clause, so i can just have that in update instead of in the coroutine
if GC has to collect a lot within a frame it could be issue in performance
btw Coroutines can be stored in variables
so if coroutineVar == null, start coroutine, else pass?
Coroutine myRoutine;
void Method(){
if(myRoutine == null)
myRoutine = StartCoroutine (TheRoutine());```
```cs
IEnumerator TheRoutine(){
//do stuff
myRoutine = null```
Why do you need a coroutine in this case? What operation is it doing?
iirc they want a function that can have delays between stuff
nameOfThatTextComponent.enabled = false;
that one is SetActive
[SerializeField] GameObject theGameObject
theGameObject.SetActive(bool)
Oh wait, yes, that's not a Text component
because its a Function on GameObject
so diceLabel.gameObject.SetActive
btw components have .enabled when they have any of these method implemented
random question, so the top vector3 line works but the 2nd one doesnt, why is that? it seems like the same code but certain parts are not highlighting despite it being the same
input is not the same as Input btw
multiple reason, 1 input is already an assigned local property and input is bad capitalized
yep just noticed
🤦
cant believe i didnt realise the i in input was different, that was making everything not work
my bad
thanks
yes c# like many languages is case sensitive
yep lol, just didnt notice that i was not capatilised :/
i used python in high school but its been years since that im basically relearning
c# will set u straight 😄
it sure will 😅
are any languages with >10 users case insensitive
SQL is pretty big lol
ah true, though that isn't a programming language
i guess asm lol
though it also isn't one 🙃
BASIC is pretty badass
older ones too ig like Cobol or Fortran
ah im not familiar with those at all, cool to know
https://pastebin.com/AnDwuwy3
Need help with this, even with multiple Time.deltaTimes, its still framerate dependant ( moving around is fine, its just jumping and wall jumping thats fucked )
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im going insane
Update isn't the easiest to debug, but I suggest start debugging by the final velocity value and then going down the list
Your OnJump code is definitely wrong. You absolutely don't want to multiply the velocity by Time.deltaTime there
That's guaranteeing you'll have different jump heights for different framerates
riiiggght, makes sense since its not every frame
A lesser but also real issue here is that you cannot use Update for consistent physics
There's a really good reason the physics engine uses a fixed time step
You can't get a consistent simulation without one.
deltaTime is not sufficient to correct for second order effects like acceleration
It can only accurately fix first order changes over time like a constant velocity
i think it does, but yeag ima move the velocity related stuff to FixedUpdate
I mean it does make sense that it can work in fixedupdate, but the visuals would need to be interpolated
i dont have to use the .Move() function in fixed update if i only do the velocity decay and gravity there
got something super early, mostly just followed a tutorial but was also trying to learn what everything meant at the same time
only thing im not happy about is that when rolling over an object, the ball struggles to roll, so that will be the first thing i figure out myself without a tutorial on youtube
this is the code ive done so far
You could just remove the collision from the cubes* and just have them stick to it, or if it's supposed to affect the geometry collider yeah that's not the easiest
potentially increase just size of the sphere collider radius that matches the prop
yeah its an odd one, cause in katamari the objects you roll over does effect how the katamari moves, but it doesnt make it impossible to roll over
ooh that could work
ill figure that one out haha
btw no need for Time.fixedDelta time in AddForce its already moving on fixed time
as the sphere would get bigger i would need the collider to basically inscrease in size too
oh yea, the tutorial i was using basically used that lol
they probably wrote it without understanding how it fully works
maybe maybe
at least glad i got a foundation i guess. as long as i can build off it then im happy
i have found a solution, just made the collision boxes smaller on the cubes. instead of a size of 1, ive made the collision boxes 0.2
unsure yet if i would get away with that for any assets i make but its at least viable for now
fixed it by moving all "physics" related things FixedUpdate()
im not using a physics based character controller bc i feel like itll introduce too many variables i dont want to deal with, and all i really need is decaying speeds ( gravity and "knockback" )
( "knockback" only being a thing for walljumping )
deltaTime has always been frame dependent
It calculates the time between two frames
It's always a good move to put movement in fixedupdate
even the normal wasd movement? it seems to be working fine
CC should be used in Update
I mean physics events
Depends on how you treat your movement
I personally put all my movement code in FixedUpdate because it can guarantee consistent movement
You can choose to not to, it’s perfectly fine, just depends on how you want to handle it
But my suggestion is to always put physics in fixedupdate
Great suggestion, but as they said, they're not using physics-based movement
yeah but i still need something like gravity
i need the tiniest bit of physics
"physics" in this context means the physics engine specifically
They're talking about the using the physics engine . . .
not enough to justify an entire rigidbody based movement system, but enough to need to put certain things in fixedupdate
If you're not moving using the physics engine, you can apply your own gravity in Update. Obviously, a custom solution . . .
You can implement gravity by apply force in air by applying gravity*Time.deltaTime on your velocity
I think fixed delta time and delta time makes no difference in terms on how it feels to play
Unless it’s like extremely low frames
I mean I don't exactly know the differences of how acceleration behaves between doing it in update or fixed, but a large reason that fixed is useful is that you're not doing expensive queries dependent on your frame rate
It's more performant to predict or take some sample and interpolate that information than grabbing it 200-300 times a second
That depends on what that process is, I mean you can just use a coroutine for async for functions like that if you want to run in parallel
I assume CC isn't doing these expensive operations on a frame basis, but rather accumulating those values then doing it at a step further in time which is why you do populate these buffers in update
i was trying to write code to lock my cursor to the game screen and make it invisible but it doesnt work. do i need to make a new script for this code or am i able to put it in my ballcontroller script?
this is the code btw
And where do you call that function?
if im being honest im unsure, still learning and was looking up a youtube video
just started today
You need to call the function with one of Unity's built-in callback functions (messages)
Awake, Start, in Update somewhere given some condition etc
ohhh alright 2 secs
For example cs private void Start => cursor();
Case sensitive
oh yea, ive got start somewhere else in my script
would i need to put the code ive got in that screenshot im assuming underneath the other start ive got
just noticed yea
this is the other start
Those lines of code won't automatically run. You'll need to either insert those lines of code into some function that is called by Unity or call your non-Unity function manually
ah alright, so ive at least gotten the case sensitivity gone, moved the code
there we go, the code is working now
we might need a new text channel...
call it code-babies...
and put just me in it..
anyways, ill send my progress so far
probably gonna take a break and soak in what ive maybe learned today
actually somewhat proud tho, despite me using youtube tutorials
oh right, ill post there, thanks
i have made my post 🫡
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types
a float and double are different data types, both exist in c#
It's exactly the same in Java
really?
can anyone help with this? whenever i use a buffer jump it is always a full jump and i cant control it with variable jump height
i used brackeys movement script
the 1st image is in update and second is in a function
The last line sets jumpBufferCounter to 0 so it'll only run once regardless of how big the counter value is
how do i make buffered jumps vary with variable jump height?
im using this script for shooting with a bullet. the bullet is going in a completely different direction. i even check with a debug drawray, but the bullet is going in a completely different direction from the debug ray. what am i doing wrong?
the script is in the gun object btw
good job man
i assume when you pass by the cubes they turn into children of the sphere?
sounds like a fun idea
you should point the rotation of the bullet to also the rotation of the gun
in this case youre just instantiating with whatever rotation the bullet has
the rotation is 0,0,0. why would the rotation matter when im applying the force in the direction based on my gun
the rotation of the bullet is zero.. im adding force to the bullet based on the direction of my gun right, so how does the rotation of bullet matter
the forward point of the bullet needs to be the same of the gun
otherwise the bullet just goes towards another direction
you can make a bulletSpawn in front of the gun for clarity
then when instantiating the bullet you set its rotation to the same of bulletSpawn
GameObject bullet = Instantiate(playerController.drinkEquipped.bulletEffect, bulletSpawn.transform.position, bulletSpawn.transform.rotation);
something like this
ohh alright.. so i need to set the rotation to that of the gun. i'l ltry it out and lyk if it works.. thanks!!!
i wouldnt put the rotation to the gun itself, since you might have more than one gun with different shapes
but to a gameObject that is in front of the muzzle of the gun
yep, thats it, next thing im gonna probably work on is figuring out how to make the sphere get bigger as i join with more objects, gonna be a challenge for sure since im new, then ill probably code in something where if you bump into a wall or something bigger than you, the biggest item you picked up falls off you
once ive got these down ill start with figuring out unique stuff i can make for the game
you can scale the sphere up whenever you pick an object
make it subtle like 0.1 or something
or something i seen online, could add on the size of whatevers getting picked up to the size of the sphere maybe?
yea or that depends on what you want
for the biggest object falling i'd store their scale in a script
then when picking it up you send that data to a list in a general script attached to the sphere
um problema de cada vez
wait
for now just try to make the sphere bigger
stupid question, are you portuguese?
PORTUGAL CARALHO
Hi everyone, i was wondering if anyone could help me try to understanding how to use composition a bit more modular and in conjunction with each other.
Because currently while i get the basic idea, its to make it easy to reuse stuff but actually using it in an effective and different manner is where im getting a bit wobblily.
Like for example i made a health component, since im gonna have wildlife and humans in my project.
Put it on these different entities and they have Health stuff - events or otherwise, no need to rewrite the code in other scripts.
So if i want a human to grunt in pain - i would think we make a Human script, that has a Method called MakeGruntNoise() and it subscribes to the TakeDMG() from the Health Comp.
Like is that the general idea or have i crossed some wires - other ways to do it?
it didnt work :(. its going in a completely different direction
show me the bullet instantiate code and the bullet code
there is no bullet code
yet
show me the gun component
im not using a different object as gun (yet), im directly attacking from the enemy
directly attacking from the enemy? ah you mean you just have an empty gameObject with the script attached?
no lol i am using the script i am using to control the enemy to handle the shooting as well
and that script is attached to the enemy?
yes
thats why
transform.position, transform.rotation are grabbing the transform of the enemy
not the gun
yeah.. but its still suppsoed to work
can you show the debug ray code aswell
that's transform.forward and thats the direction im putting force in
Debug.DrawRay(transform.position, transform.forward * 50f, Color.red);
well on transform.position set it to transform.forward then
huh? do you want me to put transform.forward instead of transform.position in the debug ray??
have fun man
yea sounds good
if you have multiple things that can get damaged i'd make an interface tho
it doesnt work bro 😭
the parameter is position how is transform.forward gonna work
hi, i wanna make a question game with drag and drop system and after the player put the answer a check mark to show if it s right or a x if it s wrong but i can t rlly know how to make the script for that can someone help?
no i thought it would work... but it didnt
make a child of the enemy
put it where you want it to shoot from
then instantiate there
ok for some reason it worked
i checked fr now haha
thanks a lot!!!
Keeping my platformer character grounded
hello guys, i'm new with code cause i'm an artist and start to learn shaderlab, anything should i need to notice?
GLSL/HLSL for the most part
CG outdate?
CG can still be used, but it's just a compatibility layer on top of HLSL and considered legacy.
It's used by the legacy render pipeline. URP and HDRP use HLSL.
You can get away with a lot of basic shaders with CG
but if you want to do something lit, you'll need to know Unity's macro lingo
what's that?
https://www.cyanilux.com/resources/
Good resource though, but otherwise #archived-shaders when ya get stuck
Useful Links to Resources/Tutorials/Docs related to Unity or Gamedev
c# for unity, but shaders are a separate thing
i see, thanks
hey im currently running into the problem my charcater is running but as soon as the stamina runs out he keep running unless i let go of shift and press it again then it stops running
you're in a code channel, post the code and other additional info..
public void PlayerSprint()
{
{
if (isRunning && Stamina > 0)
{
Stamina = Mathf.Clamp(Stamina - (StaminaDecreasePerFrame * Time.deltaTime), 0.0f, MaxStamina);
StaminaRegenTimer = 0.0f;
sprintSpeed = 2;
}
else if (Stamina < MaxStamina)
{
if (StaminaRegenTimer >= StaminaTimeToRegen)
Stamina = Mathf.Clamp(Stamina + (StaminaIncreasePerFrame * Time.deltaTime), 0.0f, MaxStamina);
else
StaminaRegenTimer += Time.deltaTime;
}
}
}
this funtion gets called in update
hello guys, can anyone help with triggering point lights?
i have a plinko game, and i want a point light to trigger on to the peg to make it glow
this is one function
incomplete information
help with what exactly?
public void OnSprint(InputAction.CallbackContext context)
{
if (context.performed)
{
isRunning = true;
PlayerSprint();
//sprintSpeed = 2;
}
else
{
isRunning = false;
sprintSpeed = 1;
}
}
I thought you said this got called in update
it is
this isn't update, this is a button callback function
weird way to spell update
private void Update()
{
PlayerLook();
PlayerMove();
PlayerSprint();
//HoldItem();
}
ok so why is it ALSO in the input callback
so i dont really know how to call upon a specific point light and trigger it
light component has a .enabled property you can use, just make a reference to it
or you can set active the gameobject that has the light component
You should probably stop giving tiny windows and having us play 20 questions and just post the full !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.
Anyway this:
if (context.performed)
{
isRunning = true;
PlayerSprint();
//sprintSpeed = 2;
}
else
{
isRunning = false;
sprintSpeed = 1;
}```
Is not good. Did you know there's a `started` phase? You are going to set isRunning = false in `started` as well as `canceled`
you should explicitly check if (context.canceled) to do the = false part
and depending on how you configured your input action - performed might not even happen right away
so i have a question; do i have to make a script for each peg with a different name for each light object? or is there a simpler way to do it
no 1 script that does the same thing can go on multiple pegs. Maybe add a timer so you can shut it off , perhaps a coroutine
no i dont know about the started phase ill have to look into that
you almost never want to do anything that deals with object names in your code. It's a very slow, fragile, inefficient way to do things
yes reference the actual component you want with a serialized field
thanks im still very new to unity so i have questions
do you know about refencing component & assigning ? check this resource has example too
https://unity.huh.how/references/serializing-component-references
you can use coroutine to add a delay to turn the light off after a specific interval https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Coroutine.html
so all together could be something like this for script on the peg, if its 2d game use 2D variant for OnCollision
[SerializeField] private Light myLight;
[SerializeField] private float lightOnTime = 0.15f;
IEnumerator OnCollisionEnter(Collision collision)
{
myLight.enabled = true;
yield return new WaitForSeconds(lightOnTime);
myLight.enabled = false;
}
yeah im trying to figure it out right now
i got it by adding it to the else function in the other function but see it also flued for a different reason so will look into what you told me and hopefully smooth it out more
How do I rotate a Vector2 around the z-axis by an angle? I tried manually using a rotation matrix, but it's going all over the place. I also found Quaternion.AngleAxis, but how do I apply a Quaternion to a Vector?
multiply Quaternion * Vector3 returns the rotated Vector3, then just convert back to Vector2 (which just drops the Z axis)
Simple code example (rotate 50 degrees clockwise around the z axis):
Vector2 rotatedVec = Quaternion.Euler(0, 0, 50) * myVector;```
Yeah, that worked. Thanks^^
I also figured out what my original issue was. Vector2.Angle (and Unity/Transform in general) work on degrees, but Mathf Sine/Cosine want the angle in radians instead, so I was getting nonsense results.
true
Hey everyone, got a question about prefabs. I have three wheels on my UI that represent player hunger, thirst, and stamina. All three wheels should work exactly the same - the StaminaRing_Visual has an Image component with the Image Type "Filled", and its Fill Amount is tied to the class SurvivalManager's StaminaPercent property. Simple enough.
Each of these work the same way, and so I have the sense that they should be three prefab variants of a base prefab of "SurvivalMeter" or "SurvivalWheel". Does that sound right in theory?
yes
makes sense
Variants are nice for things like enemies where you may find yourself with a hefty amount of variations, but otherwise it's not a requirement
or even just a single prefab and a script that sets the sprite in OnEnable
why not just have them as instances of the prefab and override the sprite and perhaps the names
or that yes
A good question about variants is do you find yourself in a situation that you want to modify all variants by changing the main prefab
Got it, because this is effectively a single object, there's not really a reason to make a prefab variant, is the feeling I'm getting. Right?
Just making instances like chris mentioned is probably the idea here
yep - you wouldn't make a prefab for a one-off object
same for prefab variants
I'm trying to understand how this would be possible. That requires a script that sits on the top level of the prefab (here titled "StaminaRing"), with SerializedFields for the Ring visual, Icon visual, and the DisplaySprite, and then OnEnable, changing the Icon Visual's sprite tot he DisplaySprite. Does that sound right?
yes
That's a very typical approach
or in a separate Init function
depending on how you populate these things in the scene
you can think of it in layers
an instantiated prefab would be a gameobject with that prefab as its "parent"
a prefab variant would itself have the prefab as its "parent", but it can also be a gameobject's "parent"
And then from a "best practice" perspective, should I create a SEPARATE script for the Ring_Visual object to determine the FillAmount and draw the ring with that percent value? Or would I keep this logic at the top-level StaminaRing object?
wouldn't be required, but that's a viable approach, sure
i'd just have 3 instances of the prefab and override the image in the inspector
Oh! Way simpler.
then you could have the "management" script that controls said values accept Images for each meter, so that "management" script would be able to set the fillAmount
Good way to think of variants is you've an enemy prefab but you split it down the line into different types which include subtypes, so for instance you got Elves -> Deep Elves, Dark Elves, Orcs -> Green Orcs, Blue Orcs, and you want to apply a component of knockback to only the orc sub set
Got it. Ok.
At first I was going to disagree with the approach, because I feel like the Ring should be responsible for drawing itself, rather than some management script (in this case probably the SurvivalManager script) but when turning this into a prefab, I lose the ability for the ring to know...what it is. Is it a Hunger Ring, a Thirst Ring, a Stamina Ring? And so which variable should it set itself based on.
But maybe I'm not aware of some way to get this to work (without using hard-coded enums/strings/case statements)
in games it can be tempting (and unity encourages it) to conflate 'displaying your game' with 'your game logic' but it's not always a good approach
it's kind of up to you which you feel works best for your workflow
the thing you're discovering though, that it's very helpful in games for them to be able to reason about themselves, is accurate and why a lot of games trend towards being very data driven instead of collections of self contained objects
that's pretty abstract advice, so more concretely I would say that if you are splitting your visuals out like this, you probably do probably want to 'hydrate them' in some top-down way from a manager like was suggested, rather than having them reference the manager and query their data
I'm not sure I 100% follow. I understand the distinction between "Displaying your game" and "Your game logic". The Ring doesn't understand how/why the percentage is set. It just displays the percentage.
But where I'm not understanding is the philosophical difference between "The Ring should go GET the percentage" vs. "The SurvivalManager should PUSH the percentage to the ring"
in what you showed, the manager isn't actually managing
Very true. The Manager is managing the game logic, but it isn't responsible for displaying anything.
I think this comes from a place where, say I brought on a new developer - and that developer goes into the UI and clicks on the Ring and sees "The Ring has a Fill Amount that's being set somewhere"
There's no easy way to figure out WHERE that value is being set how that value is being set.
I would say that mostly it doesn't really matter, except that it is simpler to reason about/manage 'these few top level things which control everything else' compared to 'everything querying anything it wants everywhere'
I don't think that 'my code should make sense to someone with no knowledge or context' is a very useful guideline
that person will only be interacting with your code for very short periods of time and if the thing they have to learn is 'it's set by one of the dozen managers', that seems pretty low-lift to me
what I do is segment things out in a way that feels reasonable to me
Alt + F combined with Find Referenes, etc is plenty enough to find where and how the FillAmount is being set
so I have 'views' which are responsible for querying data and then pushing it down into the components, which are mostly dumb and just display data
the views are contextual and understand the game, the individual components just display what they're told
waitt.. are u the guy yesterday that was asking bout where and how to split ur code up?
I might have been Spawn, yeah.
Which it's been split in a way that now works really nicely.
very gucci 👍
if ur familiar with XML and code Summaries you can also document ur code along the way.. it really helps people thta may be lookin in on ur code
basically adds those tooltips and variable descriptions when u hover them
Is it possible to document something like this though, where the OBJECT has no code whatsoever, but its values are being set by another unrelated object?
and inside intellisense when ur scoping methods
when TestACloserThanB tests that A is closer than B 
u can def summarize the parameters
and values
But in an object with no script at all? In the Inspector?
lmao... first example image i found from stackoverflow 😈
inspector has its own attributes
like [ToolTip("Blabla")]
you can just explain in your readme that it's a convention you follow and follow it
and that ^
these things are only problems if you're inconsistent and...just never do that! 😛
Lol
This is in the effort of consistency. So I'm with you on that. 😉
ya, when is too much too much?
if you can.. type ur code out in a way thats as readible as possible
without any fancy attribs or tags
I think that if your unity scene is mostly stuff that's getting hydrated and you are consistent about where from, that's much simpler to convey than a lot of 'architectures' you'll come across
this is a lot of the philosophy behind ECS
where are components changed from? systems, and it's simple enough to see which systems query which components
So, I feel like there are two trains of thought here:
A. The SurvivalManager should manage (and set) the fill-amount for visual objects on the screen. It manages both the game logic AND is responsible for distributing values to members around the UI and game. I don't know if I fully agree with this method, but it's one method.
B. The UI objects themselves have logic that reference the SurvivalManager and query it for the state of the player character. They set their own values.
I know how to do method A. SurvivalManager keeps the rings as object references, and directly sets their Image.FillAmount value to the percentage values of HungerPercent, ThirstPercent, StaminaPercent.
But (and I might not use it, but I want to understand how it would be done) how could I accomplish method B? Particularly if the rings were part of a prefab.
B. gives me eww vibes
C. The UI uses the observer pattern and subscribes to events on the game data model for when that data changes.
I vote C
me too! 💪
Actually I'm amenable to C for sure. Though this value changes literally every frame anyway.
Really? Stamina changing every frame is ew?
yeah most people will recommend this
For sure.
that's not an issue for C
it shuldnt be doing anything
The value doesn't change, right.
only when its being added to.. or subtracted from
then it -> should get updated
thats part of the pattern they mentioned ^ when it gets changed an event goes out
ui or ui manager sees that event.. and oh.. it changed? well ill update
the only thing with events is you have to deal with decentralized sequencing, which doesn't matter a all for a lot of things but can be very annoying for stuff where it does a lot
So even with this mechanism, I'm not sure I understand how it could be done with a prefab. Can you create (don't kill me) a SerializedField that points to a specific event inside of another class? I know you can use a SerializeField to get a reference to another object. But I'm not familiar with being able to reference events inside of classes that way.
Ahh
A UI Manager.
if your game tends to be made up of specific triggered sequences rather than being more of a simulation, it can be nice to just control the meat of that directly instead of mucking about with events
yea thats how i do it.. as a singleton too (may or may not be the best solution) for me it works
generally you would have your objects 'auto register' with some kind of event bus
my UI manager has refrences to all the UI it needs..
or subscribe, i guess
then i tell the UI manager to change values when possible
You would set up the subscription at the start of runtime
always dozens of ways to do things.. 😄 mines a little lower on the totem pole
prakkus and praetor are way more skilled than i
So SurvivalManager has Properties A, B, C, with Events A, B, C that fire when those property values change. (I'm generalizing terms here for the sake of brevity and understanding)
I have three instances of Prefab "Ring", who needs to subscribe to A, B, or C. How does each object instance specifically subscribe to Event A, B, or C?
it's funny because you're thinking very data-driven which I love and would embrace, but it's not where most people are when they pop in here or in line with most of the common advice you'll receive
often, a 'change' to your gamestate is more than just one piece of data changing (one property, which would fire an event, in your example)
so it doesn't really make sense to have events for 'this piece of data changed' (not actually true, I do this, but I don't use them that much'
more often what you want is to represent your game in terms of what actually happens
if you go do webdev they'll talk about how everyone is all excited about domain driven design now
but really it's just 'model your game in terms of what it is'
so you would decide what things happen in your game and those would be your events
lmao!!! my VSCode AI extension just gave me a pat on the back 😐
not sure how i feel about that
(Yeah, I worked in FinTech consulting for several years, with a bit of DB development, scripting, app dev, etc. all thrown in there) The video game domain has always twisted traditional programming fundamentals on its head a bit, because of its more...real-time nature.
speakin of.. anyone using VSCode? Codiuem seems to have gotten a new Brand..
I felt this way when I started doing game dev and then came full circle to that it's the children who are wrong
Windsurf
Hahaha, I'm ready to feel the same Prakkus.
if you are comfortable with it, model your game as a relational DB with CRUD events and you can do a lot with that
ahh, if u've done app dev, and DBs you should be way better off than most begniners
update your ui every frame because it doesn't matter, or optimize places where it does if you want to
and just have stuff that gets queried and updated
this is basically waht ECS is too, just with a different data structure (and since it's your gamestate, you can use whwatever structures you want, mix and match them, go crazy)
I definitely feel like I'm starting in a better place. It's the 3-dimensional math and Unity-specific thinking that throws me through a loop. The philosophy of "who does what" is something I'm still trying to understand, but the logic of game programming comes naturally to me.
So to wrap this up then, I'm actually thinking of creating a UIManager that sits between UI elements and the SurvivalManager and communicates for them.
The UI manager will keep references of each ring, and pass them values from the SurvivalManager either when they change, or simply every frame (as their values are typically changing every frame anyway)
Is there any clever/more efficient way to check if an object in 2D is outside the (fixed) screen bounds? Or do I just need to keep manually checking its position? (If it matters, it's for a moving object that's supposed to despawn once it goes offscreen, and will only show up in small numbers at a time)
theres a good ebook for free that helps out with Game maths/vectors and stuff
Oh yeah?
You either use colliders and adjust the colliders to the camera position/size or you check the position in code. WorldToViewportPoint is useful for the code option
Awesome, I'll add this to my nighttime reading. 😉
And - thanks everyone. The discussion was helpful (if only a bit long-winded to get to the practical answer 😉 ) I appreciate the patience and the desire to help others out here.
no prob.. insight is usually moer useful to someone thats "really" trying to learn than a concrete answer anyway 😄
If I've learned anything during my time on the internet, it's only worth investing time in the people who are truly trying to learn/discuss/grow in good faith.
bruh.. if ur here any amount of time.. get ready to see things that'll blow ur mind
BTW, I wanted to clarify something about the C# naming conventions. I think you sent me this yesterday, Spawn? https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names
Am I understanding right when it says "Use PascalCase for constant names, both fields and local constants" that if I defined a reference to a class called SurvivalManager in my UIManager, that I'd called it "SurvivalManager"?
and i totally agree.. as do most of us thats dedicating our time to help out..
if ur not "trying" neither will we..
Or does it mean that when you create the SurvivalManager class, you make sure it's Pascal Case. But when you reference it in another script, it's _survivalManager?
thats a good question tho
I understand that. But maybe a better question is: when at the top of my UIManager class I include:
[SerializeField] private SurvivalManager _survivalManager;
What...am I doing? I'm creating a...what? Field?
And "should" it be static because it will never change?
it could be static... i personally use singleton patterns
that way theres no mistakes..
if theres multiples by accident it gets cleared up
I would in this case but the game will be MP. Which if I'm understanding right, I couldn't use the singleton pattern. (I'm gonna say up front though, that I haven't even broached the MP element yet, so I might be way way off)
i personally still use camelCase for private class variables
this is the convention i tend to follow
I'll use the singleton pattern for my "WaveManager" that manages enemy waves of increasing power.
I actually like this a LOT more than putting an underscore before every. Single. private. field.
I did this for the SurvivalManager after reading the C# documentation and I hated it
yup.. i dont like _ or the m_
i use those for method parameters. b/c i have fewer of those
void SetHP(int _newHP)
Cool. Thanks for this.
the countdown bullcrap at the bottom is just residual context from my last AI session.. i have my AI reformat my code for me quite a bit
so it has my nameing convention memorized
@odd remnant there happens to be a Unity doc for naming convention as well as teh C# one..
thast how i put mine together.. ill see if icant find it right quick
That'd be great. ❤️
here ya go
aye... i did it right!
the best advice i can give u.. is don't go all cryptic..
i hate when ppl code with letters and integers
100%. One of my prides is clear, clean code with just enough commenting to help explain big decisions, and remind Future Max to come back and fix his past terrible, terrible mistakes.
ive slowly been getting better at readibility
the easier it is to read the code (mainly for good naming) the less comments u need as well
It takes time and experience to realize "oh shit...maybe I should have done..."
Even stuff like in-line curly-brackets can make a difference.
lmao.. good thing i've spent 50% of my 4 years learning doing absolutely nothing but refactoring my code 😬
Personally I despise when people do:
else
{```
ONE missing tab and you're gonna lose track of that else somewhere.
well,, you'll hate me 😄
Hahahaha
all my conditionals are new lines
I MEAN 😡 😡 😡 😡 😡
its easier to read!
It is, kinda. I'll admit.
you been using switch statements yet?
Occasionally. I haven't had much need for them, but I will soon when we get into collisions.
how long you been learning Unity so far? im curious
I should be working on the base game mechanics and making the game fun. But there's a piece of me that constantly nags about elements like UI and core mechanics.
1 week?
Maybe 2?
bro.. str8 gangsta lol
Hahahaha
keep doing u 👍
tbh it may be more of an investment up front...
but it'll definitely pay off
I had experience about 10 years ago in uni, studied game dev and design. But we worked in the professors' proprietary engines instead of a mainline engine.
wait til u start writing editor scripts
But yeah, this is the most serious I've been at it.
Haven't heard the term yet. I'm curious.
the Unity editor is 100 percent customizeable
you can write your own Editor scripts..
that make ur normal game developing easier for example
I've been thinking about this, and meant to ask here about it. Sometimes Visual Studio has ZERO context that I'm developing a Unity game.
And other times, it has TONS of context.
What am I doing wrong?
Aww, really?
ive been hearing alot of that lately..
I like studio. :3
tabbing in and out..
may or may not set it straight..
ive been having a problem where tooltips and stuff from VSStudio get stuck on the screen
not until i force close it do they disappear... 2 months of that and i swapped back to Code 
Rider is free now for non-commercial 😉
Like here.
It doesn't know that "Image" is a class.
Nor does it recognize [SerializeField]
make sure that your !IDE is configured 👇
do you have the using UnityEngine.UI; namespace?
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
It still doesn't like it. But lemme try the IDE Config. I was sure I'd done this before.
Yeah mine's installed.
if you follow all of the instructions in the guide and it's still not working then go through these steps: https://unity.huh.how/ide-configuration/visual-studio#if-you-are-experiencing-issues
K. I'll try the first link, then the second. ❤️
including the unity workload for visual studio?
yea u should def configure it if u havent..
but i was correct.. Image needs the UnityEngine.UI namespace
It's installing an update, I'll get back to you in an hour. 🙃
Editor Scripting 😈
one of the many reasons I believe Unity is the ultimate prototyping/sandbox
if u can imagine it u can build it
oh.. soo Unreal has this (1) tool that Unity doesn't? Hold my beer
very true.. lol.. live and learn
the search feature on unity is actually pretty incredible now imo
HOO BOY, another "best practices" question: In a multiplayer game, are Managers unique to each player (like SurvivalManager and UIManager) children of the Player object in the scene hierarchy? Or do they sit elsewhere?
That's way too vague of a question
every game handles things differently
Also "multiplayer" is vague - are you talking about splitscreen or networked multiplayer
in a networked game there's only one UI
there's no reason to have a UI object for players owned by other people on other computers.
Woah, ok. That's NOT how I understood how games worked. I figured the UI was a client-side element, and so there would be some kind of "local" object managing the UI client-side, and a then a "server" object running elsewhere that passed information to the client. This is an area I haven't researched or done enough tutorials on yet, so I'm maybe jumping into the deep end too quickly.
yes the UI is a client-side element
the information the Ui is displaying - that could come from all kinds of places
Ts pissing me off becuase it seems like it should be so easy
I understand i cannot set transform like that
I have looked up how to do it like 10 fking times
And they literally just do exactly what i wrote
and it works
I cannot find a solution to this
All i want to do is set the transform of the current object
Oh my god
Every single unity discussion post i go to provides a solution that does not work
Yo Holdup
I might be slow
Actually in that screenshot im doing == which is wrong
but i changed that later, just a single = still does not work
this is more accurately the problem
Like why does every discussion post i go to write the exact same code as me and get no errors???? ive been searching for what makes mine different for like 20 minutes
That is not the exact same code. In your final screengrab anyway, you are trying to just change the x component of the vector. The components of the Vector3 struct are not able to be written to directly.
This will work for your case:
Vector3 pos = transform.position;
pos.x = 8f - size/2;
transform.position = pos;
why can't i do something like gameObject.transform.position.x
or this.transform.position.x
or idk
Some type of way to do it in one line
by referencing the current gameobject
Okay, you're checking if the X position is equal to 8f - size/2 then doing nothing with that result
Nono i accidently made it a double equals while trying things
in that screenshot
i reposted what im actually trying to do
You cannot both get and set an individual property of a vector in the same line. transform.position returns a copy of the vector, since it is a property, not a variable.
You need to store the vector in a variable, then modify it, then set transform.position to that vector
Or you could set the entire vector at once, transform.position = new Vector3(...
I just don't understand why pepole on the internet did what i did and got no errors
not just in that screenshot in multiple videos and other places
so strange
No one would ever be able to do transform.position.x =
Show somewhere that modifies an individual component of position
hey digi.. do u copy the entire value and modifiy it?
or do u construct a new one?
i wanna know ur ways 👀 lol
i think they added a new Vector3 in the same line
so thats why it worked
Depends on the context
thats fair 👍
Sometimes it makes sense to make a new vector, sometimes it makes sense to store it first
I'm currently trying to make a behaviour tree for the first time. Would people generally recommend working on the classes for all nodes in the same script or in separate ones?
Use separate scripts for your classes . . .
Hey i been struggling with smt. My current dialogue system is fully hard-coded wich is slighty frustating meaning i need to make an army of scripts for each single Npc and interaction. I been trying to make it modular but i get confused and doesnt work. My teacher recommended using Xml as a DataBase wich made sense but seemed harded...
Idk what to do
You could use ScriptableObjects to hold the texts or use a dialogue system like YarnSpinner.
Ink is free
Not exactly code question per se, but how can i add a custom mesh collider to a model i created in blender? what would the process of this look like
You would put the mesh collider on the gameobject that actually has the mesh
if its not code question why ask in code channel #💻┃unity-talk
oh ok ok. didn't know that was a place to ask questions! thanks
yup, thanks alot !
hey yall, im trying to make a dialoguebox so when you press the interact button inside this specific box, a specific dialogue will trigger
the ontrigger works and detects the player entering, it can detect when the player presses "interact", but it doesn't output the message when both happens
i think what is happening is that it checks as soon as you enter and then never again, which is not what im looking for, i tried setting the first if to a 'while' but that crashed unity
i am going to save, and change that second if to a while and see what happens, wish me luck
that will crash
While loops run to completion
it... didn't
Well, then it never reached the while
When a while loop runs, the code inside the loop is the only code that can happen
if the code in the loop does not eventually make the condition false, it will crash
btw there is no way you're going to be able to GetButtonDown OnTriggerEnter
OnTriggerEnter runs the frame this object enters the trigger.
GetButtonDown runs the frame you start pressing the button.
Checking both means that you're going to need to hit the interact button the exact frame you enter the trigger
not likely.
use a boolean for OnTriggerEnter / Exit and use that in Update for Keypress
something like isInTrigger = true
thats what i thought was happening, so im gonna need to look for something that isn't getbuttondown, or something that constantly checks rather than just triggering once
lets try that!
that could also work but iirc thats in the Physics Fixed loop no ?
Fair, you'd still potentially skip a button press
Using a bool in enter/exit is probably the better choice
i wonder how many of these dialogue scripts i can have constantly checking to see if the player is in the boxes does to the performance, probably want to turn them off when the player isn't near

honestly this is just for a uni project, ill check when i develop this game a bit more to see how much the computers there can tank
often its a non-issue , computers today are very powerful
bool checks are fairly inexpensive and unity already does the OnTrigger messages
hell yeah, thank you friends for your help
is drag changed to damping or am i tweaking?
Yes
What is like, the sintaxis to cast a Renderer as a SpriteMask? I am too dumb to freaking find it lol
It's just normal cast syntax, nothing special at all?
(SpriteMask)renderer
Ye, I was trying to do renderer(SpriteMask) and was not working, thxs
It's very strange to be making up new syntax at this point, haven't you been programming for ages lol
Not that much really, I stopped for a while, and casting stuff is not a thing I do often so....
As you can see I am far for a pro lol
public interface IPointerUpHandler : IEventSystemHandler
{
private void OnPointerUp(PointerEventData cursorData)
{
Debug.Log("trigger");
if (((int)cursorData.button) == 1)
{
Debug.Log("rmb down");
}
}
}
am I doing something wrong? no debug msg is getting sent
For this to work on colliders you need physics raycaster on the camera and make sure you have event system in the scene
Wait also did you not put this in a Monobehavior script?
Idk what the top two lines you wrote for lol
I'd be more like
public class MySctipt : Monobehaviour , IPointerUpHandler, IPointerDownHandler
spelling errors probably , I'm on mobile rn lol
thanks, for ur latter advice, I cant add them to a class
what do you mean you can't add them to a class ?
Yes you need to implement the method associated with that interface
Your IDE should be able to insert that for you if you ctrl + . On the red underline in the Ipointer part
ah thanks
btw probably a good time to learn about Interfaces lol
factomondoz
yea good idea lmao
Hey guys i wanna learn how to code but every tutorial is getting me no where can u help?
Maybe show an example and explain what you're getting confused by and someone could maybe help explain it?
yeah i just stared coding in unity i was wondering if u know how i can learn better of faster
Do more tutorials
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Or pay thousands of dollars for a private tutor.
I charge up front and also expect mileage and per diem
👍
speaking of learn.unity is there a page on interfaces it in the unity documentation
How should I be storing data in tiles for a tilemap like passability, gameObject occupying it, etc? Right now, I have a separate dictionary storing the tiledata mapping a Vector2 to CellData but I know that I could just inherit from the Tile or TileBase class and make my own, any tips?
hello! i'm trying to make it so that the player character either falls or experiences a consequence (e.g. disappears/takes damage) for not being on the platform.
i've found a lot of conflicting opinions (and unfort not a lot of helpful tutorials) on the most long-term efficient way to implement this, so i thought i'd pop in here for some extra advice!
e.g.
- 2.5D (doing everything 3D and using Z axis manipulation to make it seem like 2D?)
- OnTrigger-based collisions/scripts (Easier for me to understand/I've practiced this more, but I'm worried it would be inefficient with every individual platform?)
- Raycasting/layermasking? (seems promising! but I'm sort of confused about how to apply it consistently over a flat plane for this specific prototype)
- OverlapBox (similar to above -- Switch & Case may be helpful here to save on processing from what I've seen? As opposed to the dreaded ten million If-Else's)
currently the rigidbody2d gravity is set to 0 for the top down appearance, attached a video below + i can attach code of the player movement & dashing script if that helps! any input at all is really appreciated :]
seems like a triggers and colliders would be sufficient enough..
and since its top down you can shrink the size of the cube a bit when not on the platform to simulate it falling (being farther from camera)
2.5D sounds overly complex unless theres other usecases for ur game..
raycasting seems pointless in this scenario..
idk bout overlap box
nah, w/ triggers u could have the platforms as the trigger part.. and if u leave that ur not on a platform..
youd have an enter method on each of em for platforms.. (i dont see why it wouldn't be performant)
it'd be silly to have the triggers everywhere but the platforms imo unless we were to see some more context of the level designs and what gameplay is
i seeee. yeah tbh I'm trying to prototype something with inspo from Hyperlight Drifter and playing around until i land on a core loop that feels good
should i be writing something like an OnTriggerEnter if-else statement?
yea, i think ur overthinking it.. for now i'd just chose a method and go with it.. if u structure the game right.. and design mechanics in pieces then u shouldn't be that hard to swap over the platform/not platform detection whenever you feel like it
OnTriggerEnter -> onPlatform = true;
OnTriggerExit -> onPlatform = false;
then do w/e u need with that boolean
if i understood correctly an interface is kind of like a reverse method?
reverse method ? 🤔
instead of calling code in the script it calls a script and then calls code
no not at all
interface is a "contract" on the implemented class, it basically forces the class to implement the methods or properties in the declared interface
this ensures that anything that implements an interfaces always has those methods associated with that interface
that was what I was trying to say except 100 times worse XD
the interfaces themselves never have code in the body of a method
its up to the class how to proceed with the code inside
from link I sent you can see perfect example with common use which is an IDamageable interface
thats actually why i called it a reverse method
the class itself does the values not the script calling the interface (im kinda shit at explaining things sry)
its not about being shit at explaining, you just have to learn the specific terms lol
script calling the interface , there is no calling here.
it "Implements" the interface
what i still dont understand is why this isnt working
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("eeeee");
if (((int)eventData.button) == 1)
{
Debug.Log("rmb down");
}
}
Is it still depending on the collider to detect for right clicks?
first of all you have to show what you've done in terms of implementing this method and where the components are etc.
it would be good idea to also explain the exact use case of what you're trying to do
public class PlayerManagerf : MonoBehaviour, IPointerUpHandler
i'm just trying to use the _player gameobject as a button
and did you add the component on the camera I mentioned earlier?
this is the correct one, yes?
also remember this ?
Note: In order to receive OnPointerUp callbacks, you must also implement the IPointerDownHandler interface
mustve glossed it over, lemme go do that
done, but another question, is this dependent on the collider of the gameobject?
i think for world objects yea
Oh I understand the problem now, I'm already using the collider to detect for left clicks and it cant actively detect both
(atleast I think thats the issue)
what?
sounds interesting, ScriptableObjects then, yet i need to figure out how to do so but i will eventually, thx
