#π»βcode-beginner
1 messages Β· Page 742 of 1
Yes. You usually want ui decoupled from the game logic. The ui can just set some kind of index that some manager would read and use it to spawn the right character later.
ohh yeah i understand a stage system seed > sprout > littleplant > Fully grown I'll see which one looks better
Ah that makes sense, thank you for your help hopefully I can figure that part out
i don't konw what string is off becuse llline 23 seems right to me. it is from tutoirall i followed
currentEscapeStages is a string. Did you write the scene name inside that variable from the inspector?
If not, then it is empty. You don't assign a default name in the script . . .
i think the tutoial i followed was unity 2021
That doesn't matter . . .
Did you read my previous message and check the variable?
that is irrelevant. you needed to assign a value to your variable in either version
yea i did
Show the inspector field
SceneManager.LoadScene(...);
Debug.Log($"Next stage: {...}",this);```where `...` is the stage etc
If I am using this system to hold the data of the damage dealt, if I clear the damageLog, do the recountEntries, that no longer have any reference to them, keep occupying space in memory or it's fine?
The .NET Garbage collector will collect the classes when they have no more references to them
So yes, clearing the list would eventually have the GC collect it when it runs
I guess it's not worth for me to even try to do it manually right?
Do what? Clear it from memory? No
One thing you could do is improve how memory is managed. Things like class pooling or using structs can help since references are less abundant and you reuse them for different purposes, but this is also specific to what you need and might not fit your use case (i.e. I believe you can't serialize a struct like you have there, and it can't be shown in the Unity editor (probably could with a lot of extra steps though))
The best thing is to have the GC run as little as possible. Every run slows down your application.
But know this is mandatory. Realistically you can't work without the GC ever running
When assigning a listener to this button, I am using the iterator variable
void Start()
for (int i = 0; i < buildOptions.Length; i++)
{
print(i);
newBuildTile.GetComponent<Button>().onClick.AddListener(() => StartBuilding(i));```
But when I print it later it always gives me the max index of the loop for some reason, as if it's overriding all the events for the previous loop iterations??
```cs
public void StartBuilding(int option)
{
print(option); // Always gives me buildOptions.Length```
Ohhh I see, so it's basically just keeping a reference to the iterator, and calling upon it's final value when printing it.
Thank you very much!
posting in the wrong channel for a start π
Delete and ask in #πβanimation
for some reason when i execute this, the rotation of said door goes to (-90, 0, -90)
Whoops
Forgot to change channels
I think I did on my pc, but im on my phone now
After dashing twice I get this error message that interrupts the game test (im assuming this would be the game crashing in a finished build)
in this script at line 431 I have a function that should make the momentum carried after a dash slow down smoothly to feel nice. This works flawlessly on my Laptop but not on my home pc for some reason.... the laptop runs on Ubuntu and the PC on Windows 10 not sure if that's relevant
this is the formula I use to slow down the momentum after the dash
So i need some assitance with this because i just cannot find a consistent answer because of the fact that unity changed its input system and people are either using the old one or they have made their own
this is the movement script ive written
and these are the sprites, I just want it so that when the direction keys are pressed the currently show sprite is swapped to the one of the direction the player has pressed
where you see sprite render.sprite = upsprite thats an attempt i made to get the sprite renderer to change sprite so ignore that
you don't need to do that
you can just change the x scale *-1
so just put a - before it and it will flip it around for left and right
for the new input system I can recommend "game code library" 's tutorials on youtube they helped me understand it too
my sprites arent asymetrical. so something on the right hand side of the player sprite wont be on the left so i cant just invert the sprites
so the cat sprite facing the camera is the walking downwards and the one facing away is walking upwards. its a top down isometric
fair enough
well I can show you a method of handling input if you want using the player input component
the sprites you can do in different ways
either with an animator or if you really just wanna change the sprites you can load them out of the resource folder
the resource folder one is what im looking for. the game doesnt have any actual animations. its just static images facing cardinal direction
could you point me in the right direction so i can figure this out please
you can do this:
image.sprite = Resources.Load<Sprite>("CatSprites/CatfacingLeftSprite")
the path starts in your Resource folder meaning anything you wanna load this way you want to put in the resource folder
hope that helped
loading a sprite every frame is probably not ideal. You can just reference the 4 sprites and assign them in the inspector:
public Sprite upSprite;
public Sprite downSprite;
etc...
The assigning you did with spriteRenderer.sprite = upSprite; should work fine, you just have to add the other 3.
the input handling is kind of flawed as well since more then 1 key can be pressed at a time
i did the old input method of input.getaxisraw and all that but i believe im using the new system. but apparently not
well, you want errors if you are missing a sprite, no? Better than wondering why it doesn't work.
that code looks like new input system, but most people do not try and access key inputs directly, but setup action maps which can include a vector2 movement action
If the issue is still ongoing: I'm pretty sure f turns to NaN once x is larger than momentumCurveTimeVar, since Mathf.Sqrt of a negative number will return NaN
you also should calculate the move vector from the inputs. X is left/right Y is up/down, than you can normalize it and use it to translate your transform.
Because right now your character is moving "faster" if you move in two directions at the same time (like up and right).
other reason to get it as a vector and map a proper action for it
Hello fellow humans, I need to learn a bit of C# to work in Unity, I need for college, do you recommand looking for an tutorial that can teach me C# or are there any good tutorials that teach you specifically for Unity?
can have the input system normalize it for you or just do it in code after
!learn will teach u specifics of unity
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
BUT will not teach you c# because thats its own thing as a programming language
Oh alright, thanks! I will start learning from there!
ah I think I know what the Issue is then
I don't know literally anything about coding π
At the end of the block they will interview me how I made it, so I can't pass it xP
I already know my stuff so im good
Even if I use ai I need to understand what the ai is doing
110%
Yea then you try to make it do something with some obscure lib and it just makes up non working code
yea i do π
AI rubbish can only do the easy parts, and then just leaves you without the proper background to handle real issues
I guess you can go talk to claude then instead of us
@wooden cypress This is a learning community, don't send people to LLMs. If you are just here to troll you are welcome to leave.
Does anyone know how i can call CloudCode from a Server sided Entity System?
All the functions seem to be async and public void OnUpdate(ref SystemState state) I cant make this async cause of ref
how do i fix raycasts going through walls? below is my raycast hit script (all thats needed)
if(Physics.Raycast(ray, out hit, interactionDistance, interactionMask))
{
InteractionText.text = "Press '" +InteractionKey.ToString() + "' to interact.";
if (Input.GetKeyDown(InteractionKey))
{
RcHitOBJ = hit.transform.gameObject;
if(RcHitOBJ.gameObject.CompareTag("Door"))
{
DoorMain doorScript;
doorScript = RcHitOBJ.GetComponent<DoorMain>();
doorScript.OpenCloseDoor();
}
if (RcHitOBJ.gameObject.CompareTag("Holdable"))
{
DropHeldItem();
HeldItem = RcHitOBJ.name;
RcHitOBJ.gameObject.GetComponent<Rigidbody>().isKinematic = true;
RcHitOBJ.GetComponent<BoxCollider>().enabled = false;
RcHitOBJ.transform.parent = objectHoldStorageLocation;
RcHitOBJ.transform.localPosition = Vector3.zero;
RcHitOBJ.transform.localRotation = Quaternion.Euler(0, 90, 0);
}
}
}```
well right now ur using a mask to only hit those in that mask
so if ur walls aren't included it shouldnt be hitting them anyway
thats the reason.. its going thru the walls.. as well
what i mean is if im behind a wall and i have a door on the other side, it will allow me to open the door
yea.. b/c its only hitting the layermask which i guess the doors included..
its going to ignore walls (if they're not included in the mask)
how would i remedy that
they raycast does not see walls at all due to the layer mask so walls can not block it
you would ^ include w/e u want in the mask
and then check each object and see if its a wall (ignore)
or something with the doorscript (open)
a TryGet works well here
TryGet?
its like a GetComponent.. but better (it'll only run the code block if it can get that component)
Damn its so backwards, to call async functions via an authoratitve server i'd have to make a mono behaviour and do the async call there, then my server sided system would have to just poll that monobehaviour through a singleton :S
Spaghetti
Hello, I found one error when I update to the 6.2 version today.
I tried to edit an array within another array in a scriptableObject file in the Unity interface. It all bugged, and the console displayed an error. The console error and the ScriptableObject code are in the link below because they are large: https://paste.mod.gg/zycabokifqer/0
A tool for sharing your source code with the world!
alright, i think i got it. how do i check if something is a certain layer?
would i do if(hit.transform.gameObject.layer == interactionMask)
not exactly.. a layerMask is not the same as a layer
bc this wont work for me, i have multiple things using this interaction raycast. its not just for doors its a general interaction raycast
Thats true, a layer mask is meant to signify potentially multiple layers
yes it can either be an int for its index or an int where a single bit is the layer.
void Update()
{
// Create a ray from the camera through the mouse position
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
// Shoot the ray into the scene
if (Physics.Raycast(ray, out RaycastHit hit, rayDistance, rayMask))
{
EdgeHud currentEdgeHud;
if (hit.collider.TryGetComponent(out currentEdgeHud))
{
Debug.Log("Found an EdgeHud on: " + hit.collider.name);
}
}
}``` if u use a `TryGet` u can compare and find out if the hit has a certain Script
yes, im not adding a script to everything i wanna interact with so this is a no go
like in this example its looking for a scritp called EdgeHud ^ if it finds one it can do something with it if not it just continues code
a gameobject can only have 1 layer so compare the layer value to a stored value say from NameToLayer
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/LayerMask.NameToLayer.html
u can use TryGets w/ interfaces as well..
thats what it is rn
so 1 script could call a function from every script w/ the same interface ..
just giving a bit of knowledge.. u don't have to use it.. but TryGets are better than GetComponents <-
if u end up using GetComponents its teh same line of thinking
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, interactionDistance))
{
if(hit.transform.gameObject.layer == 6)
{
InteractionText.text = "Press '" + InteractionKey.ToString() + "' to interact.";
if (Input.GetKeyDown(InteractionKey))
{
RcHitOBJ = hit.transform.gameObject;
if (RcHitOBJ.gameObject.CompareTag("Door"))
{
DoorMain doorScript;
doorScript = RcHitOBJ.GetComponent<DoorMain>();
doorScript.OpenCloseDoor();
}
if (RcHitOBJ.gameObject.CompareTag("Holdable"))
{
DropHeldItem();
HeldItem = RcHitOBJ.name;
RcHitOBJ.gameObject.GetComponent<Rigidbody>().isKinematic = true;
RcHitOBJ.GetComponent<BoxCollider>().enabled = false;
RcHitOBJ.transform.parent = objectHoldStorageLocation;
RcHitOBJ.transform.localPosition = Vector3.zero;
RcHitOBJ.transform.localRotation = Quaternion.Euler(0, 90, 0);
}
}
}
}
else
{
InteractionText.text = "";
}
}```
that is the function rn, i go check it in game (the function is being called in update) it doesnt work. yes 6 is the interaction layer
Is your mouse locked or unlocked?
locked
I forget if its forced into the screen centre when locked
it is
it is
Cool then lets presume the raycast is hitting someone else, the layer is not set on the object with the collider or the distance is too small
Perhaps some Debug.Log() s will help or you can try to use a Debugger if comfortable
Debug.Log($"Always debug your hits: {hit.collider.name}");
i shall figure this out later cuz i gtg
if(hit.transform.gameObject.layer == 6)
doorScript = RcHitOBJ.GetComponent<DoorMain>();
hardcoding layer comparisons and using GetComponent
yet :
yes, im not adding a script to everything i wanna interact with so this is a no go
in regards to using TryGet..
odd.. that statement doesn't make any sense as that's what you would need to do w/ the GetComponent
(if u have more interactables.. for example)
is the hit a door?
is the hit a switch?
is the hit a lever?
each interactable would need a new block of logic
i just make Interactable a interface, can use TryGetComponent to check if something can be interacted with then each thing can implement that interaction how it wants
Use an interface so that every interactable has a standard method to call . . .
public class Door : MonoBehaviour, IInteractable
{
public void Interact()
{
Debug.Log($"Interacted with {gameObject.name}");
Debug.Log($"Its a Door");
}
}
public class Switch : MonoBehaviour, IInteractable
{
public void Interact()
{
Debug.Log($"Interacted with {gameObject.name}");
Debug.Log($"Its a Switch");
}
}```
and then:
```cs
public class InteractRaycast : MonoBehaviour
{
public Camera mainCam;
public float rayDistance = 100f;
void Update()
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, rayDistance))
{
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("Found an interactable on: " + hit.collider.name);
interactable.Interact();
}
}
}
}
}```
well i would key check first unless you are changing UI or something
and return early as needed to reduce nesting
i think he's misunderstanding...
i mentioned TryGet and he says nah, im not adding code everytime..
but then rocks the layer comparisons and GetComponents anyway
but he'll sort it out later π
hmmm I just realized something
protection level doesn't seem to matter on functions within interface
is that an accurate assumption?
public void
private void
it does in some cases like if internal
but yeah not really, now there are two ways of implementing the interface though
ohh okay.. but POCO it doesnt?
well i mean its not concerning for basic use?
interesting..
like when implmeneting it you can do it publically or do InterfaceName.MethodName to do it in such a way you can only see the method from the interface
All methods declared in an interface are implicitly public.
ohh okay.. so I can't actually put private void Interact()
i mean I can.. but the raycast script that calls Interact() doesn't compile
learn something new everyday
yea i just did
ignore me.. coffee still in standby
now there is a trick to hide the method for things that have only the concrete class and not the interface
can be useful sometimes if do not want to clutter up auto completions
and guide people on usage more if its only used from your own lib code
A. cs hit.collider.TryGetComponent(out DoorMain currentDoor);
B. cs hit.collider.TryGetComponent<DoorMain>(out var currentDoor);
C. cs hit.collider.TryGetComponent(typeof(DoorMain), out Component comp); DoorMain currentDoor = comp as DoorMain;
π This is something I need more experience with..
the whole generic stuff.. dynamic type, known type, & so on
C is mostly for cases where you get a type a different way and need to pass it
ahh okay
like if you got it via reflection etc
yea.. lol we'll hold off on that a bit longer π
A and B are the exact same thing
will do π«‘ thanky sir
ya, 1 just has a variable it can use
and the other just creates one real quick
i get those two... it was really C. i struggle with
both are creating it
not creating it would be if you declared it above and did not add the type / var part in
ohh u right.. my screenshot is where it just uses an existing one
#π»βcode-beginner message this one
yeah existing or not is just about how you want it scoped
as long i dont need to use the C one too often im good lol
thanks for the insight passerby π
i always look for tryget snippet to copy and paste.. and they always
seem to be more complicated than the one i use
TryGetComponent(out whateverReference)) is the one i can never find..
have to start off with auto-complete in the IDE and just remove the bits until i get clean syntax π
they should matter, it just has a different default
class members default private, interface members default public
so just like private in classes technically doesn't do anything, same for public in interfaces
yup yup.. thats the part i learned today
interesting.. i never even knew
how do we check if a raycast hit is null or not?
hit.transform == null
i can't think this morning π© a
π€¦ββοΈ π«
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
or hit.gameobject
hit.transform's good for my intentions π
hi,I'm trying to make a boosted effect for my player and I've done everything the way I thought would work, but once I pickup the gameobject that's allowing me to use the power, I get an error in the console saying I'm still trying to access the destroyed gameObject, https://paste.ofcode.org/3a7D2rV7vW3nYdXuEB5ZrWe, https://paste.ofcode.org/s5jumWbtsBM6ZdudKJmAzV, https://paste.ofcode.org/eJH6KVD98pKuUJntBnYYeE
all those 3 scripts work together for this
and the error is in which one
it doesn't include any of this
once u pick it up.. do u destroy the "pickup" object?
and if so.. is there any of ur code that might still be trying to access it?
sure it does, show us the error in the console. Have the error selected so the callstack is visible
yes I destroy the picked up GameObject but I don't see anything still trying to access it
that is not what I asked for, only half
Click on the error... it displays more information (the call stack) in the section below
no, that's setting the currentBattery null, not trying to use it. It wouldn't cause an NRE on this line
this one else if condition is for Batteries, the one for the boosted player effect is else if (hit.collider.CompareTag("invicible")){}
I'm sorry I forgot to include this
you destroy invincible, but still try to use it here -> https://paste.ofcode.org/3a7D2rV7vW3nYdXuEB5ZrWe
assuming invincible is the same game object across the two classes
OH yeaaaaaa
tyy so much,I forgot this one was in the Update() function and I wasn't even looking at it
that error wasn't very clear (it may show further down that's cropped out which one of your classes it starts in). I worked it out from the UnityEngine.GameObject.SetActive(System.Boolean value)
....I'm really sorry
my brain is cooked after school
there you go.. class and line π
if i move the frustum, causing a bunch of chunks to be queued in the async chunk loader thread then i do a 180 flip with the frustum so now all those chunks that are being loaded are no longer needed, how should i handle the logic to prevent the queue from getting clogged or loading data that is no longer needed?
soo, whenever you get back to working on this check out what I mentioned and then the replies afterwards from other people.. You can build it however you want, of course, I just wanted to clarify what i was saying a bit..
Here's the setup for using Interfaces and a TryGetComponent() --
- ur interactable objects can just use an interface like:
public class Door : MonoBehaviour, IInteractableandpublic class Lever: MonoBehaviour, IInteractable - they must all share similar methods since its an interface.. you can have a method called
Interact() - the TryGet() would call
Interact()on any script that uses that interface (this way ur not remaking the code over and over... when you have a new object thats Interactable you simply make it use theIInteractableinterface or w/e you call it..
IInteractable currentInteractable;
RaycastHit hit;
void Update()
{
Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, rayDistance))
{
if (hit.collider.TryGetComponent(out currentInteractable))
{
Debug.Log("We successfully cached the Interactable");
}
else
{
currentInteractable = null;
}
}
else
{
currentInteractable = null;
}
}
- when the raycast successfully "gets" the Interactable you just cache it (store it in a variable)
- then u can use Input to check if theres something cached.. and if there is u just call the method on it (
Interact())
hows the logic look as it is now?
i send a request for a chunk through a pipe, the pipe sends the chunk back
i guess its not a pipe if its between threads
sender thingy mechanism
ahh yes, the sender thingy π
is async chunk loading considered beginner?
i thought my one sentence question was because it involved no code and is just abstract implementation ideas
maybe someone smarter than I has an answer.. i know very little about async or chunking.. π good luck tho
If you have a limit to how many loads can be happening at once, you need to somehow figure out which ones can be killed first to make space. Id think you want to kill those that are less visible/not visible at all anymore first.
its limited by disk read speed so i cant load an infinite amount at one time. The issue is how does a non-needed chunk know its no longer visible/needed after its already been called for load
perhaps you dynamically update some kind of priority on them as the camera moves and you can use that to kill off those who go below a threshold
e.g. angle from view
once i send it to the load thread i dont think i can like update the priority cause its no longer existing on the main thread
ofcourse you can
its not a seperate process
presuming these are not stack allocated only
so every time the frustum moves, i mutex lock the entire queue and validate each one again?
then you can infer this data without any writes when refreshing what loads can be kept
Perhaps then you can dequeue, check if the load should even happen, if not discard and continue
which then removes the need to do extra work to each queued item
hi, what could be the reasons InputGetKeyDown(KeyCode.M) doesn't get detected?
All my Inputs work well except for M, and the problem doesn't come from my keyboard
a dot between Input and GetKeyDown π
either you're calling that method from somewhere that isn't run every single frame, or you need to restart the editor. it's probably the first
https://paste.ofcode.org/dGJLnRPgKjzKjsXxpxK2AU, it's called in the Update fonction
consider logging both conditions
did you check if hasRedBull is true?
and yes I'll try to restart the editor
yes its
how have you actually confirmed that
and I've also tried to see if M KeyCode gets detected by logging it
in the inspector variables
it's set to true Once I pickup the redbull GameObject
and regarding the KeyCode,I logged it and it doesn't work
log both conditions at the same time, do not rely on the inspector because you won't see if the condition is false for a frame or two. and if it is and those frames happen to be the ones you initially press the M key (because it checks for initial press, not if it is currently pressed) then the if statement will be false
okay,I'll do this just after the editor is restarted, thank you
also you don't happen to be using some non-qwerty keyboard layout, right?
I'm using Azerty...
I'm not from the USA...
qwerty isn't just for that third world country!
see that's useful information that you should provide up front when dealing with input issues like this. i'd bet if you pressed the key that would be the M key on a qwerty board it would work because you probably have Use Physical Keys enabled
but I don't think it'd change something, this is only for the first letters that it changes something
ohh
if (Input.GetKeyDown(KeyCode.M))
{
Debug.Log("Input has been snatched!");
if (PlayerInventory.instance.hasRedbull)
{
Debug.Log("Player has Redbull!");
}
}``` try it this way (same logic but nested instead of combined)
ohhh Azerty π
Well I think someone hacked my pc
I didn't add any emojis to this
and added one to this
the one I put got deleted
and the one I didnt got there
@rocky canyon @slender nymph
sir?
well.. thats not good
and have you tried pressing the key where the M keywould be on a qwerty keyboard?
yes it works with ,
","
sorry for the time I've wasted but I saw 4 malwares in malwarebytes so I've just deleted them
but yea M is , in azerty, it's annoying, are there solutions?
https://docs.unity3d.com/6000.2/Documentation/Manual/class-InputManager.html
It's the use physical keys thing that's causing this
disabling it would solve everything?
hey folks, think yall can help me out ?
this is a code channel, if it's a code question then π
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #π±βstart-here
it is, just a second
DebugKeypress/ Input class
// update
foreach (KeyCode kcode in System.Enum.GetValues(typeof(KeyCode)))
{
// debug/print each *Down* Keypress
if (Input.GetKeyDown(kcode)) Debug.Log($"Pressed: {kcode}");
}```
little helper function that prints out the input keycodes /enum
but yea the issue i believe is what boxfriend has keyed in on
tyyyy bro
and yea it fixes it
but my commands for moving still are ZQSD instead of WASD
Azerty guys.. amirite π€ͺ
fr
i think its neat.. i'd be awful at typing and working with one tho π
i didn't even know that was a thing that boxfriend was talkin about
well.. i kinda did but never woulda guessed that was the case
how do i reference TextMeshPro UI in code
public Text ScoreText; doesnt work
Text is the legacy component
You want TMP_Text
it says type or namespace couldnt be found still
so add it
π‘ use your ide to help
it should have auto added it when you typed that, have you got your IDE configured?
I have this glitch where Im constantly jumping and moving backwards I think it has something to do with the code aspect
nvm got it working i forgot to add using unityengine.UI
thanks!
still.. it should have auto got added, have you got your IDE configured?
i dont think so.. i already had vs code installed and installed unity it didnt auto load c# file when i clicked is so manually import the scripts folder by locating it!
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
There's a handy guide for you
thanks!
think yall can help me out ?
still not working
I can't help beyond pointing you to the link... VSCode is / was a pain in the ass to get working with Unity. I'm on Windows so just use VS
yea no need im fine working like this
That canMove bool, do u change its value anywhere else? Or it's just true all the time?
if anything ill switch to vs later on
It is a requirement to get help on this server to have your IDE setup. You're pretty much coding with your hands behind your back without it! Switching to VS (or Rider) would be better
i guess im an old school guy
i guess its alright for now cuz im using a tutorial and just remembering and typing it out
true all the time
I can still move whilst jumping and moving backward
but the jumping and moving backward is unpromted
unprompted
the moving backward thing is fixed, but the jumping is still an issue
It's likely due to movementDirectionY u use to try to reset the vertical direction when grounded
alright, how do I mitigate this
Remove that variable. Check if it's grounded, then inside that statement, another nested if to check for jumping
If it's not grounded, apply gravity
{
if (Input.GetButton("Jump") && canMove)
{
moveDirection.y = jumpPower;
}
}
else
{
moveDirection.y -= gravity * Time.deltaTime;
}```
to a charactercontroller? no
then how do I proceed ?
make your own isGrounded check, maybe that's what's broken. cause the default one is pretty bad
how ?
raycast down by a tiny amount and if it hits something then it means you're grounded
It works fine for me most of the time. I just find it weird to multiply the entire input axis with the direction vector
yeah, mayhaps, I used the code ya gave me, and it didnt work, I added a rigidbody to the capsule and it just started spinning
U can just put those 2 values as float for x and z of the direction vector
May be u should put a Debug.log message to check when it jumps
Is this the right place to ask questions about popular assets such as DoTween?
Or is there some other chat, or maybe, an official server that would be better suited for such questions
When I call Instantiate to create a new object from a prefab at the same position my Player is at, the new object's OnCollisionEnter gets called immediately. I've tried right after the Instantiate disabling the collider on the instantiated object but it still happens. What is the way to do this? My torpedoes must be allowed to swim.
OnCollionEnter will not get called immediately. It won't happen until the physics update phase.
Disabling the collider should work, as should using Physics.IgnoreCollision
I've set collider.enable = False right after the Instantiate call though.
You can also use layer based collisions
Can you show your code? Maybe you disabled the wrong collider
or maybe there's more than one collider on the prefab
etc
GameObject weaponGO = Instantiate(config.prefab, startPos, startRot);
WeaponController controller = weaponGO.GetComponent<WeaponController>();
if (controller != null)
{
Collider weaponCollider = weaponGO.GetComponent<Collider>();
if (weaponCollider != null)
{
weaponCollider.enabled = false;
}
}
It's possible your if statement(s) are failing
the outer if statement and GetComponent seem pointless
Can you show screenshots of the prefab inspector
Debug.Log would help you here too
Well I did trim down the code a bit so you didn't have to look at the non-collider things.
basically it's very possible this code will do nothing, depending on how your prefab is configured in the engine
Does TorpedoController derive from WeaponController?
Yes
And does the object have any other colliders, perhaps on child objects?
oh.. hmm... good question. Its from the asset store (I have no artistic or animation ability). I'll look at that.
dang it. All day I've been messing wthi this π Thanks.
More debugging could have told you this π
So is the right thing to do to spin through the instantiated object finding all the colliders and disabling them?
Well for one, are you sure you need more than one collider?
Something like a torpedo I would expect to maybe have a single capsule collider on it
for two - I would make this the responsibility of the TorpedoController or WEaponController itself
it's pretty common to have an Init() method on a script that you call immediately after instantiation
Why does Shader.Find("Universal Render Pipeline/Unlit")
return null in a build, but not in the editor?
Could be that it was stripped because unity found no uses of URP unlit
usage in code cannot be detected during builds
that's probably right, unfortunately i can't find it in the always include shaders section
any idea what's it called?
have a material asset pre made and modify it
or you use a shader variant collection asset to ensure certain shaders + variants are included
best way is to have a material ready made to use/modify as that is most reliable
gotcha, so instead of shaders.find i'll just use my material?
Yea (e.g. via serialized var) and that then introduces a dependency that ensures the shader + variant needed is kept
Yo any 2d programmers here?
I tried to make my sprite character move with a script but it didn't work
I'm a big despisor of this pattern btw. Wouldn't it be much better to let a in-between factory method handle this? The way I see it is: an Init() call can be forgotten, calling factory.Create() can't be.
We dont make monobehaviours so for them its the second best way to perform an Init with args
you could have a factory that spawns and does the init so it wraps both steps
Try logging the value of delta.
If it's zero, try figuring out why.
Either input isn't detected or move speed is zero etc
In Android Version of Unity, how can I write a file into the User's Download folder? Like downloading a file
okk ill check that ty
and I need the External Storage Permission yes, I saw two methods to check and request, but how do I make it wait till the User accepts/denies
It's been 3 hours, ive tried everything, not a single download works.
Turned off windows security
idk what to do now
this isn't a code question
#π»βunity-talk
π
Permission.RequestUserPermission(Permission.ExternalStorageWrite); is async, and I want to wait to see if the user denies/accepts
I debug logged delta and it was responding, same for movespeed, weird, maybe it is an input problem. I don't know how to fix that other then just rewriting almost everything
Yeah I am just gonna rewrite the code with "input.GetKey", it will be easier that way.
Maybe it's due to your setup https://docs.unity3d.com/Packages/com.unity.inputsystem@1.15/manual/QuickStartGuide.html
trying to make a shader that indexes from a table:
#ifndef GETLAYERCOLOR_INCLUDE
#define GETLAYERCOLOR_INCLUDE
uniform float4 layerColors[10] = {
float4(1, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0),
float4(0, 0, 0, 0)
};
void GetLayerColor_float(float2 UV, out float4 LayerColor)
{
LayerColor = layerColors[0];
}
#endif```
`layerColors[0]` makes the output float4 black (all zeroes) but doing `LayerColor = float4(1, 0, 0, 0)` outputs correctly; how come layerColors[0] isn't returning the element at index 0?
(this is a custom function in a URP shader graph)
First of all it's a #1390346776804069396 question.
Hi im looking to find a way to track the players last frame not the current frame, but the one before that is there a way to do that?
Track what about the last frame?
the location
then ill be able to track the speed of a vr controller
grab its location at the start of Update before you move it. that will be its position from the previous frame. then after you move it you can use its new position and the previous one
or grab its position in LateUpdate if you don't have control over how it moves
I dont use VR but id really assume there's a way to get the speed if thats something commonly needed.
Otherwise there's a few ways to go about it. you just need to make a Vector3 for the last frames position and write the value as the last thing you do in update or write it in late update
right
how can i grab its position before update
should i use start(); ?
i didn't say before Update, I said at the start of Update. as in, the first thing you do in Update
Oh i see now so get the location of the current frame and then i can get the location of the next frame ty ty.
So now im getting a curious
is there a way to grab it from the last frame
it probably wouldnt be useful now that im imagining it
i feel like you didn't actually comprehend any of what was told to you
I did
dw
then your question has been answered
right i was just curious
if you COULD grab the last frame
but i got my answer anyways
so thanks
grab its location at the start of Update before you move it. that will be its position from the previous frame
literally the first thing i said
Okay.. maybe i need some sleep lol
of course, this is dependent on you getting the location before you do whatever moves its location that frame
so would late update be the next frame
no, LateUpdate is the end of the frame
if you store its current location in LateUpdate then when you get it in the next Update it will be the previous frame's position no matter what
ill need to make the numbers very sensitive if its happening withen the same frame
thanks
oh
i see
ty ty
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Idky Iβm having trouble with this but is there any good way to define tiles over a sprite - like say ur positioning shapes which are sprites like these into a grid youβve defined and need to check if they can be placed in grid bounds without overlaps
Needs to be checked dynamically too tho like if ur generating shapes to be placed in a grid
well if you have a grid, you use grid math, so decide where the origin is and then check that plus the right 3 grid squares for the red shape
or whatever shape you want
you do need to know their 'grid size' which you probably want to just set manually because there aren't that many shapes and that's simple
Hello, how to script to avoid copyright, it feels hard to do my own, idk how to code.
What kind of copyright are we talking about? Generally copyright is hard to enforce with coding. As long as you'd don't decompile games and copy paste the decompile code, but just learn from other people's code and adapt it to your needs, you don't really need to worry about copyright.
And if you don't know how, then just learn.
Ok
We copy codes all the time 
There is a first person movement script that's on the assets shop. Idk if I should just apply that script to my "bean player character" or would it be better to make the first person movement myself?
Thank you so much for the help
I've ran into a problem and I can't seem to fix it on my own so im just going to ask a question on how I would go about fixing this.
Am I allowed to share a picture of my problem?
π 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.
It is an error message that im trying to show but I have no idea how to add a comment? With a line number? Idk what that even means im just so tired and my head hurts
it just means adding a little // <== line [n] here in your code, signifying where the error came from
if it's not an internal/editor error, the error message will tell you what file and line it came from
start with showing the error
Like in a picture? And also where do I put the error message do I put it where the word "line" is? I need you to speak to me in crayon eating terms please, my brain is so worn out from trying to figure out code it's also like 3:00 am
You just define your shapes as a list of 2d integer offsets, and check them all
in that case you should probably just go rest first
that will lead to much higher productivity in the future
Yeah you're right I need to rest first before I try to do anything more. Thank you I'll talk later
There are no good official docs on urp lit shaders (non graph) so you may have to look at lit/simple lit and fudge in support if you are willing to try yourself
hello could someone teach me c# pls?
there are resources pinned in this channel
oh
wich one do i click? there are like 8 links π
just pick one of the links like geez dude 
I said just click one links at the time
im not gonna watch a tutorial or read a tutorial π i allready know my dumbass will run into a stupid issue that the tutorial doesnt cover. and ill get softlocked. i tried following tutorials EXACTLY once. and ran into an issue π
or i'll prob make a typo in the code and just brick the whole project and spend 30 minutes finding the typo π
dude just stop crying and get better at it it will be worth it
Then this hobby isn't for you. Nobody here will be a personal tutor, if that's what you're seeking you'll have to find and pay someone elsewhere.
trust
fair
I know about unity and I am new to it but I do know about c sharp
Hey there. I'm kinda stuck with an error saying "Optional parameters must appear after all required parameters"
i don't get why that's happening, am i doing something incorrectly?
This is a very basic fade in script that i'm working on.
[ContextMenu("Fadeout")]
private void LaunchFadeIn()
{
//only fade if not currently fading
if (IsFading == false)
{
StartCoroutine(FadeIn(2, new Color(0.5f,0.5f,0.5f)));
}
}
public IEnumerator FadeIn(float Duration = -1, Color FadeinAmount)
{
IsFading = true;
float Elapsed = 0;
if (Duration == -1)
{
//Default duration
Duration = 3;
}
Color CurrentColor = BackgroundRenderer.color;
//Fade amount
Color FadeAmount = new Color(0.5f, 0.5f, 0.5f);
while (Elapsed < Duration)
{
Elapsed += Time.deltaTime;
float Progress = Elapsed / Duration;
BackgroundRenderer.color = Color.Lerp(CurrentColor, FadeAmount, Progress);
yield return null;
}
IsFading = false;
yield return null;
}
is there a problem if i may ask?
with this code
I kinda not the best at knowing the parameter
Yes, the function parameters are invalid
FadeIn(float Duration = -1, Color FadeinAmount)
but i'll let the mod and admin awnser that
Optional parameters are ones with a default value (the = sign). They have to go at the end of the list of parameters in your function.
Thanks alot, i really appreciate that
beside I think you will get better at this coding
Oh so unasigned paramaters must be written prior
is that so?
Try it. Your FadeIn function.
i will.
it works now. That's a rather odd restriction, i never knew that, is this exclussive to c#?
also thanks alot!
Does Someone have a basic Tutorial for a 3d movement System i cant seem to find one
well i can find one but they are all ass
most tutorials are gonna be ass
they're usually geared to just get u up and running and to start familiarizing urself with the concept ur working on
no tutorial is ever gonna be 1:1 exactly what you need
its up to you to expand on it urself and adapt it to what u want
player controllers are a big deal.. between that and the camera movement its probably the most important part of the game..
takes time to make one fit ur game.. if its from scratch, a template, or even a bought asset..
hey why is unity saying the type ro namespace IEnumerator could not be found IEnumerator OnRightArrowRelease()
{
if (horizontalInput = 1)
{
horizontalInput = 0;
}
else
{
horizontalInput = -1;
}
yield return null;
}
did u add the using statement that IEnumerator requires?
btw, that horizontalInput = 1 is wrong. if you aren't getting errors in your ide, you need to configure your ide
!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
huh oh yeah i realised its ==
Hi. How to optimize drawing through a script? I have c# logic, was trying to draw it on a texture2D, but updating it every frame is very slow. I read people suggested to use Graphics.Blit or maybe shaders? I can't figure out how to connect it to a c# logic, and a bit lost. Blit function takes texture as an argument, so I will still have to set pixels first and I can't see the point there.
You can update picture only on draw, when you draw
For example when you selected brush and pressed left mouse button
I'm updating it through texture.SetPixels and texture.Apply. But doing it every frame will give me 20fps
Why do every frame you just need to paste on draw
If you are not drawing texture is not changed nothing to update
because it updates and moving every frame. I'm doing pixel stile particles with physics, something like falling sand or snow
graphics blit is the idea yeah
but I want it to be a pixel style and a plane picture, or look like it
modifying the texture cpu side is slow af
So you do not need to save texture at the end, you can use shader instead
can you help me with how to use blit? Some example would be great
how come only two variables are exposed in the inspector here?
is it possible to make a very specific logic in shaders? Im very noobie in it. I need to have control with every pixel. Know it location and state and update it. The whole size of a picture would be around 1000x1000 maybe
Well, like hunter said are you sure that a shader wouldn't suffice here? There's reasons to modify the texture if you were to stick it into other shaders later on in the pipeline
Going to presume you have compile errors
are you on that broken unity version where you had to open its inspector multiple times to reveal more variables?
That was a thing?
i dont, the game plays as well. im on 2022.3.62f1
yep, that's the exact version
Ha well time to update!
that's the last lts for 2022 though, they made more where they fixed it but that one requires unity pro π
sorry, enterprise or industry* not pro
its just some visual bug through where theyre not showing? i guess i can deal with that. not sure if upgrading to another version would cause more problems
Ah dang is 2022 already out of support
yeah you have to open its inspector multiple times
ya its visual.. as long as u can access ur public variables from elsewhere in ur IDE its fine..
except for the annoying inspector
they made a 62f2 for 2022 but i doubt they fixed it there
@civic gust You can use shader to display changes but you will also need to save draws into texture
That's for the cve fix
I think from shader you can draw to texure Using GPU instead of CPU so it will loss less performance but I'm also not an expert didn't do such logic before
You can create compute shader to write to the texture using GPU instead of CPU.
Probably too complex for them but yea a compute shader is the way to got to produce a texture
Hey, guys! How to create a camera-based crouching system like a simple one? Whats the main formula?
What do you mean? how to move the camera? Usually the main parts to crouching would be move camera down, adjust collider height and adjust movement speed.
cameraOffset = crouchHeight;
Yes I mean I know how to make it with character controller and the camera attached as a child to the player game object but what if camera isn't a child game object
There are different approaches probably you can do it with Cinemachine Cameras as well but is it meaningful to do so?
The same implementation would be used, the camera is moved down/up depending on being crouched.
Usually the collider height is reduced so we would move the camera down too. Its pretty trivial to animate/change the y position relative to your player object.
If you are using cinemachine to follow your player then you can use a follow target that gets moved down instead.
You need to explain more about your current setup to get better help if you still need it
No I am just wondering because I have made crouching system only with character controller once
and I had the camera as a child of the player
its the easiest setup for crouching
if you have camera as a child
with camera I wanted to create
camera-based crouching system without character controller like only the camera to move down and up
I have searched some people suggest lerp others suggest to use move towards method
for this to happen
well those are just choices you can make then
How do I let the user choose a file on Android? Like on Windows you can click on something, it will open the File Explorer and let you choose a file and give it to the app. I want that but in Android.
Thanks
Question. Lets say all my code is split up into different assemblies via assembly definition files and lets say for example I build my project out to an exe for windows, if I decide I want to update the "PlayerController" assembly can I just essentially drag and drop the one modified dll? or does the entire game have to be redownloaded?
It probably would work if class definitions did not get changed but if you are using something like steam it will just handle efficient updates for you
Is there a way to properly connect keyboard controls to ui button for main menu screen? I tried and the keyboard only works when you click on the mouse button i would like it to just work once the game or project runs?
in the editor you need to focus the game window by clicking into it. a build should typically receive focus as soon as it launches
wdym by if class definitions do not change? and honestly I am not releasing to steam. 30-40% cut just to sell my game is rediculous
So my plan was to have a post build script that will loop through every file in the output build and generate a sha256 hash and generate a json file. That json file will live on a webserver where the files will download from and then also on the client. The client will send a webrequest passing their json in and the server will compare what the player has versus what the server has and download the needed files. but just wondering if there is anything that will have to be changed each time regardless if the filehash changed or not.
look up library linking
anyway if you have a dynamic file update system then the problem solves itself
because if one dll doesnt change hash then we know it didnt change
going to do some reading into library linking
Is my overall concept correct on how things like this are handled though?
Honestly I was planning to go the tarkov route and force purchases through my website.
I think as long as you only care about the most recent version it should work as you describe
how do you guys organize your namespaces for runtime classes/enums/interfaces etc
or do you even use namespaces outside of editor stuff?
well if you do that make sure you have authentication otherwise anyone can pirate and steal the game
there is a reason why people pay for platforms to do this stuff for them
Oh I understand but 40% is crazy talk.
But its not like your game cant be stolen/pirated automatically just because its on steam.
Hell there are multiplayer games that are being pirated and steam is being abused to support multiplayer still by utilizing steams default appid (spacewars)
no but if you implement this yourself then you have more things to consider
Is there any way to average out profiler metrices?
Not that I am aware of in the UI but you could easily write an editor script that does this.
oh dang it, it's good for analysing frame drops but oftentimes script take differing times so it's hard to know which one is slow
frame drops usually caused by gc spikes
profile that first, especially if you're having a hard time pinpointing a script thats taking too long to execute
will do, thanks
no problem. are you instantiating or destroying many objects at once in your game? what can happen is you can spawn 200 game objects destroy them but they will persist in memory until the gc does a sweep. Later in the game you might spawn 10 more objects and hit some limit that tells the gc to run and that is when youll get the frame drops.
does anyone know a solution when tiles sometimes have a one pixel gap when the camera is in a certain position?
looks very glitchy
pixel perfect camera
i have tried that but that doesnt feel smooth
camera moves very odd then
Yeah thats one big drawback with pixel perfect camera it restricts smooth movement
Chances are you can fix this with your import settings, is your filter mode on point?
point (no filter)
what about pixels per unit?
ok so your import settings make sense
my temporary solution rn is i made it 31 ppu but it looks a bit odd
You sure its just not low quality art assets?
maybe.. but i think it just happend when i begun the project i didnt have it
what happens if you manually set the resolution in the playmode window
dont touch the zoom just adjust the resolution and leave it where it is then press play
in the camera?
or the pixel perfect camera comp
tbh ive tried everything even ai cant help me
alr i tried it on 1920 x 1080 which it was on which doesnt work and 4k also but i still have it
is your sheet on an atlas?
wdym
Hello everyone βΊοΈ
Yes, with the Profile Analyzer. It's a separate package available in the package manager
HELLPPPPPPPP HELP ME HELPPPPPPPPPPPPP PLSSSSS ME NO SPEAK ENGLISH ME ON MAC BOOK HELP ME PLESSSS
known vscode issue
I'm trying to get to grips with the new Input System Package after initially learning the Input Manager, I'm mostly there with the basics I think, but there is one issue I'm having. I have a Button ActionType that is triggering both on key down and on key release, so each time I press space bar the event happens twice. Does anyone know a solve for this?
how to fix
but ok for mac?
this isnt a platform thing. Its a new C# extension feature thing
ok I will try tanks
AndroidJavaClass intentClass = new("android.content.Intent");
AndroidJavaObject intentObject = new("android.content.Intent");
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_VIEW"));
AndroidJavaClass uriClass = new("android.net.Uri");
AndroidJavaObject fileObject = new("java.io.File", FolderPath);
AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("fromFile", fileObject);
intentObject.Call<AndroidJavaObject>("setDataAndType", uriObject, "resource/folder");
AndroidJavaClass unity = new("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
currentActivity.Call("startActivity", intentObject);
i might need to make a dev version to see the errors
my original question since i asked in wrong channel
ignore the "using", i was testing smth but its not there anymore as i dont need it (edited the message)
With that much JNI id just write this in java and invoke that
i mean yeah but whats wrong with the code π?
Not sure, you want to open a file picker? Did you add the required permissions?
I do remember this stuff changed at some point so dont use an old api
no, just open the file explorer
smth like how u do it here
Application.OpenURL("file:///" + LevelPath);
but on android
android doesnt really do such a thing
Its more complex now and requires extra steps to access files outside of your app https://developer.android.com/training/data-storage
how do I fix this(Doing a 2d game right now)
Input code differs between the built-in Input Manager and the Input System, and changes are required.
why is it so complicated
π
because they tried to move away from apps having full access to all files so its better controlled now
File provider examples
Ill thread the message so it isn't a wall of text
I updated my unity 6.0, and now I am getting errors about packages missing Unity Sentis?
Library\PackageCache\com.unity.ml-agents@2b4ded88494d\Runtime\Academy.cs(11,13): error CS0234: The type or namespace name 'Sentis' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
What even is Sentis?
Sentis was renamed thats probably why.. its a Language Model / neural network engine basically
now is called "Inference Engine"
you can try just deleting the library folder and refresh the project
delete the packages related to it first if you have any
yo guys why isn't the sprite editor showing upp?
Doesn't sound like a code question, try moving the question to #π»βunity-talk
alr
Hi i was trying to make a hand walking system. This script is supposed to track the distance from your hand from the last frame. I was wondering if I needed to declare currentHandPos again on LateUpdate;? I am on my school laptop so im not able to test it right now.
using UnityEngine;
using UnityEngine.InputSystem;
public class MyScript : MonoBehaviour
{
private Vector3 lastHandPosition;
private Vector3 movementSpeed;
private Vector3 handDelta;
private Vector3 currentHandPos;
private Vector3 newPos;
private float distance;
public Rigidbody playerRigidbody; // PUBLIC
private float movementMultiplier = 1.3f; // adjust value to change movement power
// called immediately when the script is loaded or something, before start.
void Awake()
{
}
// called first other than Awake
void Start()
{
}
// Can call at a fixed interval? How can that be useful lol.
void FixedUpdate()
{
}
void Update()
{
lastHandPosition = transform.position; // the current position so it becomes the last position in the next frame
}
void LateUpdate()
{
currentHandPos = transform.position;
distance = Vector3.Distance(currentHandPos, lastHandPosition) / Time.deltaTime;
handDelta = currentHandPos - lastHandPosition;
float movementForce = distance * movementMultiplier;
Vector3 moveDirection = -handDelta.normalized;
if (handDelta.magnitude > 0.01f)
{
playerRigidbody.AddForce(moveDirection * movementForce, ForceMode.VelocityChange);
}
}
}
i would assune LateUpdate(); -> Update();
because Update(); runs every frame, same as LateUpdate();
Both update and late update happen in the same frame, and as the name implies, late one happens later, so your current and last positions are the same in update.
so would is my code basically just redundant
Yes
π
You should put everything in update and set last position at the end of the logic.
Ah, you're moving via physics...
If you're moving via physics you should be doing all of it in fixed update
Howdy yall!
right but I wanted to get the current frame and then when that frame passes it gets the hand position of the frame how would i do that without Update(); and LateUpdate();
CurrentHandPos -> NextFrameHandPos // then of course you just subtract them to find the total then apply the velocity
now im at a halt and i dont see how can i use fixedupdate. it seems useless since it can only update at a fixed interval. How can I get the current frame then save it, and then get the the next frame?
i was thinking of using a float then saving it
Thank you! You helped me alot and I know what I need to do now. I will move all of my code to Update(); instead of FixedUpdate(); because sometimes the force being applied will be delayed and for a highly physicsal game I will be needing all of the optimization. Thanks!
I do have one question, would FixedUpdate(); be better at physics? If so can I just set the Interval to 1. So its better at physics and moving at the same time as Update();?
for a multiplayer online game, how can I tell the host to spawn objects from the client? Or is there a way to enable distributed authority?
I have heard FixedUpdate(); is speficly ment for physics
-# im not entirely sure, theres people with more knollage for sure
Did not fix it
make sure you've also updated all packages
Sorta.
Yes, FixedUpdate runs on the physics execution time (runs a lot less often).
Most of the time just multiplying what you are doing by Time.deltaTime and doing it in Update is fine. It makes non-physics changes smooth, allows for input to be processed properly on the frame it starts/ends, etc.
Most physics operations are also fine to execute from Update as they are applied on the next FixedUpdate anyway (with a couple gatchas). But there are some scenarios where running it in the physics loop is important.
It's just rarely needed in practice and mostly misused (imho).
Yes, FixedUpdate is used for moving an object via physics . . .
lets you access input faster
this is not quite true. input is just framebound, they're updated per frame, so they should be read per frame - otherwise you're skipping data
If you are checking input in FixedUpdate, it could check it 4 or 5 frames after the visual is processed.
And the input state may have changed
I.e. missing presses and releases
exactly. it's not "getting input faster", it's getting input correctly
Ok, I reworded it, for what little point it is worth
fwiw i feel like it's kinda misleading to say you should just do everything in Update
rigidbodies have interpolation to make them not jittery even as they actually update in the fixed timestep
So tell them to do something else
things that are bound to the fixed timestep, ie most physics stuff that isn't just an assignment, should be done in the fixed timestep
If you have a practical reason you suggest they use fixedupdate, my suggestion is to tell em.
randomunityencounter already gave a sufficient answer tbh
i'm specifically telling you that your advice is misleading
Ok π
Here is a resource for you to understand what people are discussing
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
doing ld58 rn, and im having trouble getting a rotation working, i have two vector3 world positions, and im trying to rotate an object on its local X axis to line up with the positions, feel like ive tried everything
.localRotation may help
is there a way to capture a windows desktop screen and duplicate it inside of unity ? i cant seem to have any luck finding something similar online, other than a couple of japaense libraries
In what sense? As in a live capture so if they move the mouse on desktop it moves in the editor or in game
For that your best bet is to look into C# and .Net libraries, unity itself wouldn't handle it since it's likely a system method
What do you mean about line up? Like copying one to another, looking at, or something therein?
align, match the rotation of the direction of the two points
This may work in a pinch
https://github.com/hecomi/uWindowCapture
thats one of the japanese libraries i came across. i did some digging and i found the creator discussing it in a forum and according to him the performance was unsatisfactory so he didnt work on it further. Idk should i still try it ?
i came across this a few minutes ago
Quaternion.LookRotation might be what you are looking for.
and thank you so much for replying to my message ππ
That looks promising, plus, there is source code for the DLL, so if it works you can modify it later if needed. I'd definitely give both of those a try
Hmmm oke doki. Iβll get on it as soon as i get back from uni π«‘
Literally Google it. It's a .net library and you save it to bitmap which is used for things where the image can change
i saw it, the windows graphics capture thing. i didnt see anyone using it so i was hesitant i thought if it was any food iβd see it pop up somewhere
People don't use it because they don't understand it or think it won't work, the best way to do any screen capture is the way the Developer of the code wrote... Any hack around will not be as good or flexible
I find it infurating that Unity won't change things like their stupid custom null equality check for "backwards compatability" but then do stuff like this.
Changing the null check equality would be insane
No it would be the smart thing to do, they even said they could have done it.
Because then you would fallow actual standards for the language instead of making up stupid stuff
?= doesn't work because of their stupidity
What is insane is that I have lost 2 days fixing my project because they wanted to change thier ML package name
ok
hmm, fair point. Iβll try it. Thank you so much πππ
due diligence when upgrading a project into another version...& version control before any upgrades is a must
Alongside a backup before and after the upgrade
that's what the version control is for. just revert to the previous version if updating broke things
how are multiplayer games on steam preventing people from stealing accounts if steam ids can be spoofed. I am not using steam just wondering what auth options we have
In theory, many authentication options, such as the whole Google play etc.. but a steamID isn't necessarily there to be a level of security, more a entry in a large database
Agreed I have those
I did, but I have to upgrade because of the security issues, so it is either now or later.
Server can validate sessions with Steam https://partner.steamgames.com/doc/features/auth
https://gist.github.com/krzys-h/76c518be0516fb1e94c7efbdcd028830#file-saverendertexturetofile-cs-L21
im using this script to save the render texture, but the result saved texture keep being set to 512 no matter what i do, is there any way i fix this
I thought this would've gotten every gameobject without tags, but it's giving me a null error instead.
i want to grab every gameobject that doesn't contain any tags.
GameObject[] AllNonetags = GameObject.FindGameObjectsWithTag(null);
i'm guessing getting the scene might be a better idea
as im reading all gameobjects have a tag.. and when they dont have a tag the default is "Untagged" probably thats the problem you cant find all obejcts with "null" ^^
Ooh! i didn't think of that.
I'll test it out although i already wrote a scene manager get all root parts script.
guys help plssssssssss
the vs code bug strikes again!
the obj folder should be deleted. update vs code and the visual studio package in project.
how do I do that I need more detail
All assets for your project are in Assets/. Delete the "obj" folder in Assets/.
Update vs code if there is an update as its c# extension is making these files incorrectly.
do I update vs code by deleting and downloading?
Cannot update while running on a read-only volume. The application is on a read-only volume. Please move the application and try again. If you're on macOS Sierra or later, you'll need to move the application out of the Downloads directory. This might mean the application was put on quarantine by macOS. See this link for more information.
what the
no fuckin idea π
delete the obj folder for now and I believe there is a setting in the c# extension you can disable to prevent it happening again
hey, so ive been touching on interfaces, now it doesnt go through walls if u were here last time. but how do i get the name of the interface object?
ah, nevermind just remembered hitinfo is a thing π
yea I think it worked
Great. vs code spat out some files that unity cant compile hence the issues. Delete it again if it happens more
alright thanks
If you mean c# interfaces, you can still cast to MonoBehaviour and get the gameobject and name.
Or you can add a property to your interface that we know all monos already implement:
public GameObject gameObject {get;}
nah, its all good i got it working
so if im doing it this method how would i get the object from a raycast?
would it be better to use hitInfo or the interface to get the object?
Get it from hitInfo because its easily accessable without a cast
ok
as you see you already access the gameobject
get the gameobject once and store in a var
prob would be smarter
You can like I said but we can avoid doing that in this context
Its best to avoid repeated accesses with unity properties as many go to native code
But if you need to elsewhere you can do:
GameObject g = ((MonoBehaviour)interactable).gameObject;
In the context shown above you dont
u may have answered this b4 idk but what one is better?
so like how a raycast points out, i want a sphere to be at the end of said raycast checking for an object in the general area, so that the player wont have to look at the object exactly to pick it up
A raycast can be first used to look for an interactable, if not then if you hit the floor/some surface you can sphere cast there to find something close by.
So I'm using VS code but for some reason it doesn't identify errors. How do I enable that feature?
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
^ make sure you have things setup correctly
Thank you
so, my interaction does work. but it wont interact with some parts of the object
like say my door for example, it works on the upper half but not the bottom half?
is the box collider covering the entire door?
easy enough debug the raycast hit and see what it says when u hover the bottom half
Give the interface a GameObject property . . .
guys, who's free rn?
yes
Don't ask to ask, just ask . . .
okay
could the raycast be hitting the player?
uhm, dunno if u just read that or if ur just ignoring the rest, but i solved it :3
maybe, actually
how would i stop that?
raycast has a layer mask parameter
Yeah, I'm reading all the new posts from this morning . . .
yes but the reason i decided not to use it, is because it would go through walls if i used it
i have this problem. if sonic stands on the joint of the platforms, he shakes like in the video. how to prevent this type of shaking? if you need the code, i'll send it
please
just fix the ground, when the character leans down it goes straight onto the flat surface, making it flat again
then it loops
it appears its trying to angle b/c of something
and then trying to stay upright b/c of something else..
u have two ground/check thingies affecting it at once
okay, thanks, i'll try
well it depends looks like he has two rays far away from each other
even if the ground is conncted.. if hes standing on the edge like that (1) is gonna have 1 normal and the other has another normal..
yes, they're finding the right angle
u could blend them.. or have 1 take priority
hmmm i notice that now
why are you using 2?
actually it is
green one says slant to match the ramp
the red one says nah bitch u standing upright
i have the priority
why not just use 1 and put it in the middle
^ that would be the easiest solution
just check what floor your on then change to that angle
or u could take both of em abnd blend them togther.. so it tilts halfway between both of em
no it wouldn't if you just make it ignore the player layer
well, it works like red, ur distance is shorter than mine, ur main
ahh okay
yes, how do i do that?
make a player layer
would i put a layermask but put a ~ before it?
just assign it in the inspector
just select all the layers u want to detect but the player layer
easier that way than inversing the whole mask
just in future, how to prevent this shakin. i checked the other engines and they has this shake prevent system, idk how does it works...
alright, i understand it
elaborate on the shaking?
its his tilt player to match ground normal
he just has (2) of em working together.. w/ different normals causing it to jitter
so if he goes down then up again its gonna cause the camera to shake
i think if u lerp the camera it may work
or slerp
either one
if there are 2 normals and distances of these visors is the same, it will take the average angle
slerp is more linear where as lerp will slow then speed then slow back down again
or just use the slope from the two hit points
i dont think it is
because i did the layermask and it still wont select the top half
maybe you forgot to put the player on the player layer
if not, then debug what the raycast hits then
or maybe you forgot to add the layer mask to the raycast
this is what it might look like if u used the average of all the raycast normals
@echo copper
i dont think i forgot anything
i believe you forgot to debug to see if the raycast is hitting something else
if not, then debug what the raycast hits then
#π»βcode-beginner message
u should debug all the hits while ur testing anyway
im doing the debug now
it will reveal whats blocking it
making a debug cooldown so it doesnt print something every frame
making it wait 0.5s before firing
well, the other engine has the same problem, but sonic isn't shaking. maybe just the sprite interpolates somehow. well, mb the engine detects these shakings. how to do it?
wait am i an idiot or am i an idiot?
i feel like im missing something
ive done cooldowns many times before but, i cant remeber whats wrong here
using System.Collections
brih
It used to be part of the default template but was removed in Unity 6
Since more cases don't need it than do
thanks, didnt realise
it was clearly telling me but i swore it was alr there
@cosmic quail
i firgured it out
feel like an idiot
its the triggers that are in front of the door that tell it what way to open :p
gotta exclude those from the layer mask too π
its working now
one last problem though, that i need to fix
wait
no
i remeber now, it would only disable the door interact ui, not the text itself π
sometimes i just create the problems in my head and dont read my own spaghetti code π
meh, thats how most of us learn the best π
being told not to do something a particular way doesn't hit as hard as
actually doing something the wrong way and realizing it urself later on π
Is it just me or does declaring an array as public cause lots of errors and warnings in the inspector using unity 6000.0.58f2
its just .58f2 as well as a couple others ive seen...
public class s1 : MonoBehaviour
{
public Transform[] transforms;
public Vector3[] positions;
public Color[] colors;
[SerializeField] private Transform[] serializedTransforms;
[SerializeField] private Vector3[] serializedPositions;
[SerializeField] private Color[] serializedColors;
}
β the editors are bugged out pretty bad..
π (reset ur layout as a work-a-round)
Classic unity
yup, jank for now
It works!!
just to take a few nice long slow breaths before compiling π€£
this editor is bout testing patience ;D
I'd assume it would take them about a week or 2 to iron out the quirks
Till then this should do
lets hope π€ that security thing has em probably running around like chickens w/ their heads cut off
I am using WASMTime as a scripting runtime for my game. It will allow players to mod the game and create custom scripts while staying sandbox. The library is multiplatform but I am unsure how the folder structure works for unity, how do I lay out the folder structure for a native plugin to support osx, windows and linux?
https://paste.myst.rs/9g8k6a6g
heres a little editor script I just wrote that makes it a Hotkey
just save the script to a folder called Editor that way it doesn't get built or anything
then you can simply press Shift + F5 to reset the layout quickly
what was the security vulnerability anyways?
no clue.. some potential back door or something
https://unity.com/security/sept-2025-01 heres all the info
Seems odd to me tbh, we aren't sandboxed with the code we can execute so idk what the ramifications of it could be
no one's exploited it yet.. but thats why they went thru the trouble of notifying everyone..
update as soon as u can.. and if you've built with any of those versions and its possible might want to port it over to a different version and re-release
are susceptible to an unsafe file loading and local file inclusion attack depending on the operating system, which could enable local code execution or information disclosure at the privilege level of the vulnerable application
so essentially if someone has a virus on their pc and my game installed the virus could exploit the bug in my game to execute code?
thats all i really know
im in the process of moving everything over to 6000.0.58f2
but seeing lots of people with editor / visual bugs with that version
soo i really don't know what im going to do... just wait and see for a while i guess
Honestly im just going to stay on my current version until they iron out the issues.
im not totally sure but that sounds reasonable to suspect
If someone already has a virus on their pc their cooked anyways
ya, i don't think it means Unity will give u a virus.. but yea
like ur saying.. if u already have one it may make it worse
just don't go downloading so much π½ until its fixed π€ͺ
steam fixed it so if you upload your game there then it's patched anyways
steam did not patch the games. steam is only blocking the command line parameters only if the game is actually launched through the steam client
Hey, guys! I am making a camera-based crouching system. For one reason, my camera when I am pressing C button to crouch, it does tiny movements until the camera reaches the crouch height. I am not sure why. Also, another issue is that with my Update Camera Position By State method on Update() method the camera is falling down at the beginning of the game. Could you please review my code and see what is happening because I stuck?
A tool for sharing your source code with the world!
what does that means?
you overflowed ur stack π
void InfiniteLoop(){
InfiniteLoop();
}```
check for Recursive update calls, coroutines calling themselves, or nested property getters
If i read it right, there are 4 risks, the main one being an exploit to essentially let someone load a DLL to your game and execute something in it. Most likely someone installs a free game, it checks everything on the system to find exploitable games, and sits on the info a while.
From there its a lot more open what they can do with an exploited version (download a Trojan through your game for example). But its not exactly an easy thing to exploit. And 95% of games will end up not patched anyway.
What steam and others is doing is blocking the URI command to launch the game with the request to load the DLL. It can't stop something from running windows command line to do it.
At least, from what little I've read, that seems to be the risk.
where do i go for UI help?
It seems quite convoluted to me as a risk, versus the bad app from just infecting the system directly. But the disguise is what they are mostly worried about
Idk maybe i have no idea about how security works but I dont see how this is any issues. If someone downloads a unity game and wants to exploit this put a trojan the only pc at risk is his own. This exploit doesn't give him the ability to just infect everyone who has downloaded the game.
Yeah exactly. Like there is a very very distant possibility (if you say have user generated content, and they really work hard on it, they could exploit that). But thats more of a mass user adoption game sized concern
I mean even then user generated content should be being executed through a sandbox that should stop this from happening anyways.
I am actually as we speak embedding the webassembly runtime into unity so users can create/share scripts with each other without executing any malicious code.
Will allow users to create scripts in any language that can compile to wasm and be secure in knowing someone elses mods cant do anything fishy
Pretty much. Yeah, that's what the exploit is trying to circumvent. In theory it lets the data be accessed by their own code outside of the developer and engines normal sandbox
But its still restricted to the permissions the game has
Any games allowing mods through c# reflection are going to be the ones that have the hugest risks
but yeah I guess this is only a problem for games with user created content
vr chat probably scrambling right now
Plus, they will need an intimate knowledge of your code base to figure out how to exploit it in most cases. So security by obscurity for most small devs.
Yeah i can definitely see it being a risk for vrchat
But we won't know for sure until someone actually exploits it. People are crazy innovative π
i'd rather have the exploit than my editor being incapable of drawing correctly half the time..
#firstworldproblems
Haha true, or not knowing what the patched executables breaking
Not 100% sure if this falls under beginner or not, but anyway... I'm making a survival horror / FPS game and I'm tackling enemy AI. They can see and hear the player to find them, but I'm wondering about smell.
If I made an invisible particle system that trailed behind the player, could I have the AI interact with / follow the trail of particles? TIA
(Any guides, videos, etc. are appreciated!)
One ugly solution, is the particle systems can have physics attached. So you could actually have them hit colliders as a way of sensing smell
So yeah, you could use a trail of particles
And, that way, you could also make the smell "visible" at some point in the game
Solid, thanks lloyd!
I've js finished the rollaball course
what course should I start now?
now you should take the concepts you learned in that course and create a full game out of it and release it on the app store of your choice
the course taught nothing other than simple movement input, UI and some ai navigation what are you talking about.
how can I create a game out of that?
yo hello guys, how do I choose the gpu that my unity engine uses to run, rn its running the games in the editor on my cpu
my perfomance is terrible
create a game about a basket ball trying to find its way home idfk but there are 10,000,000 games on the app store that contain very little additional coding than whats taught in that course
why is my game doing this?
and how can you prove that?
maybe you have the camera as a child to the player?
am I not supposed to?
was following this guy's tutorial and that's what he was doing
alright
https://www.tiktok.com/@karlinhaa_games/video/7282533708660329733
https://play.google.com/store/apps/details?id=com.dino.rolling.skyball.balance&hl=en_US
There is two one has over 50 million downloads
If you have your camera as a child then it's transform and rotation will be updated with the player
and you're also updating it's rotation via mouse move input
explaining the messed up movement and rotation
@true pine before doing what I recommend
make the function in the code of movement from void update to void lateupdate
and see if it works
hang on would it help if I sent my actual code
yes that one has even more stuff than the course even showed
I have pastebins for the mouse and movement scripts
I don't know much about code, but I know a lot of concepts and HOW to make them, just not HOW to code them
yes and taking courses are not going to teach you how to code. Take the concepts from your entry into the engine and try to expand it on your own without following a video
whatever
bro please how can i choose the gpu that my unity engine runs, its using my cpu right now
I have the opposite problem; I can code but I'm just not well-versed in concepts
take a problem
turn it into multiple little problems
and then fix every little problem
maybe I didn't word that correctly
anyone know the helper team here, i want to get my stuff fixed
I'm not good at expressing what I'm talking about
is your monitor plugged into your gpu? this definitely isn't a question for the coding channel.
laptop with dedicated nvidia graphics, i have set nvidia control panel to default my system to use the gpu tho
ok so, that didn't really do anything
it's really weird what's happening
oh, sry I couldn't be of help in some way
if I spam wasd while moving my mouse it freaks tf out, but then it just magically works normally for a few seconds
a few seconds?
I don't get it either