#💻┃code-beginner
1 messages · Page 810 of 1
thats what im asking, i dont know where to start
(that was in reply to buddy)
mb
btw on that "limit diagonal running", you generally would not have to do that, just normalize or clampvelocity on the input and then limit the overall magnitude of the speed
yeah
well i cant use vector3.clampmagnitude becuase that would also affect the y axis
but yeah its a little rough around the edges ill clean it up a bit
you can clamp magnitude on the input before applying it to the rb
i know..
are you sure the loss of momentum is due to CounterMovement?
nothing there changes when you hit the ground
it might be, its hard to tell
i feel like it's just due to ground friction
because when i dont have if(grounded) return; the player accelerates so fast in air to the point where i think it just negates the halting
ill try attaching a physics material with 0 friction
that doesn't really make sense, if you had/removed that then nothing would change when you're in the air
counter movement
yeah
what about it
im realising now i forgot to do it lol
In what way? Like it decelerates instead of abruptly stopping?
adding or removing if (grounded) return; affects the behavior on the ground. it wouldn't change the behavior in the air, assuming the grounded check was written properly
like at the start of CounterMovement() i would have if(grounded) return; then it wouldnt counter movement in air
Lerp
that's not what that statement says
it just doesnt stop the player
wdym
it helps but its still there
@frigid lark have you read this
(might want to consider noting down where you left off and taking a break then)
nah its just school i havent actually been doing much gamedev today. about 30mins-1hr
maybe its the extra gravity
because if im constantly applying a downward force then its going to try and push me into the ground
and maybe thats stopping it
shouldn't affect anything with no friction
does the loss of momentum happen if you just comment out the CounterMovement call entirely?
checking
yeah it does
but then i slip and slide like a penguini
and increasing friction would just reintroduce the problem, would it not?
oh yeah this wasn't a solution, just a check to see if CounterMovement was the cause
and, well, clearly not
private float previous;```
It's implied as Time.time returns a float.
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Time-time.html
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi all, I'm having a bit of a brainfart.
if (GameManager.Instance.globalDataManager.closestStargate.GetComponentInParent<GroundTileDataContainer>().groundTileBiomeData.canShowFootprints == true)
{
GameObject newFootstep = footprintPool.GetPooledObject();
newFootstep.transform.position = new Vector3(
transform.position.x,
0.01f,
transform.position.z);
newFootstep.transform.rotation = Quaternion.Euler(
0,
playerGameObject.transform.rotation.y,
0);
newFootstep.SetActive(true);
Debug.Log("Should be Footprint");
StartCoroutine(DisableFootstep(newFootstep));
}
I'm grabbing some footprints from my pool and they're working great, except for the rotation, I can't seem to figure it out (they always enable with a Y rotation of 0. Can anyone see where I'm going wrong please? 😕
Hello. Im new to Unity 6.3, and I faced this kind of problem.
error CS0246: The type or namespace name 'MaterialReferenceChanger' could not be found (are you missing a using directive or an assembly reference?)
How do i fix this? I did try to find the solution through YT, Google and Grok AI, but I still don't understand.
playerGameObject.transform.rotation.y very likely isn't what you're wanting. That value is a quaternion value, not the euler y rotation value.
Can you show the console error? (stacktrace included)
If you want your player's rotation , you can use the euler angle value:cs newFootstep.transform.rotation = Quaternion.Euler(0, playerGameObject.transform.eulerAngles.y, 0);@ruby python
Ah yeah. Told ya, brainfart. lol.
internal MaterialReferenceChanger m_MaterialReferenceChanger;
public override void OnPreRun()
{
m_MaterialReferenceChanger = new MaterialReferenceChanger();
}
the very first line, but i could not find the error.
I want to see the console window to better evaluate the stack and error.
wait
To open the Console, from Unity’s main menu go to Window > General > Console.
Try restarting the Unity Editor. It may be a false positive.
How?
Close the Unity Editor application and launch the project again from the Unity Hub.
You mean delete the 6.3 editor and install back?
No. Close the Unity Editor. Then open the project again from your Unity Hub.
Ok
Hi guys I got a problem, when I run my 2D game. I think there should be way to disable unity short controls, when code running like control + p (stop running), because in my game parry is leftControl and attack "p". Thank you for help!
Well, i still faced the same problem.
Close Unity, remove the package cache folder of that specific package and start the project again
Wait, is there another way to deal with this?
Why would you avoid the way I suggested? its just deleting a packagecache thats being regenerated the next time you start unity
If I want an object to strafe left and right in a smooth manner, what are my options ? I'm looking at Vector3.MoveTowards but it needs to be in an update apparently. Can I do a movement by trasform outside the update ?
Update is just a loop thats being called every frame by Unitys game loop. You can do whatever you want to transform.position whenever you want, it just has to be called by someone somewhere. Update is just the convenient way to keep things "running"
What I'm trying to do is : I have the input reference action for movement (left and right arrows), I put an event on action.performed and from that I want to do a smooth movement to a fixed position, like go from x = 0 to x = 3
then you want your transform.position to "follow" your targetvector and only update the targetvector in your performed event
so to make it smooth, transform.position = vector3.lerp or whatever you want to smooth in update and in your callback method, update the actual targetvector
I think I understand. The event just set a target and the update follow it
Ok
Hey, so I have a character controller. Currently, I use rigidbody's drag float to increase drag while the character is grounded. unfortunately this is causing issues with my dash feature. The dash feature is meant to set the drag do zero while dashing (which it does) but for some reason if I set grounded drag to 0 instead, the dash is much cleaner.
Basically my question is, is there a better way than creating counter force or increasing rigidbody drag while grounded to give a tighter less floaty physics based movement controller?
Hi I'm trying to understand the new unity Input system I'm Following the Unity Input System in Unity 6 (2/7): Input System Scripting Video and im trying to understand something We used to use The X and Z axis for movement in vector 3 but now we use Y axis in a vector 2 from the action maps. Doesn't Y normally refer to Up in the world?
Dashing sounds to me like it should not be "dragged influenced", or? So setting it to 0 while dashing and resetting when done dashing sounds valid to me.
y axis is also up on screen position probably? Not sure, what the input tutorial is currently covering. Can you show some code?
yeah, that's what I have currently. I must have messed it up though. I see in the inspector it does set drag to 0 on the rigidbody when I dash. but dash works so much better mid air where the drag is set to 1 than on land where it's set to 8 despite the fact that drag should be set to 0 while dashing and that seems to actually be the case too. Hmm maybe it's some sort of string tension thing because I made my capsule controller hover with spring force...
remember all a vector2 and vector3 really are is just a little group of numbers, they can be used however they want
in this case your mouse (or joystick) goes horizontal and vertical, so in code its stored in a Vector2, which is the x and y
oh so instead of using just the x and z we now use the x and y to take account of controllers?
and y refers to w and s
can you show your code eventually? Like where do you set the drag to 0 and where are you dashing?
pretty much yeah
what x, y and z "mean" is defined on how those values are being used in the given situation
they don't have an overarching definition that spans every usecase
commonly used: x,y = left/right, up/down (in input case)
eg. you might use a Vector2 to conveniently store a minimum and maximum value, which would be using x and y
purely because its nice to store them as a pair of two numbers
...Uh...I...yeah...this sucks lmao
guess you found the issue 😉
ah i see thank you makes alot more sense
Hmm I have an issue... i'm trying to make strafe movements in a sort of rigid way, and I'm using fixed value for that. Like I consider my starting point to be (0,1,0) and I want to move in (3,1,0). The issue is I also want to jump so I ut a rigid body, but now my position is weird, I don't have clean values like 0 or 3
are you probably mixing up rigidbody and transform.position? If you use physics, you cant simply use transform.position, which acts like a teleportation from vectorA to vectorB
Well the game is supposed to be a kind of infinite runner. I have a character that can strafe on three "roads" and jump. I thought that transform.position to move left and right would fit. Since I need to just go from one point to the other
But when you use transform.position, you are basically skipping physics update till the next frame. so you might miss collisions and whatever rigidbody provides
That's indeed an issue
you might wanna look into Rigidbody.MovePosition
in a fixed update right ?
read the docs 😉
Now that I think about it I can see a problem arising. The character is supposed to be able to fly also... I fear the time when I'll have to deal with that and gravity
or maybe I can disable gravity when I fly?
you can disable gravity, you can set velocity directly. many ways to achieve this, depending on your game mechanics and setup
can anyone tell me the best place to learn coding for games... like i dont want any of that 'hello world' starter bs
i want coding which will be for games mainly for 3D
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ok basic movement done. I just need to make an imput buffer for more smoothness in the controls
I'm thinking about how to make an input buffer. My thought so far is to save the command the player enter, create a list of command that is limited in size (like two or three inputs at a time) and then in the update, if you're available to do an action, you pick the first entry and do that.
Am I right ?
i don't think you need a buffer
it might create more problems that it solves
hi would Vector3.Reflect() work for something like a projectile parry?
or is there some better way of implementing that?
as in you block the projectile and it is reflected off the shield/block?
ya
no just add an acceleration vector
How do I set up adaptive ui, my ui is messed up for some devices, pls help
ye
I made a simple one, it just records the last command and plays it when possible
yeah, that's bad
Helps with the controls
How so ?
well, let's say you are still in air
why even have the rigidbody on there if you're not gonna ue it
and press jump
well, then you would jump when you land even if you now don't want to
if you want to use a buffer, then maybe make the command inside expire after 1s or 0.5s
If I'm flying and hit jump it won't do anything. I would need to press "down" then during the time I'm lowering, press jump
gotta be ragebait
still, make the buffer expire after 1s or 0.5s
what's actually the difference between Physics.OverlapSphere and Physics.OverlapSphereNonAlloc?
what im doing wrong. cant find. ```Action<InputAction.CallbackContext> _action;
void ActivateRuneInput()
{
_action = ctx => HandleRuneSlotInput(0);
runeSlotInputs[0].action.performed += _action;
}
void OnDestroy()
{
runeSlotInputs[0].action.performed -= _action;
}
we need more info...
we are not mind readers
okay. trying to sub to function with ActionRef
maybe this helps?
tho i think it's what you are doing, hmm
are you sure the subscribe function is getting called?
- It subs, but doesnt calls function
- It doesnt Unsub
are you destroying the object?
yes. im 1000% sure
i know that it gets destroyed. i have done it million timess
bc if it subscribes, then 100% it's caling that function
i mean, check if OnDestroy is getting called
same for the action
add another function to the subscribed ones
where it's just a debug
to check if the action is actually getting performed
Action, performed.
Function not called.
OnDestroy called
ok that's strange
private void OnRunePerformed(InputAction.CallbackContext ctx)
{
HandleRuneSlotInput(0);
}
void ActivateRuneInput()
{
runeSlotInputs[0].action.performed += OnRunePerformed;
}
void OnDestroy()
{
runeSlotInputs[0].action.performed -= OnRunePerformed;
}
try this
did it work?
no
its too long to send
send the file
[SerializeField] InputActionReference[] runeSlotInputs = new InputActionReference[10];
int selectedSlotIndex = 0;
List<BlockType> blockTypesOrder = new List<BlockType>(); // To store the order of block types
EventSystem eventSystem;
Action<InputAction.CallbackContext> _action;
void ActivateRuneInput()
{
runeSlotInputs[0].action.performed += OnRunePerformed;
}
void OnDestroy()
{
runeSlotInputs[0].action.performed -= OnRunePerformed;
BlockSlot.OnSlotClicked -= HandleSlotClicked;
if (LoadoutList == null || LoadoutList.Count == 0)
{
Debug.LogWarning("LoadoutList is not initialized or empty. Skipping SaveLoadoutList.");
return;
}
SaveLoadoutList();
}
void HandleSlotClicked(int slotIndex)
{
selectedSlotIndex = slotIndex;
}
private void OnRunePerformed(InputAction.CallbackContext ctx)
{
HandleRuneSlotInput(0);
}
void HandleRuneSlotInput(int index)
{
//For setting selectedIndex to clicked slot.
BlockSlot selectedObject = EventSystem.current.currentSelectedGameObject.GetComponent<BlockSlot>();
if(selectedObject)
{
selectedSlotIndex = LoadoutList.FindIndex(slot => slot == selectedObject);
}
else return;
Debug.Log($"Index: {index}, Selected Slot Index: {selectedSlotIndex}");
LoadoutList[selectedSlotIndex].SetRune(blockTypesOrder[index]);
selectedSlotIndex = (++selectedSlotIndex) % LoadoutList.Count;
//Sets selected slot
if (eventSystem != null)
{
var baseEventData = new BaseEventData(eventSystem);
eventSystem.SetSelectedGameObject(LoadoutList[selectedSlotIndex].gameObject, baseEventData);
}
}```
took all related functions and variables
did you actually enable the action?
void OnEnable()
{
if (runeSlotInputs[0]?.action != null)
{
runeSlotInputs[0].action.Enable();
runeSlotInputs[0].action.performed += OnRunePerformed;
}
BlockSlot.OnSlotClicked += HandleSlotClicked;
}
void OnDisable()
{
if (runeSlotInputs[0]?.action != null)
{
runeSlotInputs[0].action.performed -= OnRunePerformed;
runeSlotInputs[0].action.Disable();
}
BlockSlot.OnSlotClicked -= HandleSlotClicked;
}
instead of OnDestroy and your function
tho you can keep using those if you want
lol worked. now i have to make for loop to enable certain count of actions
guys can u guys help i dont understand the curly bracket thingys
so, i got stuck. private void OnRunePerformed(InputAction.CallbackContext ctx, int i) { HandleRuneSlotInput(i); }how do you give it extra values? Or i have to create for each action its own function
you don't do it like this
the curly brackets are really confusing
what about them don't you understand?
also braces are used in quite a few ways to mean roughly the same thing, might want to get more specific
they are not?
python user?
prob
Is this a troll post?..
or lua
i mean i could totally see this being about properties but not describing it well, i'm giving them the benefit of the doubt
so how are you doing it. its somthing like inventory selection
i think you can now go back to your old method
for (int i = 0; i < runeSlotInputs.Length; i++)
{
var actionRef = runeSlotInputs[i];
if (actionRef?.action == null) continue;
int index = i; // Capture current i
_runeActions[i] = ctx => HandleRuneSlotInput(index);
actionRef.action.performed += _runeActions[i];
actionRef.action.Enable();
}
to subscribe
for (int i = 0; i < runeSlotInputs.Length; i++)
{
var actionRef = runeSlotInputs[i];
if (actionRef?.action == null || _runeActions[i] == null) continue;
actionRef.action.performed -= _runeActions[i];
actionRef.action.Disable();
}
to unsubscribe
nah its alr i fixed it
what was confusing about curly brackets btw
it js made no sense about where which one would go
btw where can i find designers
wdym designers...
i js mixed them up
game asset designers
ppl?
yes
!collab prob
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
tho don't expect them to work for free
huuh, well, gl then
paypal is not the only method btw
(it's also the worst, but let's not go down that rabbit hole)
ok
Can I get help from a good developer?
You need to ask a question first
idk if this is the right place to ask but i need help learning how to script
There are pinned resources in this channel.
!learn is a good place to start for general Unity/coding for beginners.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thank you
this is probably a "try it and see" but if i wanna cast a ienumerable like this can i do it like this directly or do i need to make a new one and add a casted version of each element
public void AddListener(Action<IEnumerable<T>> action)
{
MultiColumn.selectionChanged += (e) => action.Invoke(e as IEnumerable<T>);
}
oh do i just pop a linq cast?
i believe so, because it's an interface, i think? and if it were a concrete type then you couldn't do this
IEnumerable<string> and IEnumerable<object> are related, but List<string> and List<object> are not - at least as far as i understand (which may well be wrong)
Rubber ducked myself, the code snippet doesn't work in the sense that the casted ienumerable is valid but the contents seem to be wiped
Linq's .Cast<T> just works
ty
I guess this is more of a c# question than Unity but is there a standard convention to mark in a DateTime (or equivalent) that a part of the date is unknown / invalid? or do i need my own solution for this
i have stuff where some things have a fully known date (eg. 05/09/2014) but also things that only have a partial (eg. ??/04/2012)
the canonical way to store datetimes are either unix or iso 8601 timestamps, so i guess you could technically use the latter but you'd have to process a lot yourself
so this probably would not be a built-in thing
scary words, fair enough thanks
dont mind cooking something up was just curious what the proper route was 😄 ty again
there are some libraries for this you could also use
let me see if i can find the one im thinking off
you would need to make your own data type
or use a separate "mask"
nahh its not that deep it's all good! thank you though
for marking which parts are known/unknown
(which is essentially a custom data type)_
that's probably the best way tbh - the mask
this is on a project to learn ui toolkit so a custom data type is a good excuse to learn how to make a nice drawer for it
i made a movement script and a 1st person camera controller script, but for some reason when im moving and turning my camera at the same time, its very jittery, any ideas how to fix this?
make sure your camera code is in lateupdate and if your character is a rigidbody make sure it has interpolation enabled
and make sure you aren't modifying the transform of an object that has an rb
i have both of those and it still is jittery
thats exactly what im doing, do i have to just remake the code?
yes
change the linearvelocity instead
or use addforce, that works too i guess
both of those work with the new unity input system right?
yes
alright thanks
they are completely separate from the input system
ah okay
what is the line to switch scenes?
Google Unity SceneManager
There's no one "line". All the methods to load scenes are in that class though
Assets\Scripts\MenuLogicScript.cs(1,19): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
using UnityEngine.SceneManagement;
public class MenuLogicScript : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void SwitchScenes()
{
SceneManager.LoadScene(1);
}
public void Exit()
{
Application.Quit();
}
}
if the error is coming from that code then you haven't saved it after making the change from UnityEditor to UnityEngine
I did
and the code works
that error only appears when i try to build
then you are looking in the wrong file
or you've copied everything after the first line since the error appears on line 1
yea I had the same using UnityEngine.SceneManagement; twice
I removed it before I sent it
are you sure the first one wasn't the UnityEditor.SceneManagement line? because that one would be the exact one that was causing the error since the editor assembly doesn't exist in a build
I dont really remember
and for future reference, do not modify the code when sending it when you are experiencing errors
Ima save and try to build again
If you did, that would have been the error
it works now
So, you almost certainly had both, and when you removed the "duplicate" by posting it here you actually fixed the error
thanks yall ❤️
yes
🙂
Can we get Unity documentation as PDF?
Hello! Super noob here, how come my VS code isn't autofilling? In the tutorial for essentials, I'm on the step where we have to add the OnTriggerEnter.
When I start to Type On, that option doesn't appear.
I have C# and C# Dev Kit entension installed
!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
can anyone help with this? for some reason my vscode randomly decided to stop showing syntax highlighting for unity and its really inconvenient (since im new and it gives you descriptions of what each field does)
ive tried regenerating project files, checking for vscode updates and reinstalling the unity extension on vscode
(if you wait a bit into the video you can see that it initially knows what to highlight then decides to not do it)
check the bot message right above
It would be nice if you can show that each setup has been properly set. Other than that Visual Studio Code mentions something about dotNet version.
Heyy SUPER new noob question. I'm trying to learn about different joints and I'm watching a youtube tutorial for it. In the video the guy sets up a fixed joint with one cube connecting to another one. With the fixed joint, he's able to grab and drag one of the cubes to make them both move.
When I added the fixed joint, I am not able to make the both move, but when I got to play mode I can see the cubes fixed and hovering. How is he able to make these physics active while in Scene view?
Thank you!
Hey everyone. I have a homing projectile in my scene that is supposed to fly to my player
Vector2 direction = (player.position - transform.position).normalized;
rBody.linearVelocity = direction * homingSpeed;
but for some reason this isn't running. What might be causing this? the gravity scale for the object is 0 as well
Is this code executed at all? Add debug logs.
Byond that, make sure the rb is not kinematic.
And make sure you're not immediately overwriting the linear velocity next frame
if the code isn't running it has nothing to do with the code itself but where you put it and whether that is running
rigidbody is dynamic
it has a debug log on the previous line right above it and i see it in the console
If the debug from the line before is printing, then this code is running
i mean yeah but they are not flying to my player 😂
nope. just sitting as they were right before their gravity is reduced to 0
player = GameObject.FindGameObjectWithTag("Player").transform;
yeah it has this
where is the original code snippet located'
log your player.position and direction values right after the code snippet and show what the console says
log the values.
Debug.Log($"{player.transform} Going to Player");
im doing this. dont really know how to log values
Does whatever object rBody is on have any other code that changes the velocity
What does it say
UnityEngine.transform Going to Player
log player.position
At this point you should inspect the projectile object at runtime and share screenshots with us to avoid playing a guessing game.
As well as print the linear velocity and tell us the value.
since the gems are spawned after start, i tried moving
player = GameObject.FindGameObjectWithTag("Player").transform;
this to update but it didnt help either
Not a screenshot of code.
What is it assigned to? How is it assigned?
A screenshot of the projectile inspector at runtime please...
log player.position not transform
but at this point i doubt it matters
this also might be a long shot but have you confirmed your Player has the Player tag?
with what selected? inspector is empty at runtime cuz gems arent created yet
i was afraid of that as well lol. Yeah it does
then open the prefab
Wait until they are created, pause the game, select the object, take screenshot. Ez.
when the game is running you can still click things
I bet the animator is the culprit.
We still don't know what rBody is referring to
its refering to the Rigidbody2D
Also, when taking a screenshot like that, make sure rigidbody is visible too.
ill try without animator
I assigned it 😂 wdym
Okay, this is what I wanted. rBody could easily have been accidentally assigned to the prefab instead of this instance which would mean you wouldn't see any changes.
i think it cant find the player for some reason
I doubt since your log worked
If it couldn't find the player, you would be seeing errors from trying to refer to player
is your Collectible script also on the gems?
gem is inheriting from collectible so yes
Does the animator running an animation that modifies the object position?
only when collected but i tried without animation as well. Didnt work
when you say "without animation" do you mean you disabled the animator, removed it, or did something else?
removed the part with the object modification part
i don't know what you mean by that either
Change your log to this:
Debug.Log($"{gameObject.name}'s Rigidbody {rBody.gameObject.name} is moving from {transform.position} to {player.position} with a speed of {homingSpeed}");
And a screenshot of the rb at runtime.
it could be that since they are moving towards the ground check, they arent moving because they are actually dragging across the floors due to the colliders
since the ground check would be below their own transform point
Well, it's got at least 2500 units to cover at a speed of 5 units per second so that's gonna be a while
oh god, was everything scaled up to match the canvas size or something
Some of them are close though
yeah some are close
It's probably other gems far away
yeah those are the ones that fall while gravity is activated
i still like my theory 😊
other gems far away dont get activated
I bet on kuzmo's guess.
Might be good for testing to only spawn one
they arent dragging across the floor cuz then they'd move when i jump
fair that debunks that i guess
does changing the speed value to something massive like 500 have any effect?
I guess what's left is to have a look at the parent object.
Did you not try disabling the animator yet?
OK, then the parent. As well as bumping the speed to a high value.
does the parent have any scripts?
it doesnt
but i think i found the issue
rigidbody is turning static for some reason
its not static at runtime or when spawned. Idk what that'd happen
When does it turn static? I don't see it on the screenshot.
Try making it dynamic at runtime and see if it moves.
if all else fails, grab a direct serialized reference to your rigibody in the gem script
and try that
it somewhat worked when i reactivated the animator
the gems didnt move since they have an object transform. but they played the picked up sound. Their speed is set to 500 so i think in the update, their rbody went to the play while the sprite stayed still
How did the sprite stay behind if it's on the same object?
i think its an update bug
I really doubt that.
does the parent also have a sprite renderer?
That's more likely
no
what does the parent object have
also expand your spriterenderer in the inspector and screenshot it
that might almost certainly be the root of all issues here
screenshot the parents inspector
what happens if you disable both on the parent
i think they fall straight down and come back to the player after gravity is set to 0
my question is why is this even 2 gameobjects at all? I think you should remake the gem prefab imo, keep the rb and colliders only on the parent, and use the child for the sprite and animator
i know thats kind of a problem. I tried doing it that way. It basically has a pickup animation that also runs functions with events on the animator
yeah you absolutely don't want a separate rigidbody on the parent and child
the rigidbody should be on the parent, and there should only be one
the collider can live on either - doesn't matter which
ill try changing it at this point
Separate rigidbody == separate physics object
👍 thank you all for your time. I know its bad coding and practice but i didnt really know what the issue was when we began 
Why do both objects have sprites and colliders? Why are they two objects?
only the child has a sprite it seems, but yeah i dont see the point in 2 colliders and 2 rigidbodies
can som help
!ask
-# inb4 "gtag fangame"
: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
hey guys im having some difficult figuring out how to make this momentum system work the Y
I want it such that when a player hits a wall while sliding it retains a bit of their momentum and makes them slide, but I see the issue right now is the rb.linearVelocityY has basically infinite addition to itself. I'm not really sure how to make it return to its "default" state of having the physics control it
https://pastebin.com/LGvE4X29
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.
hi, can I ask a question here because idk what channel to post it at?
anyways changing any value on the Global light 2D URP doesn't do anything, any suggestions?:D
running into some issue where i dont know why but it enters isshooting bool and never turns it off
using UnityEngine.InputSystem;
public class Player_Bow : MonoBehaviour
{
[SerializeField] private Transform launchPoint;
[SerializeField] private GameObject arrowPrefab;
[SerializeField] private float shootCooldown = 0.5f;
private Player_Movement playerMovement;
[SerializeField] private float shootTimer;
private Animator anim;
private Vector2 aimDirection = Vector2.right;
private void Awake()
{
playerMovement = GetComponent<Player_Movement>();
anim = GetComponent<Animator>();
}
private void Update()
{
shootTimer -= Time.deltaTime;
HandleAiming();
if (Keyboard.current.fKey.wasPressedThisFrame && shootTimer <= 0)
{
print("F clicked!");
playerMovement.isShooting = true;
anim.SetBool("isShooting", true);
}
}
private void OnEnable()
{
anim.SetLayerWeight(0, 0);
anim.SetLayerWeight(1, 1);
}
private void OnDisable()
{
anim.SetLayerWeight(0, 1);
anim.SetLayerWeight(1, 0);
}
private void HandleAiming()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
if (horizontal != 0 || vertical != 0)
{
aimDirection = new Vector2(horizontal, vertical).normalized;
anim.SetFloat("aimX", aimDirection.x);
anim.SetFloat("aimY", aimDirection.y);
}
}
public void Shoot()
{
if (shootTimer <= 0)
{
Arrow arrow = Instantiate(arrowPrefab, launchPoint.position, Quaternion.identity).GetComponent<Arrow>();
arrow.direction = aimDirection;
shootTimer = shootCooldown;
print("Fired an arrow!");
}
anim.SetBool("isShooting", false);
playerMovement.isShooting = false;
}
}```
you set it to false in the Shoot method, but where do you actually call that?
i call it in my animation triggers
Your video didn't show anything to do with isShooting
ye
that is very backwards
but why
why what
why do it this way... you can just call the shoot function when you press F
and then set the bool there
no when i press f
it shoots right away
i want to make it shoot on a certain frame
not right away
are you positive your Shoot function is getting called at all?
yea it is
how would it be set to true if its not being called
Debug your code with log statements
because you arent setting it to true in your shoot function...
oh
i dont think your shoot function is being called at all
this is also why i recommended what i did earlier
keep the shooting mechanics under 1 function
if you need it delayed with an animation event keep that as a seperate function
then in your update just do "if (f) Shoot();"
put playerMovement.isShooting under that function as well
oh wait
i just realized my error
my animation isnt even playing
ah
finally found the issue after 2 days
bump
This intellisense thing is an insane asf mind reader/ predictor or my codes are just that simple?
Hi all! I'm a newcomer to DOTS and ECS and I'm running into a problem, and I was wondering if anyone here might have any advice?
Is it possible to gain read-write access to a DynamicBuffer during a parallel job without passing it in as a parameter? I have a parent entity that the job operates on, but during the logic, I need to alter a DynamicBuffer belonging to a child entity of that parent.
Unity's built-in safety systems are preventing me from using a BufferLookup with read-write permission in a parallel job to prevent multiple threads from trying to write to the buffer simultaneously, but I believe that each individual child's DynamicBuffer will only be accessed once, so unless I'm mistaken there shouldn't be a risk of that happening.
I'm unfamiliar with other ways to access a DynamicBuffer of a different entity other than a BufferLookup, and my attempts at searching and asking so far have not led me to figuring out how to remedy this or work around it. Any assistance is appreciated!
Might want to ask in #1062393052863414313 . Definitely not in beginner channel.
Ah, thank you! In my sleepy state I didn't see that spot in the server! I'll go ask there.
Hello guys, I tried to code a yaw movement to my object, but it kinda buggy. Can anyone detect my error? I want to code the object to do yaw movement without any problems.
!code Please paste it correctly so people can check the textbased version
📃 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.
kinda looks like your ide isn't configured
!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
Hey, my IDE just stopped working and m confused whats going on.
I have .net 8 and 9 installed. It was working fine, but today VSCode is saying this.
You must install or update .NET to run this application.
Framework: Microsoft.NETCore.App version 10.0.0
I dont have C# Dev kit
just C# and .net install in vscode
When i open VSCode, I get this error.
are your extensions and ide version all up to date?
hey, i was wondering whether there is a way to modify this .lua file inside the resources.assets in the files of a game? I dont know where to ask this kind of question
i tried to open the file with unity, but it didnt work, im really unexperienced but trying to mod some parts of the game "Esports Club"
Modding is not a topic that is covered on this server and not allowed to be discussed.
oh okay my fault!
Not the IDE, but extensions yes
I installed .net 10 and its working now.
do you know where I can get info though? Its not really for anything bad, I just wanna add some more characters to the game as its capped at 30
i tried to google, the game only has a chinese playerbase and sadly i dont know any chinese
Again, not the right server to ask. Google is all I would do in the same case.
how can i change Debug.Log() text color?
The logs support rich text
thanks @midnight plover, i should have done that first
ye
i try to learn how .json works because i need to save and load some data on my game.
i already have the json file but i haven't figured how to add thos value to load on my code as veritable if found this i will move next part is to save values back but first i have to found how to make out load the data for json.
{
"playerName": "David",
"isAlive": true,
"score": 150
}
Make a transfer c# object
what do you mean by that ? you meant like game object ?
you can serialize and deserialize c# objects to your likings. So if you have a class with public float, string and int, this would convert it to a json string or convert back the json string to your class so you can use it
Create a c# object that represents the data you want to grab from Json or save to it
For example you have in your case a string , a bool and a number.
So a class or struct, (object) with that data types. Then you use a utility like JsonUtility or the Json.Net to convert
so beastly like this ?
public string playerName;
public bool isAlive;
public int score;
Pretty much
yes but how to make this value to take the json data for example in this case player name becomes David or whatever value i have ?
That would convert to something like
{
"playerName":"yourName",
"isAlive":true,
"score":123
}
so if you wanted to change the name, you take your c# object, set the value and serialize it to json and save that string to some file on your harddrive/playerprefs/whatever you like
i already have the json file i don't know how to load this to my script.
Have you googled for the terms we gave you?
Saving data is critical for any game. Whether you need to save high scores, preferences, or game state, Unity offers a variety of methods – from PlayerPrefs to serializing data, encrypting it, and writing to a file. In this video, we share some valuable tips on creating data persistence in Unity.
Speaker:
Bronson Zgeb, Senior Content Develope...
https://github.com/SpawnCampGames/Dbug/blob/d5c56fb53371954a5dc8afaf705d7e498acbf878/Dbug.cs
you can just use rich-text as someone mentioned.. i've made my own lil static class u can put in ur project
use using SPWN; as a namespace and just use Dbug.Log()
formattedMsg = $"<color={color}>{formattedMsg}</color>";
thats actually very useful, thanks
very welcome... it was kind of a "just bored" project.. i didn't do much w/ it besides make some simple gizmos i can use like circles and rays and whatnot
but ur welcome to any of it that helps u out @lunar axle 🍀 happy coding
i would love to optimize it if u wanted to
like i can wrap the styles to a struct which will be cleaner
although this is already good enough
i don't really understand how json work's yet Hoever for what the say o video i check it say to i have to siralize and desiralize the object.
Serialization and deserialization are the steps that let your code go back and forth between objects and JSON
yes it make sense i haven't understood how yet to do that yet i will check the video later.
and hopefully i will understand.
I just read the following statement "Stay away from OnDestroy() in general: it has too many edge cases, especially at edit time. Use OnEnable() and OnDisable() for all sub / unsub needs." Does this actually make senes as a rule of thumb? I've been using it a fair amount. I definitely track the state of my objects though.
i thought OnDestroy() calls only on its object deletion, nothing else?
Here is the thread [https://discussions.unity.com/t/remove-event-subscriptions-ondestroy/933194/15]. @Lam : That is how I've been using it. I'd have to go through my old code and see what problems I would have running off OnEnable/Disable. My general approach is to use Start/OnDestroy when subscribing to event actions...which is what I'm doing now
Just trying to learn best practices...I'm still very new to Unity
look i don't know what you make but some times
if you make game you have to destroy and create new game object
instead off disabled and enable but it depends on the project and the code
i think it really depends on what ur trying to achieve
OnDisable() is called just before OnDestroy()
and OnEnable() is called before Start()
so its tomato tomato. like Lam said.. it depends on what u want to achieve
i prefer OnEnable and OnDisable.. b/c i know it'll work if im toggling the gameobject..
I think the "issue" is OnDestroy doesn't always run when you expect it to. In this case I'm just subscribing/unsubscribing to event actions.
I definitely create/destroy/enable/disable objects constantly
😄 dont we all
when u call Destroy() it will run OnDestroy()
Multiple Calls: OnEnable can run multiple times, whereas Start is guaranteed to run only once per object. this is basically the idea
this is the caveat u have to entertain
same to Awake()
👍 also true.. Once per lifetime of the script instance
although i think theres a fuction call that calls even before Awake()
this how i wrapped my head around coding in unity
i know electronics are on/off
and i knew how to change things around in teh inspector..
with those two key points i was able to pick up Unity pretty quickly
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
I've never had any issues...it was just a statement I stumbled upon. Maybe i has something to do with OnDestroy running at the end of the Script lifecycle....so people assume it might run earlier than expected
dang.. lol
i had to see what dude was talkin about
Reset().. yea idk about him
never used em
spiking off create objects for what i have seen some people use method call pool
but for what i understand this system only disabled and enable those instead off destroy them and re usethem if reach then number before the do why is thhat ?
creation takes more than if it already exists
pooling systems take advantage of cycling thru gameobjects that you only need to instatiate once.. (like at the beginning of the game)
instead of destroy and creating it just toggles on and off.. keeps the garbage collection down
more performant
you typically use just enough
say u only ever want 10 bullets on screen.. u'd make a collection of just 10..
maybe 1 or 2 more just in case
yes i knew that but hear what is the problem if make poll off 100 for example when player fire and the player doesn't fire at all this 100 object pre load with out reason even if those are disabled.
if u dont do that you'd use a dynamic system
which i think is what ur talkin about..
so u create objects when needed..
but only up to the limit.. and then u start re-using..
U can calculate how many bullets u need to instantiate first to make a pool initialy
If player fires:
- If disabled object exists → reuse
- Else if CurrentPool < MaxPoolSize → create new → add to pool
Preloading too much is a memory/performance hit if the objects may never be used.```
its a balancing act..
as much of development is
Every fps matters
lol.. ive been learning unity 5 years now..
i still havent sat down and started focusing on frame-rates
😬 eeek lol
what im try to mix approach it will be better why at lest for my project that have multiple weapon.
intense object if object go bigger then and haven't distory reuse the existing object else if x amount time past distory or something like that
cap it at 60 and call it a day//
=)))) lucky u, once u enter the optimization rabbit hole ull never be the same
im just now climbing out of the editor extension rabbit hole
dont tel me theres another one 👀
lol
i dont do well in rabbit holes
Thats a good thing, u dont go too deep
im erratic enough as is.. i have to stay really surface level to keep my sanity intact
/// SPΔWN[CAMPGAMES]™
/// DYNAMIC OBJECT POOL || RUNTIME
/// SCRAP (scripts-development)
/// License: CC0 SpawnCampGames Free-Use, see: LICENSE.md
using UnityEngine;
using System.Collections.Generic;
public class DynamicPool : MonoBehaviour
{
[Header("Pool Settings")]
public GameObject prefab; // object to pool (bullet, enemy, etc.)
public int maxPoolSize = 10; // max objects to ever create
private List<GameObject> pool = new List<GameObject>();
/// Get an object from the pool
public GameObject GetObject()
{
// Look for a disabled object to reuse
foreach (var obj in pool)
{
if (!obj.activeInHierarchy)
{
obj.SetActive(true);
return obj;
}
}
// No disabled object found, create new if under maxPoolSize
if (pool.Count < maxPoolSize)
{
GameObject newObj = Instantiate(prefab);
pool.Add(newObj);
return newObj;
}
// All objects active and reached max, return null (or handle differently)
return null;
}
/// Return object to pool
public void ReturnObject(GameObject obj)
{
obj.SetActive(false); // just disable it
}
}
something like this is a dynamic (create as u need) setup
Before digging in a rabbit hole, search up for github and use what they did first
Woah u just coded ts up?
and usage:
if (Input.GetButtonDown("Fire1"))
{
GameObject bullet = bulletPool.GetObject();
if (bullet != null)
{
// position bullet
bullet.transform.position = firePoint.position;
bullet.transform.rotation = firePoint.rotation;
}
}```
i sit on soo many prototypes i have almost everything already 😄
jsut comes down to my organization skills and how fast i can find it 😄
thank God for indexing
so system like this exists thank this big help i goin to check this system later
Reuseable code on top
my problem is trying to make everything re-useable
Addressables is also a good way to keep things running and reuse assetreferences
So liek prefabs?
like DLC
Recylable code
If you use prefabs in a scene, they are loaded into memory, assetreferences can be used in inspector without adding the actual object to the scene. as the name states, its just a reference and will only load when you call it to, so no memory clutter because you packed everything into the inspector upfront
my biggest problem as game developer is although im solo development i try to make huge projects on my own and i have to do everything for code to 3D model or whatever.
same here 😉
Thats nice
u get better work-flows as u learn
So meaning u can also save reference for scripts?
i work on bigger projects than i can handle as well..
but that doesn't mean u can't work on smaller projects at the same time..
i try to make things re-useable.. soo systems that are in the bigger project (that ill probably never ship) usually get packaged up and moved over to a smaller project
And other stuff other than gameobjs
if u guys were to make a script that moves a gameobject (x amount of units every x seconds but not smoothed )
like a step animator how would u do it? with coroutines or something else
Not sure what you mean. You can reference anything that addressables support, but scripts are precompiled when building your game. so you cant add "new" scripts through addressable bundles. But yes, you can reference audio, images and what not.
I created my own coroutine manager that stores all objects that call it and handles the same animation types like position, localpos, rotation and what not, soy ou can call the manager anytime and it will smoothly takeover the previous coroutine with a new one.
o thats neat
It basically stores all mono references that called it with the specific transform and check aginst null and what not. And in the end you just call it
this.Animate(yourTransform, Easing.AnimationType.LocalPosition, Easing.Ease.EaseInOutQuad, yourTransform.localPosition, nextPosition, duration);
for example
i dont understand what u mean by "not smooth", like u meant teleport after an amount of sec is what not smoothed means?
yeh, just change positino every nth seconds. Id do that with a simple coroutine/while loop
or u can create a new mono-behaviour script (call it Glide) that moves the object in Update()
sounds like a plan..
how do i destroy a gameobject through C#
what did google tell you?
i did not ask google
he might know
well there's your first problem. you're expected to make at least some attempt at researching your question before asking here because a 10 second google search can answer that easily
Update: I successfully fixed my code after hours of understanding about Quaternion.Euler stuff. I did yaw and roll hahahahahaha
And i did the pitch movement too
Coding in project work is sooo easy, I can just write "I abandon it after several failed attempts" instead of writing codes
rezero!
Any kinds of development researching / reading documentation is most of the work
# Milestone
Unity is trolling me
How is it possible that these two identical world transforms are in different places? They are not children of anything
select center at the top left and switch it to pivot
they were always on the same spot
the handle just showed up on the center of each
instead of their origin point
I know that the origin point at least for the 3d model is defined by blender. What's the center?
median center of all mesh vertices for 3d models i think
might also be bounds center, im not 100% sure
pretty sure it's bounds center, wouldn't average of vertices be biased to a dense part of the mesh
It uses the center of the total bounds of all colliders and renderers on the object
Use #🔀┃art-asset-workflow or something, this is a code channel.
If I have ClassB : ClassA and call StopAllCoroutines() in ClassA, will that stop coroutines running in ClassB?
these are instance methods, not static methods
are you calling it on the instance of ClassB? if not, then no. it only affects the instance that StopAllCoroutines is called on
StopAllCoroutines will stop all coroutines on whatever instance you call it on
Coroutines don't run on classes
I have an instance of ClassB and I'm calling a method in ClassA that calls StopAllCoroutines, basically wondering if for some reason it wouldn't affect ClassB coroutines
The coroutines run on the GameObject
Figured since B is an instance of A it should stop
the inheritance is basically irrelevant, it's about the instance
i don't think so? pretty sure they're on Components
it's confusing
deactivating an object stops all coroutines on the object. but the docs are saying that stopcoroutine "Stops all coroutines running on this MonoBehaviour"
but if you're just saying you are calling an inherited method that doesn't make a difference. The ClassB instance is one instance. Calling StopAllCoroutines will stop the coroutines on it, regardless of where you wrote the line of code.
the active state of a gameobject affects all its components updating as well, is it really that weird for that to also apply to coroutines
GameObjects also have no members related to coroutines
Thank you, this is what I had thought as well
the runtime doesn't really know if the StartCoroutine or StopAllCoroutines call came from B.cs or A.cs, it only knows which instance it was called on
i have found how to load values with Jason but for some reason the don't show my the string value.
this the 3 parts
JsonExample.json
{
"playerName": "David",
"isAlive": true,
"score": 150
}
Data ```c
using System;
[Serializable]
public class SimpleData
{
public string playerName;
public bool isAlive;
public int score;
}
```c
using UnityEngine;
using System.IO;
public class LoadJsonExample : MonoBehaviour
{
public string newPlayerName;
void Start()
{
// Load JSON file from Resources folder
TextAsset jsonFile = Resources.Load<TextAsset>("JsonExample");
// Convert JSON text to class
SimpleData data = JsonUtility.FromJson<SimpleData>(jsonFile.text);
data.playerName = newPlayerName;
// Now you can use the values
Debug.Log("Name: " + data.playerName);// The don't show my the String value hear the other 2 below show correctly
Debug.Log("Is Alive: " + data.isAlive);
Debug.Log("Score: " + data.score);
// Example usage
if (data.isAlive)
{
Debug.Log(data.playerName + " is alive with score " + data.score);
}
}
}
data.playerName = newPlayerName; overwrites the value. Did you mean to have this the other way around?
yep you're overwriting it with whatever is in the inspector
Also I love that you got Jason to work for you, he's a good fellow
yap now it's working thank you save my for a lot of trable
which way is the correct way of doing the curly brackets 🙏
Which you prefer :3
i honestly prefer the bottom one
Allman(bottom) is traditional to c# while k&r (top) is more typical to Java or cpp
But there is no right or wrong
I use both of them for example time after time
Most of the time second one
okay why the hell is "?" automodded
Because it's another way to prevent spam
Why do you need to send less than a few chars message when you can edit it or react to post
Actually you can do it more masochistically.
void something3() => DoSomething();
or
void something4() {DoSomething();}
But yeah, it is just a joke
||Isn't it?...||
people that code like this scares me
im so confused, it has the same name how would it not be used?
Invoke(nameof(ReloadLevel), 2f);
Try it.
you have done something weird here the function ReloadLevel is either outside the class or the above ones are all local functions
Try signing out of the hub and signing back in again
Invoke uses reflection when you type it like that
Yes i will look it up by string / name at runtime. It's not really type safe doing it like this , as far as it knows you're not using it
At very least you can do nameOf keyword
Invoke(nameof(ReloadLevel)) to avoid spelling errors but still. Learn coroutine if you want delay
Okay.. got it
invoke is fine as a beginner but better ways exist as said above
Oh didn't see Norman sent the nameof thing. Mobile network slow as hell 😆
nameof() is such a good language feature
Sometimes if you don't want to start a Coroutine with the same meaning as Invoke(time) why not use it instead? Because it's impossible to catch the call or what?
Async is an alternative and yes the better alternatives can be cancelled or controlled better.
plus the call stacks should be better preserved
Invoke asks the engine to invoke some function with a name at some point in the future
(thats how many unity messages work anyway, the engine directly invoking functions in the CLR)
Fun fact, unity recommend doing your own "update" calling in c# (for lots of objects) as that can be a lot faster than relying on unity to call it on many monobehaviours
there is greater cost to native-managed crossover and unity even doing the managed call native side
i need some help i cant open or create a project and i dont know what the problem is(forget this message it somehow fixed itself thanky you unity god)
I've slowly changed all my stuff to do this . . .
I did a TD system thing a bit ago and I manually "ticked" them all as its a lot easier to control what happens and we gain some performance
It only starts to become nessesarry when we have say 250+ things
Maybe I'm tripping but I feel like that ends up kinda happens naturally once you get more comfortable with c# since you end up doing a lot more stuff outside of the update loop and more via callbacks or coroutine/async type shit
maybe im not dipping my toes in the right genres tho idk
i just seem to slowly start not having much in update
If you know programming, OO and good design its more natural to not over use unity messages
I much prefer to init and control things myself because otherwise you have to do stupid shit trying to get by only with Awake/Start
True, it really helps once you reach a certain amount. Making a TD sounds like a fun project . . .
blessed genre
the td i made for a like 4 day gamejam has more sauce than some of my month long projects
It was a hybrid but had things moving along a path and towers to shoot the enemies.
Once I started pooling objects, Init became a necessity. I think I started using a custom update when I created an object and separated each of its behaviors into its own script, and called OnUpdate from the main controller (or brain) . . .
It would be so nice if we could have proper constructors directly
how do i get visual studio code to work with unity
ive already installed it but i cant create scripts
!ide has the guide for configuring it.
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
yea its dumb, Awake is not 100% reliable so manual init is the way
forsure
i still gotta keep tinkering with my prefered setup for ideal init with so's and prefabs
it's almost there but then trying to handle netcode for gameobjects with it just blows it all up 😄
I think rider has some features to warn you to use an Init method when instantiating
there's some useful utility like forcing to use a return value
Is anyone able to help me with getting my crouch height/ceiling detection work? I created a forum post in code-general, been stuck on this for a couple days and I've looked at a ton of videos, forums, unity documentation. my current setup "works" but its super janky and has all kinds of issues
its been 30 mins..be patient & don't crosspost
I'm patient, just didn't know that was a rule/etiquette my bad
You may want to link to any information that you had previously provided.
I think this is just a "i don't know math well" question, using this function to make a UIToolkit pie chart, https://docs.unity3d.com/6000.3/Documentation/ScriptReference/UIElements.Painter2D.Arc.html
I've got a center, radius, start angle, end angle and direction, I want to get the centre of the arc i'm creating with these
Okay, idk what to search to get what I want, but I know of it.
Is there a function or something (i don't remember what it's called) that pauses a script for a set amount of time/frames?
Like, I want to have a script that runs, then holds for one second, then runs.
(There might actually be a much better way to do what I'm trying to do tbh...)
You're looking for coroutines
Okay, after looking into it, I'm seeing a lot of stuff saying only to use coroutines if I need to repeat things, which is not what I'm doing. I just need to make the script hesitate before checking something.
Incorrect
Use a coroutine for any code in which you wish to insert inline delays
Not sure what you're reading
Repeating things is done with loops, another subject entirely
You can certainly put a loop inside a coroutine but there's no requirement to do so
just several forums talking about where and when to utilize coroutines because I was trying to find documentation for IEnumerators
You will confuse yourself with that. Just look up Unity coroutines
It uses that type, and there's a technical reason why but it's not necessary to understand it to use them
More specifically the incorrect part here is the Only, you might also want to use coroutines in situations where you want to repeat things forsure
it's using IEnumerator in the coroutines, and I'm getting an error saying that IEnumerator doesn't exist 😅
might be missing a using, does it have a suggested fix?
No it's saying "are you missing a using directive"
which is why I was trying to find documentation for IEnumerator
The issue with wanting to make a "script hesitate" is that code runs in order, if you have this logic
wait until (x happens)
thing that makes x happen
x can never happen because the code will be stuck on the wait.
Coroutines work in a way where are kinda "submitted" to Unity and every frame Unity will check up to see how it's going without interrupting the code because now it's
Start Coroutine();
Unity collects Coroutine
Unity checks Coroutine
Unity looks for condition in active coroutine (the condition being wait until x happens)
The condition replies with false
Unity carries on with it's day
I mean it's not hard to find that, on the Microsoft c# docs
Okay, I've got it working, now another probably simple question...
Is there a simple way to check if a boolean changes state?
But if you're just looking for the namespace your IDE should be telling you automatically
Yeah, that's never worked for me for some reason
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I mean, it autocompletes, but it doesn't like.. suggest code stuff?
anyways, that's not really an issue
get your IDE configured using the guide linked and it will work
It's already configured
do errors get underlined in red?
Is there a simple way to check if a boolean changes state?
my VSC was in restricted mode, that's why it was being screwy 🤦
no 👍
there's no automatic notification system unless you set it up that way (with for example C# events)
I'm having such a hard time with making my character go between walking and climbing, I feel like I need a more robust detection method or like... knowing whether the player is on the ground or trying to climb but idk
you ever just sit there being like why won't my event fire why won't my eve- oh.. I didn't invoke it.. I'm that dumb
how do I make a coroutine just like stop? It keeps asking for a return, and if I try to make it return nothing, then it gives and error, and if I do anything else, the coroutine never even runs 😭
post your code
coroutines are a little weird looking when you first use em don't worry
yield break
YES, I knew there was a way, but it was completely avoiding me 😭 I'll see if that works
idk if this is the best way to post code, but y'all will tell me
private IEnumerator ClimbCheck()
{
if(!isClimbing && wallFront)
{
if(!climbHold)
{
Debug.Log("started climbing");
climbHold = true;
StartClimbing();
StopCoroutine(climbCheck);
}
}
if (!wallFront)
{
Debug.Log("stopped climbing, no wall");
climbHold = false;
StopClimbing();
StopCoroutine(climbCheck);
}
if(isClimbing)
{
if(isGrounded)
{
Debug.Log("stopped climbing, hit floor");
climbHold = true;
StopClimbing();
StopCoroutine(climbCheck);
}
}
yield return new WaitForSeconds(1.0f);
}
thats fine for small snips, you can add cs after the three thingos for better formatting
same line
no clue 😅
it just isn't lmao 😭
oh you want the start of your code to be on the next line
(and the last ``` to be on a separate line as well)
there we go
🙏 ty
Not sure what the purpose of this being a coroutine is. You only have one yield and it's at the end
that last yield return doesn't have anything after it, you're waiting to do.. nothing?
also you don't need StopCoroutine to stop the current coroutine, you can use yield break; instead
so yeah yield break can work
this is because what you return in a coroutine is basically you telling Unity what's the status of the coroutine,
so when you return new WaitForSeconds() your telling Unity "hey do this before checking up on me again" or break is telling Unity they can finish up with it
yeah, this is what happens when I'm just told "use a coroutine" and nothing else 😮💨
learning is incremental 😄
hey, no errors, this is learning progress lol
You didn't ask for it but would you be interested in a little advice on a slightly "better" way to approch what that code is doing?
Coroutines will run normally until they hit a yield. Then they'll wait for whatever that condition is before resuming with the next line
I was thinking that if I can pause the check for if the player is trying to climb, the code that's doing the transition between climbing and not climbing would actually work smoothly and not jitter around
So, you could run a line, wait 1 second, then run another line.
Or, you can do a yield return null which waits one frame and resumes next frame
the coroutine is in its own realm, any yields you do inside won't affect the timing of stuff outside
I'm probably using the right thing, I'm just not seeing how I need to put it all together for it to work
I have all the right pieces, but no instruction manual 😅
The issue I'm having is that when the player is trying to climb, it calls for StartClimbing() and StopClimbing() at the same time until one wins out because I don't have a clean way to detect when the player is trying to climb, I can only detect when they are standing at a wall and trying to move and if they are touching the ground.
i feel like ive commented on this before
SO my thought was to slow down that actual process and not call one until the other has tried to run through, and maybe that would make the transition smooth
Maybe, I had it working sorta but it was just jittery
startclimbing when you actively move up, stopclimbing when you actively move down
opposite checks, so it shouldn't jitter
Yeah, I'm just having a hard time trying to differentiate those states
moving up and moving down are not things that I am or idk if I even can read for
well you don't seem to be using player input in the checks in that coroutine
you can absolutely read this
those checks are the basis of my idea lol
I mean with the way my code is set up
well, how is it set up?
lots of spaghetti
that doesn't really affect what you can and can't do, just difficulty
straightening spaghetti is a war that can be won in many small battles
we're probably gonna have to pick a fight or two here to get what you want
-# well that sounds cursed out of context
I go back on myself a lot, and I'm scared to try touching it cause it'll break what I have and will add a week of fixing just to get back where I am 😅
I cook code so I can avoid learning how to cook IRL
well we can't really give much guidance here without seeing your code
perhaps share the full script
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
With Paste of Code, I just paste it in and send the link here?
Spent 2-3 days trying to fix the crouch height collision scripts, watched a ton of videos, looked at a ton of forums, and the issue was in one of the tutorials I saw they told me to scale player 2,2,2. So all my ceilingcheck scripts were failing and I thought it was some issue with centering/changing the origin of the object... changed it to 1,1,1 and reverted some changes and it works perfectly now...
mentally preparing myself to be destroyed
I will say that I don't really use // for notes, mostly just saving code I've replaced in case I want to go back or need to see it
thank god
hol up
no no, I'm doing that
I think
Yeah, I'm trying to do that with the IsClimbing and IsGrounded variables
I just don't check specifically moving up or down, just moving because I'm translating forward and backwards into up and down
but you aren't checking input
are forward and up not the same input
if (moveLike != Vector3.zero)
{
isMoving = true;
WallCheck();
if (wallFront && !isClimbing)
{
//Debug.Log("Start Climbing");
StartClimbing();
}
like consider this snippet, if you walk up to the wall and then walk away, you start climbing. the direction is important here.
I'm multiplying the Forwards and Backwards inputs by the direction the character is facing
otherwise the player moves strictly on X or Z coordinates
oh, going off the directions of the camera, i see
gotta see if you're walking into the wall then
The camera if not climbing, the physical direction the character is facing if they are climbing
tbh, idk what I'm actually using wallLookAngle here for
I can prolly get rid of it
this does not check if you're walking into the wall
this checks if you're looking at the wall
the player input is important here
idk how to check that
with the way my movement is set up
cause all I know to check the movement would lock it to the worldspace X and Z, not the players forward vector
could probably split it into 2 steps
- figure out the direction from the player to the wall (or the wall's.. anti normal, i guess)
- see if you're walking approximately in that direction
the latter part could be done by getting the Angle between 2 vectors and see if it's within a range
so wallLookAngle is my savior in the end lmao
oh, yeah, raycasts have normals
then yeah that seems like it'd help
How do I check if the player is moving in the direction of the wall?
...i just described it
check if you're going in roughly the direction of the antinormal
(probably projected onto the XZ plane)
I'm going to say a lot of choice words
I didn't even have to do allat
I literally just had to remove this
And add this
now it works exactly how I wanted and fixed literally every problem I was struggling with and was planning on fixing
ok now what if you walk up to a wall from the side
doesn't start climbing until you're basically facing the wall
I can make it a little tighter, but otherwise it's kind of annoying to get that kind of angle anyways
you can face the wall with no Z movement
this is the forward/backwards variable for movement
like, the direct input
basically W key or S key (not literally tho)
and you can walk up to a wall without going forwards/backwards
Yes, the only way the play can climb the wall is by walking forwards into it
you can even jump off walls now, I thought I was gonna have to code that in
although I want to make the player launch backwards, but I'll have to figure that out
You apparently did, just dont know where 😉
I still kinda do. I have a dismount function to get over ledges, but you can't like, leap off of walls, which is what I want.
So when jumping on a wall and hit jump again, you want to jump away from it?
No, when you're climbing a wall, you press jump and you jump backwards off of the wall.
Ah, got you. So you just gotta check against the will and jump into the opposite direction
thanks, will try that out right away
this is a code channel, so.. not the right place. If you can't find a channel specific to your question, don't use a random one.. use #💻┃unity-talk
delete from here and ask in there
Sure, thanks
what helped yall figure out state machines? right now its been kicking my ass for a few days and i cant figure out how to properly set it up
A full understanding of the underlying concept.
(which I learned in school)
does anyone know how I would put a texture as a floor on my 2d top down game, Im not sure about a good way to go about it. I want to have different biomes with different floors
sounds to me like you should probably use a tileset for that rather than a singular texture?
Not a code question
Hi, I'm new to Unity and I want to learn the basics of programming for a shooter game I want to make.
check the pinned messages of this channel
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
PlayerInput playerInput;
InputAction moveAction;
InputAction lookAction;
private Transform cameraTransform;
public float movementSpeed = 50.0f;
public float mouseSensitivity = 1.0f;
private float cameraPitch = 0f;
void Start()
{
playerInput = GetComponent<PlayerInput>();
moveAction = playerInput.actions.FindAction("Move");
lookAction = playerInput.actions.FindAction("Look");
cameraTransform = GetComponentInChildren<Camera>().transform;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
Move();
Look();
}
void Move()
{
Vector2 input = moveAction.ReadValue<Vector2>();
Vector3 camForward = cameraTransform.forward;
camForward.y = 0f;
camForward.Normalize();
Vector3 camRight = cameraTransform.right;
camRight.y = 0f;
camRight.Normalize();
Vector3 movement = camRight * input.x + camForward * input.y;
transform.position += movement * movementSpeed * Time.deltaTime;
}
void Look()
{
Vector2 look = lookAction.ReadValue<Vector2>();
float mouseX = look.x * mouseSensitivity * Time.deltaTime;
float mouseY = look.y * mouseSensitivity * Time.deltaTime;
transform.Rotate(Vector3.up * mouseX);
cameraPitch -= mouseY;
cameraPitch = Mathf.Clamp(cameraPitch, -80f, 80f);
cameraTransform.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
}
}
can anybody explain to me why no matter what value i set sensitivity and move speed, they dont change in game?
Are you changing the values in the inspector or the script itself?
you should not multiply mouse delta by deltaTime
it's already per-frame
also yeah
keep it for movement
for mouse you can just do
float mouseX = look.x * mouseSensitivity;
the values in the script are just the default
the inspector is overriding them
when they're serialized, in an actual component, the serialized values take priority
whatever you had in the inspector initially will always remain until you change it there
change your values in the inspector instead.
you should still remove the deltaTime from the mouse look
nah that would make tweaking specific instances impossible and completely negate the point of having serialized variables
ill just change them to private id rather have the code control the thingy
that would defeat the purpose of serialized fields entirely
you should not
doing this would mean you can't tweak them easily - every single tweak would require a recompilation to apply, which might not work properly at runtime, when live tweaking helps the most
you would also not be able to tweak specific instances
get used to exposing and tweaking in the inspector, it'll make your life much easier
(it also means you can reserve the value in code for specifying the default when you create a component, making the distinction actually useful)
aight, the movement speed works now, but after removing the time delta from mouse, it turns at the speed of light
You will need to adjust the numbers
But now it is not negatively affected by frame rate
wait yeah nevermind sorry i forgot to change it
hehe
yeah everything works
thank you so much
Hi, I'm just starting to learn Unity and I wanted to know the most optimized way to load maps in first-person 3D games, and if possible, could you give me the names of those methods so I can do a more focused search?
Sorry wdym most optimized way to load a map? Like scenes to store different areas (like the inside of a build vs the open world? Or something occlusion culling thats used to hide the mesh from being rendered when not in frame?
Most optimized way is usually addressables/assetbundles if we're talking about mem management
just a quick way to load/deload all the dependencies of a level
Well, I'm not quite sure how this fits in, but to give you an idea, I intend to make a map of a closed area in the style of FNaF SOTM (where there are several places that, as you progress, you unlock and see that they connect), but my problem is that it will be poorly optimized when implemented in Unity, and I wanted to learn a method that makes visible only what is necessary.
If you're just starting to learn Unity, this topic is way too advanced for you. It's not something to worry about right now. Learn the basics first.
Beginners worry way too much about "optimization". Get your game working first
Yeah, I wouldn't worry about mem and just cache all the prefabs
and init what you need
even the project you described seems awfully ambitious for a newcomer
For now all you need to know is you can load scenes with the methods in SceneManager
and you can instantiate prefabs with Instantiate
yeah, that's the problem I'm having, idk how to make it jump in the opposite direction 😅
What is used to make a list of objects? Like... I know what it is, but I cannot remember the name for the life of me.
Well, it's not that this is my first game (just my first 3D one), but I wanted to know at least the name of this method so I can research it (also because I can't afford not to worry about this since my PC isn't one of the most powerful, so it would be good to avoid things like this).
I'll see how this works.
a List?
It was something with an 'A' I thought?
It might just be a list I'm thinking of, idk
do you mean an array? because that's like a list but not resizable
youre thinking of arrays
yes
They might be thinking of ArrayLists even
thank you, I was blanking so hard 😭
Arrays and lists are related and similar. Lists use arrays inside. You should learn both
I know, I just know for this specific application, I was needing an Array, I just couldn't remember the name
so just to confirm, you need a collection that you cannot add to at runtime? because that's why you would choose an array over a list. a list can be added to or remove items, an array is fixed size
Yes, I'm using it to hold the different pages of the player's "Inventory"
and then change through them as the press "Next Page" or whatever
I am now thinking there would be an easier way to set the page than what I was initially thinking after setting up the array 🤔
Is there a good way to set the active item to the current array value? And have the others inactive?
what do you mean by "current array value"
Cause my first thought is to just compare it to an integer that's changed by pressing "Next" and "Previous"
like, there are 3 objects, I want to set it to Object 2 and only Object 2 is active.
well then you would set the current page to be active and the other pages to be inactive
if you remember what page you were previously on, you can set just that page to be inactive (assuming all other pages are already inactive)
if you don't want to make that assumption or if you don't want to have to remember that, you can just loop and set them all to the proper active state
it's a noop to deactivate an inactive object anyways
Yes, I'm just thinking there might be an easier way than a long if statement 😅
you would not have a long if statement
then idk what you're saying I can do
you can just loop and set them all to the proper active state
that means nothing to me
just keep an int that corresponds to the index of the active page. then when you switch pages, you just change that int then loop through the array of pages, if index == that int, set page active, otherwise set inactive. you literally just do pages[i].gameObject.SetActive(i == activeIndex); (changing relevant variable names as necessary) assuming you are just enabling/disabling them
yeah, that's what I thought, ty ty
the more efficient way is to just track the currently active page. When you switch pages you deactivate the current one and activate the new one.
yeah but that's only really marginally more efficient and really a microoptimization if they only have a few pages anyway
A bit of a structural question i guess,
Im refactoring my status effect system in my game, and the way im currently doing it is like this:
When an effect like "Burn" for example is applied, a singleton effectsmanager looks up its data in a dictionary, gets the pre cached script type for that effect and it applies it. Because the effect types are resolved and cached at startup, theres no reflection during gameplay just quick lookups and method calls.
Do you guys think this would be efficient? Or should i not use a dictionary lookup for this. It allows me to keep all effects as individual IDs hardcode in a static class.
sounds fine
does it need to be a monobehaviour?
basically you dont always have to make things a mono singleton
The Singleton that maps the IDs to their respective Assets is an MB
does it require mono messages or serialized variables?
Sometimes its easier or better to have a static manager or one you init and use
yeah this is perfect actually
thanks