#💻┃code-beginner
1 messages · Page 776 of 1
pooling
- it's pooling not spooling
- making your own object pool is more complicated than just using the built in one

For new dev, I think the built-in pool is quite ambiguous. It hides how the pool internally works, so it may get confusing
you know what screw this, even if it takes me a whole week to implement it i will do this then
But basically they are similar. Both use Stack or List
how do i get an action map that is not currently selected?

unity is hard bro
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CusCursor : MonoBehaviour
{
public bool locked;
void Start()
{
Cursor.visible = false;
locked = true;
}
void Update()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 0f; // z is 0 for 2D
// Convert screen position to world position
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
worldPos.z = 0f; // make sure z stays 0
transform.position = worldPos;
//stops working here
if (Input.GetKeyDown(KeyCode.L))
{
if (locked)
{
Cursor.visible = true;
locked = false;
}
if (!locked);
{
Cursor.visible = false;
locked = true;
}
}
}
}
litterally everything is working other than the booleans
read through this logic and tell me what you think is happening in a single frame here. assume locked == true
if (locked)
{
Cursor.visible = true;
locked = false;
}
if (!locked);
{
Cursor.visible = false;
locked = true;
}
the cursor becomes visible and locked is set to false?
let's assume i put a Debug.Log call right after that code, what will it print if all it prints is the locked variable?
remember, read through all of the logic here
think3d it would print either true or false right?
what specific value is it going to print
false
incorrect. read through the logic again
alright gimme a sec
(i'll give you a hint, there are two reasons why that is incorrect)
honestly idk bro
read through the logic one line at a time.
if (locked) //checking if locked is true
{
Cursor.visible = true; //makes mouse visible
locked = false; //locked is now false
}
if (!locked); //checks if locked is false
{
Cursor.visible = false; //hides cursor
locked = true; // locked is true now
}
now that you have those comments there, read through the logic and actually apply those steps in your head
ok
What i want: if locked = true then hide mouse
line 1. if locked is true then do this
line 2. since locked is true set the mouse to visible
line 3. now the mouse isnt locked
line 4. checks if locked is false
line 5 - 6. if locked is false then hide cursor and locked is now true
i might be stupid
since im running on 3 hours of sleep
but i dont see the issue
have you considered continuing through the rest of the code? don't just stop because you think you know the answer, finish evaluating the lines
which of the two issues did you fix though (assuming by "edited it" you mean you fixed an issue)
oh my god bruh
i get it now
its running both lines anyways
i added debug to both if statements and it sets it to false then true
thanks guys/girls
yes because they are independent if statements. your second if statement is also unrelated to the block of code below it, but i'll let you see if you can figure out why that is (hint: your IDE should be telling you that too)
but when i did elseif it came up with an error
that's likely because of the issue i just mentioned
like it didnt exist
is it like else if or elseif
ill try both
ok
@slender nymph is it because i put a ; which cancles the second if statement
ok imma try without it
yoooo
it works now
yay
thank you
What do you need an else if for anyway? What possible value can locked be that isn't either true or false?
its like a door thingy
i mean it as a metaphor
Right so why do you need an else if
instead of an else
oh
What situation could you have where neither code block runs?
yea i see what you mean now
nothing
makes sense
thanks
even better would be remove the if statement entirely because it isn't really necessary anyway. you can set Cursor.visible to locked and then !locked to locked
and that's assuming you even need the locked variable for something else, otherwise you can just toggle the value of visible
im gonna understand this
not right now
but eventually
also it's going to be a pause function eventually so i'll just keep it for now
let's put it this way, you have a variable that is basically serving a very similar purpose to the property on the Cursor class you are changing. at least with regard to your logic, i understand actually changing that property toggles whether the mouse cursor is visible. but that property also tells you if the mouse cursor is visible or not
and you can just change its value each time you press your input instead of checking what the value is to change it to the opposite of that
so i watched this video again, and i think i know how pooling works. so basically you need to setup four methods:-
- a method to create objects
- a method to reenable objects with the right properties
- a method to deactivate objects based on your needs
- a method to destroy objects.
what i don't understand is why is the guy taking_poolreferences insides the different scripts. i don't get it
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
By the end of this Object Pooling tutorial, We will have replaced a projectile spawn setup from a simple Instantiate and Dest...
again, it is pooling not spooling. it's even in the thumbnail and title of that video you linked
sry, i think it's become a bad habit of mine to do that, i just subconciously do it...
specifically from 8:03
whatever he does in the Bullet and BulletSpawner script to set up the pool ain't making sense
just keep watching, he'll explain why later
private bool paused = false;
if (Input.GetKeyDown(KeyCode.P))
{
paused = !paused; // flip state once
// if paused was false now its true
// if paused was true now its false
// now we can do the appropriate thing
if (paused)
{
CursorController.Instance.UnHideCursor(); // unhides and unlocks cursor
}
else
{
CursorController.Instance.LockCursor(); // hides and locks the cursor
}
}```
one trick i learned that makes it simple is to flip the boolean first (before any checks)
and then check with an `if/else` so it only checks once..
but basically it's so that the bullet can return itself to the pool

i believe something like that was mentioned up above as well.. just happened to have my code easily accessible so wanted to show the code.. might give u some insight
so...it's because of this which he does in the Bullet script?
at 17:05
do i need to know exactly how it is that the bullets are getting added to the spool?
something needs to be able to put the bullet back in the pool otherwise it will never end up back in the pool, which of course would mean using a pool is pointless
oh wait, when he _pools.gets(), that's when he creates a copy or smth?
anyone have any idea what this is?
i have only one editor script using assetdatabase loadasync and its in an editor window that isn't even opened. this ones being called once per frame inside of the PlayerUpdate loop
its causing lag spikes even in an ampty scene I can watch the frames drop from 500 down to 85 for half a second then jump right back up
Anyone have a function to take a collider and get all colliders that overlap with the one put in?
what kind of collider
any Collider type
Im using a MeshCollider if it needs to be one type
but a general method for any Collider would work
ah, that's the one that you can't do this for. any other shape would work because of the OverlapXXX methods on the physics class (you don't pass in a collider but it's the same concept)
? Is there no method for seeing if a Collider overlaps another Collider? If so, you could loop through all colliders
that's what the physics methods are for
I wanted Collider not Physics
My object doesnt use physics Im moving is manually
by "physics methods" i mean the methods on the Physics class, the ones that query the state of the physics scene to detect colliders in specified areas
Is there no method on it that works to let me see if two colliders are touching??
not for mesh colliders
are you trying to find out if a collider touches something or are you trying to find out what is overlapped by a collider because those are different things altogether
but yes, there is no method for mesh collider shaped physics queries
I want to know either could work, If I know how to check if two are touching then I can make it check for all touching but I'd rather all touching if possible
what is the point of a meshcollider if it cant detect collision also
how about this, explain what the actual purpose here is so the real solution can be suggested
I want to detect all objects touching my bullet object to damage them
use a raycast
that's not even necessary. just use an OnCollisionEnter or OnTriggerEnter
why if i add a tag to an object it wont collide with raycasts?
That will not work for bullets
why not
They move to fast and they can cross the collider in between physics step
then congrats, you get to use the physics queries previously mentioned
my bullet is just a prjectile it can move slow (like it dodes right now)
Its pretty frowned upon to use colliders and rigidbodies for bullets
im not using a rigidbody
maybe this is stupid but you could raycast each frame to the last position of the projectile
that wouldnt let my projectile have a hitbox tho
i did this in another game engine and worked beautifully but i had to optimize like hell
yeah
If you want to use oncollisionenter the object has to be being moved by a rigidbody
so your options are raycast
you could use a spherecast to """"simulate"""" a hitbox
I thought it just had to be one of them
No the object has to be moved by the physics engine or oncollisionenter will not be called
also when did rigidbodies come up im talking about colliders
if you have two objects in the scene with colliders on them the only way physics callbacks will trigger is if the physics engine is moving them colliders are part of physics
at this point you've already received your answer, physics queries will do what you are trying to do
why is it so hard to detect if two things are colliding
Its not
neither object has rigidbody
i didn't say anything at all about a rigidbody, did i
I thought yall said both needed to be rigidbodies for that to work
that was russell who said that about OnCollision/TriggerEnter.
neither of which is a physics query
In order to call oncollisionenter the physics system has to be moving the bullet. So that means either use a raycast like I suggested or use a rigidbody(terrible way to do it)
hello guys
It isnt a bullet its a projectile
how is that relevant
So i use a physicsquery to detect all collision objects inside of my Collision object
cuz it isnt a bullet??
ok
oh no, someone called your projectile by the name of a different projectile. that means the suggestion won't work
i never said that
like bro atp go back to tutorials
read the docs
idk
use a raycast and call it a day
im just starting to learn Unity do you have any resource recommendations?
or preferably the cast that is the closest shape to the actual projectile
!learn 👇 the pathways on the learn site are good, and there are beginner c# courses pinned in this channel
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks man
Why is something small and fast moving like a projectile using a mesh collider? A primitive is probably better.
or none at all and only using physics queries
And colliders don't really do passive "are these objects touching?" kind of checks. It's an active "I just touched this thing" message.
but yeah, primitive would be much better than a mesh collider in this case, especially considering when you move a collider without using a rigidbody it recreates that collider every physics update
if its moving fast it can move past the collider between physics steps youll have inconsistent hit detection if you use colliders for this at all
If you set collision detection to continuous you can avoid that, but it requires the bullet have a Rigidbody and is much more expensive than discrete and should probably just be approximated with a physics query
does continous totally remove this issue or just make it less noticable?
so...i tried implementing pooling and i am pretty sure that i am very close to it, thing is, i can't get the ducks to destroy
using Unity.Mathematics;
using UnityEditor.ShaderGraph.Internal;
using UnityEditorInternal.VersionControl;
using UnityEngine;
using UnityEngine.Splines;
using UnityEngine.Pool;
public class enemyAni : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
[SerializeField] private SplineAnimate aniSpline;
[SerializeField] private Animator animator;
private SplineContainer containsSpline;
private ObjectPool<GameObject> _pool;
void Start()
{
aniSpline.Completed += onComplete;
containsSpline = gameObject.GetComponent<SplineContainer>();
}
// Update is called once per frame
void Update()
{
if (CalculateTangent() < 0.0f)
{
animator.SetBool("isGoingLeft", true);
}
else
{
animator.SetBool("isGoingLeft", false);
}
}
void onComplete()
{
//Destroy(gameObject);
_pool.Release(gameObject);
}
public float CalculateTangent()
{
float tratio = aniSpline.ElapsedTime / aniSpline.Duration;
float3 tangentVector = containsSpline.EvaluateTangent(aniSpline.Container.Spline, tratio);
return tangentVector.x;
}
public void SetPool(ObjectPool<GameObject> pool)
{
_pool = pool;
}
}
the part of the code which previously(before implementing pooling) dealt with destroying the gameObject was //Destroy(gameObject). now, instead of the script doing the destruction, i set the pool to destroy it when the time is right
somehow or the other though, it's returning
NullReferenceException: Object reference not set to an instance of an object enemyAni.onComplete () (at Assets/Scripts/enemyAni.cs:37)
where line 37 is exactly where the spool decides whether it needs to destroy some objects off or not
using .Release(gameObject)
then _pool is null, meaning you aren't first setting it properly
either you aren't setting it at all or onComplete is running before SetPool
does this mean i am setting pool or not
add logs and see exactly whats happening. i did also write "or onComplete is running before SetPool"
throw a debug log in onComplete and SetPool, see which runs first
actually I just read it closer, look what object you're spawning and look at what you're setting the pool on.
You spawn a duck yet for some reason reference some enemyani that is unrelated to this duck entirely
does this help in any manner?
the Duck prefab present in heirarchy is the gameobject i am trying to spawn. it has EnemyAni script attached to it. the spawner script isn't attached to this Duck gameobject, instead, it's attached to something else
this is your error #💻┃code-beginner message
you just aren't setting the pool on the same object that you're spawning
oh god
you aren't getting the EnemyAni script attached to the duck. Look at your CreateDuck() method
So I’m trying to figure out how lists work and I can’t figure out how to use them to do what I want. Can anyone help me?
1 - I want to make a list of all game objects with a certain tag that are close and in view of the camera. I know how to check if an object is close and in view of the camera when I have a set GameObject variable I can check, but I don't know how to add multiple objects to a list based on that.
2 - I also need to find which object in the list has the lowest or highest x or y value on this Vector3 “Vector3 directionOfObject = transform.InverseTransformPoint(theObject.transform.position);” which is based on their position, and be able to set a “GameObject” variable equal to that object.
This script is connected to the camera
every time i tryto configure VS code it doesnt work
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
i linked to troubleshooting steps for you to take
they will work provided you actually followed the steps to configure it
don't you want to link the VS Code ones ?
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
tt
next time you should actually read the page instead of immediately dismissing the instructions without looking and you could have seen it was wrong yourself 😉
follow the troubleshooting steps
in this server
ill send u all the screenshots
its external
i got the thikng
have you gone through the troubleshooting steps at the bottom of the page that was linked
i deleted scripts with compiler errors
//Instantiating a new duck GameObject
GameObject duck = Instantiate(Duck, Duck.transform.position, Duck.transform.rotation);
Debug.Log("Before setting pool.");
enemyAni enemyani = duck.GetComponent<enemyAni>();
enemyani.SetPool(_duckpool);
Debug.Log("After setting pool.");
return duck;```
so i added this, and the error did seem to not come up but then something really weird happened
C# and C# dev kit are both newest version
i have th .NET sdk 9
but it does say this every tim
ms-dotnettools.csharp: Trying to install .NET 9.0.11~arm64~aspnetcore but it already exists. No downloads or changes were made.
visualstudiotoolsforunity.vstuc: Trying to install .NET 9.0.11~arm64 but it already exists. No downloads or changes were made.
why is it arm64?
because im on m1
@eternal needle like bro what, space makes ducks spawn
@viral magnet
bro i dont think I can help you
i cant even code cuz my visual studio aint working
i think the ducks aren't being reactivated and that's the issue
you doing pooling? 🤔 send your duck code
add more logs until you figure out whats happening exactly. Follow the docs example as well
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Pool.ObjectPool_1.html
this might be a bit rude of me, but check my previous posts...if you still have further questions, then ping me
its not rude but i am not that invested so i think ill pass unless something comes up i can explicitly help with lol
aight, i am checking stuff out, currently i have a theory as to smth related to start and update nto working correctly
us staring at a video isn't productive, especially when we can't see the full context like when you press space. (nor does anyone want to really go through that).
You should gather the information you can. The only thing I will note though is it does look like the ducks are set active right after being set inactive
so are there errors, or its just not doing proper syntax highlighting and autocomplete
ya, the ducks which do become inactive become active but they don't get animated on the spline
it just doesnt give me unity ket terms
should i downlkoad any of these
so like if I press g
it doesnt give me game object or aything like that
it just gives me global
wait a sec, you can't see the debug log pressing space O_O
ahh shiii, discord doing discord stuff
well I do see a log for it. it's slightly hard to read considering collapse is on so we can't see the order of the logs. Either way, no one wants to figure out your code flow by staring at a video. This is information you need to provide
oh understandable
id really just follow the example closer on the object pool docs, assuming your spawner logic looks different. the screenshot you sent doesn't show most of the methods used in the constructor of the ObjectPool
can anyone good at VSC help
maybe check out microsoft's discord or vscode's discord, they might be able to help you
with what
have you done the instructions i gave
i did
😭😭😭
i told you
i did it yesterday too
i sent you all the screenshots with al the instructions
my C# dev kit doesnt hve any output
i think i might have an inkling of what the problem is. So basically when an object on a spline reaches the end of the spline, OnComplete() gets called once. but what happenss if the same object were to reach the end of the spline, then because of the pooling, it became deactivated and then reactivated. i am assuming, that since it already passed through the spline once, its spline animate isn't gonna work again because it's not in a loop mode...instead, its just a one time thing...
so even though it gets enabled, its spline animate doesn't work because it has already been used once
holy moly big brain moment

@eternal needle @slender nymph @solar hill thx for helping
Hello,
I am not able to enter the answer to this equation which is a part of my game , Can someone help please
Hi I'm wondering if there's a way to make this more optimized as my game is running like a potato I think the main cause is the animated wheat being copy and pasted and maybe a way for the scene loading to be faster
Video isn't displaying correctly
visual studio code is the worst coding platform ever
Good afternoon. I am trying to follow a 2D game tutorial and am having trouble with a tile palette. On the tutorial video, the person added a tile to the palette and it filled the entire grid. However, when I add the image, it only fills up a tiny portion of the grid. Does anyone know how I can get that grid tile filled in? I am on the latest Unity, and the tutorial is from 2022.
I can supply the image png if necessary
would be a lot more helpful if you just linked the tutorial
well since the video isnt working, we cant really help but you should use the profiler to diagnose any performance issues yourself
change the sprite unit
the video still isnt playing, at least for me, but what i said earlier still applies...
"you should use the profiler to diagnose any performance issues yourself"
oh i will see
also enable the stats in game mode
Here is the link
https://youtu.be/_24TfxaPWlI
You want 27:43 timestamp or so on the video
An Aussie's full guide to following the "RoguelikeDev Does The Complete Roguelike Tutorial" challenge!
💰🔗 Feel like Supporting Me 🔗💰
ᐅ Github Sponsor
https://github.com/sponsors/Chizaruu
ᐅ Patreon
https://www.patreon.com/thesleepykoala
ᐅ Unity Store Affiliate
https://prf.hn/l/WoLYBoQ
🔗 Relevant Links 🔗
ᐅ Unity Hub Do...
no, just change the sprite pixel unit
Please elaborate
if your sprite 10x10 change the thing to 10
probably 10... just like he did in the tutorial
ten billion idk
Thank you. That is one mystery solved. I have not fixed the original issue of the fog-of-war not truly working, but I can remove the fog png as a possible cause
Hi, working on a retro shooter. The tutorial has everything in 3-D. Though the goal is to have billboard sprites for enemies and projectiles just not sure how to swap out the 3-D model with a billboard sprite?
Letting folks know, I resolved the problem. I was using an incorrect range in a for loop (typo while following the tutorial)
Just replace them by hand..?
replace the mesh renderer with a sprite renderer
thats about it
is this good for day one progress on scripting? idk i feel like there should be more
its very slow at first but once you get over the curve it gets faster
tuff
i see people making games in like 1 month or sum and it looks good but its prob cuz they use premade assets
i use premade assets but its because i cant draw for crap
what net and sdk sould u use for rider and unity
!ide Just follow the install instructions you've been linked to several times already.
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
Hi, I'm using this script to play an audio (using On enter function in insepctor) whenever the character enters a trigger area. It plays sound fine, but problem is, it also plays it when I exit it.
Further, if I assign a function on On exit, it doesn't work.
I am following Prototyping tutorial from Unity. They said if you don't know coding yet, you can use these scripts which would work without any changes.
Is there something wrong with code? Or maybe I'm doing something wrong.
I've IsTrigger checked on for the trigger box:
OnTriggerExit event is never invoked anywhere.. Both on Enter / Exit have the same onTriggerEnterEvent invoked
Thanks! It fixed both issues.
Unity tutorial scammed me?
which tutorial is it ? can you send it
The scripts are included in this project (unfortunately you can't see it without downloading). In Step-2. https://learn.unity.com/pathway/creative-core/unit/prototyping/tutorial/get-started-with-prototyping-3?version=6.0
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Then later, it says:
We have also created the following three custom script components, which you can use alongside the character controller to handle different interactions. These will give you some flexibility so you don’t have to choose the exact same interactions that we did.
The script I'm using is part of these 3 scripts included in that project. They themselves didn't use it in the project, so maybe not enough users noted the issue.
This is a screenshot of that sample project. I can see that issue here. Looks like the person who created this simply forgot to change that particular statement.
strange..
Yeah. I would have never solved it unless I had started learning basic coding. It confused me for a full day.
I'm almost done with Creative Core tutorials. After that I'd learn some basic coding.
Prototyping is the last tutorial series in that course.
The tutorial does not seem to specify the expected behavior
So yeah, take some time to understand how the code should work as u intended
yeah probably good idea especially the junior pathway, wouldn't hurt to also look up traditional c# tutorials as well.
sticking to the microsoft site mostly, stay away from scammy / poor quality courses on places like Udemy
but yeah that mistake slipped through the cracks, someone rushed it out ? who knows..
so im just getting started in learning how to code C# in VS 2026 and im following a tutorial from 9 years ago... is there a reason why the references page looks so different? im not sure if he wrote the namespace stuff himself or if it just looks different because of the versions
not to mention im missing "assemblies" from the solution explorer
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
U have all sort of things on discord. Just have to do ur research
Is this official or "well-known" C# server if I want to join?
I mean its server link is called "csharp", its got 60k members, and it went up in 2016 so i would say so yeah
Though if your question is a code problem in unity i would recommend just asking here
Since unity has many of its own libraries
my code looks fine right? there isnt anything out of place ive looked multiple times and im having an issue where the animation gets stuck on the last frame after just 1 click
is your exit target in your animator set correctly to exit the clip?
I'm pretty sure I have a video in #🏃┃animation hold on
lets try not to cross post
So from the video, it looks like your animator setup is correct. Are you sure, your atk gets set to false? I do not see any debug.Logs in your code, that would help you to know whats going on
@midnight plover this is what happens
it apprently doesnt turn attack 1 to false for some reason
Maybe you should try to use triggers instead of bools to trigger an animation
yeah ill try that see if that works
Let's say I have a complex mesh with a mesh collider and a hole inside.
Can I do a sphere/box cast and create an object with a collider shape of the mesh collider, but only inside those bounds? Or just get the collider somehow without making an object
that actually work
thank you so much dude! i love you lol
Used Cinemachine FreeLook for my project and its good but because the player movement script uses Input.GetAxis and transform.Translate to move but the jump code uses Rigidbody.AddForce.
And because of that the player jitters when jumping if the Cinemachine Update method is using Late update. And if i change the update method to fixed update player jitters when moving. I managed to"""fix""" this by setting the Update method to Fixed update instead and putting the movement code (Input.GetAxis and transform.Translate) in to Fixed Update()
I was wondering if its bad putting the movement code (Input.GetAxis and transform.Translate) to Fixed Update()
If the movement has Physics related, it is legit to put in FixedUpdate
Fixedupdate was made for physics. it's ideal to use that for physic related code.
It behaves differently then update in more then 1 way as well, if i recall.
you'll have less problems using the correct one for their intended purpose
Input.GetAxis is somewhat bad to put in FixedUpdate. input is framebound.
you're using transform.Translate on a rigidbody? that's wrong, you'll be fighting the rigidbody and you'll have desyncs
the jitter is probably from that
input should be taken on Update
continuous input (ie "is x held down") could be in FixedUpdate
addforce should be in FixedUpdate
instantaneous forces could be in Update
hi
can anybody help with this error message
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKeyDown (UnityEngine.KeyCode key) (at /Users/bokken/build/output/unity/unity/Modules/InputLegacy/Input.bindings.cs:418)
Bird.Update () (at Assets/Bird.cs:17)
i can provide my script if necessary
i think its because im using legacy code
you are basically using "Input.GetKeyDown" or similar, but you are using the new input system. So you have to use the syntax and code for that
yep
so whats the new input system
can you tell me pls
i swtiched to input system package to both
Google will tell you for sure
i switched to both
does your playersettings say both?
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
Is my code correct? I just learned it today. Sometimes player can't jump...
!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.
Move should only be called once per frame.
Thanks 
!collab
: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**
why?
why what, exactly?
are you developer?
no, ive never coded in my life
lmao
Happy thanksgiving everyone! May your bugs cease to exist 🦃
I have made a small unity project for my college submission, but when my friends try to download the exe from the google drive, It shows an error, UnityPlayer.dll Not found... How do I fix this?
is that a coding question?
Look I didnt find any other channel that specifically targets this error, Would appreciate if someone helps though
Hey,
I have downloaded unity like a hour ago and started following a tutorial to get to know the basics and in the tutorial they used addforce to a object to move it left and right but when i press D the force does not get added. has there been a update or something?
this is what your game build should look what the console says? also i think is because you are using a deprecated version of the input system
to make sure it works add a " print(Input.GetKey("d") " above the if statement to check if the input is really the problem
ahh i get this error
yeah thats what i thought
Are you using the old input system? Also acquire input in Update and evaluate it in fixed update
I think i am
you should switch to the new input system instead, but it takes way longer than you think
Is there a tutorial about how to use the new input system?
ill send you the one i used
Alright
whatever tutorial you are follwing there, please stop wasting your time with it
they are not even making use of Axis
Its a tutorial from 8 years ago 💀
yep i can see that
i´d highly recommend you learn the new input system instead, along with how to use axis
https://www.youtube.com/watch?v=ONlMEZs9Rgw this one explains everything about it, its very useful for me and the guy explains it very well
In previous videos, we've already talked about how we ditched Rewired in favor of Unity's new input system. In today's video, Thomas goes over the basics of the new input system, and how you can get started with it on your own.
Timestamps:
00:00 What's an input system?
00:28 Why not the old?
01:29 Setting up movement
09:47 Setting up actions
1...
Alright
I am studying software development and next period i am going to learn game development in unity so i already wanted to take a look at it and learn a bit.
sounds cool.
actually same, i always wanted to make an unity game but i was 11 the first time i used it, and my english want good either, so i learnt Roblox studio for 5 years and now im here
is the new movement system default or do i need to install it like the video?
you need to install it
Alr
You're in ISO view, click the button under the transform gizmo at the top right.
What is iso view could you pls explain in simple words ?
how do i add delay to the code?
It's an orthgraphic projection where there is no depth.
It's useful, in this case, for aligning things.
like Sleep() or Delay()
You either use a coroutine which lets you yield to time, or you track time in your Update function and do something when it surpasses an amount.
so i should stick with time1 - time2 if i dont want to use coroutines?
anyway im gonna check what are those
I don't know what time1-time2 means, but if you don't want to use a coroutine, then you need to track the accumulated time manually yes.
something like this. btw i cant use coroutines in the Update functions, and because i lack of intellectual skills i will stick with this method. thanks anyway as ill learn how to use those in future
By the way, if you're using time to buffer something like that, that's going to be bad news in the future.
Why do you need to wait 3 seconds to start the game, for example?
i just made this example to show you, i dont really know too
i really didnt knew any other way and i used this method in other game engines, as some people said this was an accurate method
so i just get used to it
Another would be to add Time.deltaTime to a float in Update, and check if that exceeds your target duration
Time.deltaTime is the amount of time spent in the last frame
Hi, I need help. I’m making a cleaning game, and I’ve projected stains onto the ground using a Decal Projector. However, I don’t know how to clean them realistically, like erasing a drawing inch by inch so it actually feels like cleaning.
I tried using Shader Graph, but I couldn’t figure out the correct way to implement it, and I ended up failing. Can someone please help me understand how to properly create this cleaning mechanic?
Thanks in advance!
this isn't something i've done myself but i'd imagine you'd really just want to SetPixels on the texture of whatever object you're cleaning. this should fall under anything "drawing on objects" related when googling
Okey I try this thanks
Hello, I’m having an issue with the playable director. I have it set to after one playable director finishes playing, another one plays. But the problem is that for some reason, the wrap mode for one of them keeps setting itself to hold in play mode. even after I set it as none in the editor.
hey i am making a multiplayer prop hunt game in vr on unity does anyone have like a tutorial or code or smthin or maybe make a video on how to
like a tutorial for the full game?
like of how to set up like a prop hunt gun
you could raycast to an object and then copy its mesh and size
I am looking for a way, that if a metor hit the objects, that the objects moves faster away because it just looks more realistic. but idk how to do that. please help
https://paste.mod.gg/hwnjekldyzfv/0
A tool for sharing your source code with the world!
you could make that the collided objects will fly away to the same direction of the meteor and that object, and then multiply the velocity by the meteor magnitude
also just for curiosity, are you willing to make this multiplayer or a sort of simulator?
how would i set that up
do you have a snippet?
i will prob make this multiplayer soon
a piece of code
ive only started recently
btw you should create a raycast hit variable, then do an actual raycast and store that in it (by doing Physic.Raycast(position, direction, out variable).
then get the game object and from here get the material/ mesh component
if you dont know how to code it then you should look for both raycasts and components tutorials
what should i search to find the right tutorial
components are a bit generic so any tutorial (even about specific things) should be okay, and for the raycasts just search a raycast hit tutorial
when i watched a tutorial it mostly just talks about using it to make wall collision
This requires years of experience..
um you shouldn't make movemnt in this way like this your game will be cooked use the new input system or use input.getaxis("Horizontal");
Yeah already did that
But thank you
oh okay great job but fact never give up whatever you stuck with ask me or anyone you know here because unity is not easy + do a tutorial game found in youtube do 2 of them then start with simple games untile you start with you dream game and learn more while you are working
i am now trying to add a animation 💀
need help ?
Maybe layer i wanna try first
Who should I contact for help?
!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
or you can use C# DateTime
DateTime startTime = DateTime.UtcNow;
TimeSpan diff = DateTime.UtcNow - startTime;
if (diff.TotalSeconds > 3 )
{
// your magic goes here!
}
Been playing with rigidbodies and could use some info on some things.
-
In real life, static friction needs to be overcome for an object to move. As far as I can tell, with a high mass rigidbody with a super high static friction value, it still moves when pushed by another object, albeit very barely. Maybe that's a code issue on the pushing side of things? Not sure, the static friction values are stupidly high rn.
-
What goes into creating different speeds of descent from gravity with rigidbodies? I can have two objects with mega different masses and they fall at the same speed.
anyone know to get rid black box that deletes letters after i backspace
insert key toggles that
thanks
Insert key takes another life
Anyone know what clampmagnitude does because i can not understand it.
it "clamps" the magnitude (the length of vector) to a certain number
its doing some" heavy lifting" math for you
all in relation to Pythagoras, trig and unit circles
Vector2 v = new Vector2(4, 4);
Vector2 r = Vector2.ClampMagnitude(v, 2);
// r ≈ (1.4142, 1.4142)```
so like it normalized then x max
My god insert key bullied me for about a year of on and off existence before a friend noticed i had it on and called me insane and i was like idk how to turn it off/on it just happens
is this a efficient way to learn c#
- See something i want to make
- use tools like youtube, reddit, chatgpt
3.remake the system but don't use any tools and go by memory - when i get stuck i focus on learning that specific thing
- repeat
use tools like youtube, reddit, chatgpt
not really, everything else should be acceptable
I roughly do that. I come from a modding background, so having the ability to sit down and look at existing stuff is really nice. From there, I try to piece together how it all works and customize from there
Usually with chatgpt responses, the final script is completely different because of my own programming preferences. Occasionally it spits out something that I like first try
wdym
don't use tools?
youtube is ok if you find right courses.. but mainly you should avoid reddit / gpt (its mostly where it scrapes data anyway)
yea i only use chat gpt to explain specific things like "how to make a raycast" but not an entire script
ok what about like just looking up how to use apis and stuff, what would be the best place for that
google / research, filter out your results to confirm accuracy
don't blindly trust what a chatbot spits out
when you mean filter do you mean trying to get the same answers from multiple sources
yes
ok cool
im just learning how to script enemy ai now so i'm getting into the deep side of c#
and i want to make sure i learn the right way so i don't need to struggle learning better ways in the future
what you mention doesn't sound c# specific, there is a distinction between Unitys API and C#
C# is the core language, unity just uses it for api to talk to the c++ engine
so like how luau (roblox) is to lua?
ehh makes sense i guess
If you wanna start really basic, start with just some sort of MoveTowards for the enemy ai. Don't account for obstacles. From there you can dive into navmeshes, raycasts, etc.
ok thanks
I think there's literally a MoveTowards function for transforms right?
i'm just doing a binding of issac remake prototype for now
i'll look and see maybe
SAME XD. Trying to get the movement right. It's kind of actually deceptively hard to implement in unity
Since there is some physics to his movement
hmm not sure I would exactly say that cause its considered a seperate language even if dervied from lua
might be unoptimized but i just used input.x and input.y
so like more tamer than luau is to lua
there is no "unity c#" only specific concepts of unity like Gameobjects etc. but its still c# classes and all
if you want to know c# properly use something like microsoft learn site or others like w3schools. Break down the bigger /specific problems into simpler to solve generalized ones
and always check Unity docs for unity specific things
The issue I'm running into is that enemies can push him and vice versa, which calls for a rigidbody, and yet his final movement in normal scenarios leads to a final top speed, which a rigidbody fights against due to how gravity works. Could just turn gravity off tho
alright
yea i just turned off gravity cuz i don't want to deal with the harder ways of doing a top down
Oh did you do rigidbody too?
i'm currently trying to figure out how to change public varibles from a raycasthit2d
i think lemme check
like
shoot raycast and edit component in whatever the raycast hit for damage and stuff
yea i did rigid body dynamic and just turned off gravity
thats what literally Get/TryGetComponent is for
Ah nice, sounds like my head was in the right place after all XD
Kept dancing between that and a CC
i will look into it
the raycasthit gives you the collider of object you can search that component on
great minds think alike
alright thank you
i'll come back once i get this working
Hello everyone, i was just completed building my unity project but mistaakenly i deleted few files which contained the Materials files which are supposed to give colors to the object, can someone please help fixing it
this is not a code question
dont crosspost
wrong channel but deleting a file cant be restored
got it working thanks
void Shoot () {
Debug.Log("Shooting raycast...");
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, 1f);
if (hit){
Debug.Log("Something was hit");
Debug.Log(hit.collider.gameObject.name);
GameObject hitObject = hit.collider.gameObject;
Enemy enemyScript = hitObject.GetComponent<Enemy>();
if (enemyScript != null) {
enemyScript.CurrentHealth -= 1;
Debug.Log("Enemy health: " + enemyScript.CurrentHealth);
}
}
else {
Debug.Log("Nothing was hit");
}
}
}
ill change the music eventually
sure not a bad start, some of the code is redudant
hmm let me try cleaning it up then
if (hit) {
GameObject hitObject = hit.collider.gameObject;
Debug.Log($"{hitObject.name} was hit");
if (hitObject.TryGetComponent(out Enemey enemy)) {
enemey.CurrentHealth -= 1;
Debug.Log($"Enemy health: {enemy.CurrentHealth}");
}
}```
ts doesnt exist
delete it before i read it
the what now?
the code
it was a joke kinda
im trying to figure out how to optimize it myself so im not reliant on other sources of code
hmm.. as long as you didn't use gpt to write it in the first place
no bro
only a yt tutorial on raycasts and unity docs
the links you sent
just wanted to point why those changes might be better afterwards thats why.. it could be self explanitory but importantly try to avoid for example redudant / writing things twice
ok im almost done and ill show you
whats the prob?
you should probably clarify whats expected vs whats happening
also wassup with those very specific decimals 😵💫
he might be making his own pi or something
also is this good optimization?
void Shoot () {
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, 1f);
if (hit){
Debug.Log("Hit:" + hit.collider.gameObject.name);
Enemy enemyScript = hit.collider.gameObject.GetComponent<Enemy>();
if (enemyScript != null) {
enemyScript.CurrentHealth -= 1;
Debug.Log("Enemy health: " + enemyScript.CurrentHealth);
}
}
else {
Debug.Log("Nothing was hit");
}
}
}
looks the same to me...
just study the one I sent and then compare
ok
sure you don't need hitObject but the point was not to repeating the thiing twice in both the log and access component
what does the dollar sign do in Debug.Log($"{hitObject.name} was hit"); and Debug.Log($"Enemy health: {enemy.CurrentHealth}");
thats important, so when you change one you don't have to remember to change it at every spot, thats why variables exists
its called string interpolation
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
avoids having to use + every time you want to add variables to strings
Type myInstance = gameObject.GetComponent<MyType>();
if (myInstance != null)
//Code using myInstance
and
if (gameObject.TryGetComponent(out MyType myInstance)
//Code using myInstance
do the exact same thing btw, the latter is just a cleaner way of writing it
i want a script which can follow my target and when i press right mouse button then my camera moves to the face of my obj (like in fps shooter game, we aim by pressing right mouse button ) but it is just following my player and when i press rightmouse button then it just flickers
ok last question, i understand the first one, but what does (out MyType myInstance)
do? i know ur defining varible but idk what the out has to do with it
ButtonDown is a one frame event
you are like teleporting a camera each time you press and it pressed done
It's like a return value.
Out parameters for functions can be used in the code of the caller.
out is basically useful when you need more than 1 value returned by a function without changing return type
so it merged the defining varible and the if statement lines so now nothing else matters except if the raycast hit the varible
the function TryGetComponent returns a bool, so if it found it puts the component in a variable through the out

ok this is valuable information
thanks guys
im gonna figure out how to do enemy movement myself with MoveToward but thank you for helping me understand stuff
might wanna start look into navmesh 2d by h8man or learn basics of a*
or use A* pathfinding project
MoveTowards works for very basic things and usually teleports through solid
or gets stuck if you got rigidbody on it
then what do i have to do ?
still not sure why you want to move the camera, fps usualy dont move the camera to aim
rotating mainly
aight
ummm i guess you dont get it , i want to make smtg like when i click RMB then camera changes its position on my desired place
i guess it is simple explanation
camera is following my player
it moves but the next frame is going to go back right away
it happens quickly
KeyDown happens in 1 frame
then runs else right after
see this
then what do i have to use to make it like when i click RMB then it just goes to my desired camera position ?
its doing exactly what I described lol
yeaaa
its going to your position
thats why it helps to explain it better what you want to do
if you want it to stay there then you cannot use that else statement on the next frame
but again hard to tell a solution if you don't explain what the mechanic is here , it may even exist a better way than whatever it is you're doing now
i want my camera to summon on the "X" given in the image whenever i click RMB and switch to its normal position (where it is following the object)
use GetMouseButton instead of GetMouseButtonDown so that it lasts as long as you hold the button instead of just the first frame
if its supposed to be a toggle then use a bool and make GetMouseButtonDown switch its value
ok i'll try
Is it worth using Cinemachine for a first-person view? I want to smooth the camera, and it seems easier with it.
yes
Alright, I give it a try 😄
only thing scares me is i have to use an empty game object as target
Curious of the times where people would recommend not using chinemachine its a full system to control the camera and you dont need to do anything
Its like with everything, that is pre setup to cover a lot of control, you can get a hard time to get special behaviour out of it. Like with every package, there are pros and cons on how much you wanna be tied to that system.
i wanna learn cinemachine but i want a proper guide to learn it . i guess it is used by everyone now and i have to learn it now ,
Arent there some tutorials by unity directly? did you check the learn page?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
nope , does it have special section for cinemachine?
Imagine there was a search engine on the web... https://learn.unity.com/project/working-with-cinemachine-cameras-2019-3
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
wait....what.....its whole damn tutorial and im here crying about it and experimenting
It might be outdated at some points, but should still be valid for most parts
hmmm outdate is just the changed its position on UI , lol
there's quite big changes between cinemachine v2 and v3
after doing research i found out making my own GUID for asset referencing is still the best solution, because its very stable and compatible, so im heading back to my own custom GUID system again
this is more of an editor UI optimization problem, how can i automatically generates the string (or key of the dictionary) when i try to add element on inspector?
because by default it wont generate itself right?
OnValidate?
just to be sure, this "new List<>()" doesn't cause any data leaks, right?
collider2d.Overlap(new List<Collider2D>()) > 0
apparently the Overlap function doesn't work unless I add that
yeah, but why not have it as a member so you don't have to construct a new one every time
I just didn't have any use for the results so I added that as a temporary workaround
fair enough, i guess
Is it "better" to just have it as a member?
Hi I have small problem understanding unity, we got an app made in unity from different comapny. I have an template of a dropdown list, I see it's posisitoned around center of the screen and it has anchor to top center of it, but dropdown renders in the top of the screen not the template. Doesnt matter how I change the anchor, dropdown always renders in the same position
I can see that instead of top being 1450 its bottom 1450
Set Dropdown Template's Pivot Y = 1 (top) Reset Anchored Position Y to 0
Anchored position is 751 right?
that's fine, Now just move the whole DropdownObject where you want it on the canvas and test it
It still goes to the top. Maybe Ill show my hierarchy
Dropdown is deleted from the scene the second I click outside of it
And is created when I click Input 4
I guess pressing on Dropdown visible under Input 4 creates new template
GameObject* based on the template
Okay, I had to put template under this Dropdown and play with Y and Pivot, thanks a lot
But now I have different issue, every now and then Unity shows loading bar, after it it shows pop ups like if it just opened (MCP server and some package info) and it crashes my app with these logs
@sour fulcrum Enemy enemy = Instantiate(creeperPrefab, creeperSpawn.position, creeperSpawn.rotation, transform); activeEnemies.Add(enemy); enemy.BeginCreeping();
the creeperPrefab is assigned via inspector
this is how you post c# snips on discord btw
I double click on the prefab that's in that field, and its walkSpeed is 0.6f
debug log creeperPrefab's walkSpeed before the instansiate line
and debug log enemy's walkSpeed after the instansiate line
well something is up with this statement
gives prefab override energy related stuff but you'd have to provide more screenshots etc. if you need help narrowing it down
I changed absolutely nothing other than removing the prefab from the inspector, and re-adding the same prefab from the project window to it
And now it has the correct value of 0.6f
Do changes made to prefabs not take effect unless you remove and re-add the reference? I thought the whole point of prefabs was to not have to do that
where can i ask for help?
that is not something that exists no, what your experiencing for some reason is unexpected behavior
That's why I was confused haha
(as in something you've done has caused this accidently, not that its a unity fault)
can't say forsure what happened
but simple debugging like this helps narrow it down fast
?? please im desprate XD
Yeah, I need to debug things more, tyt
You need to ask a question, not bait people into helping you.
sorry
im like really new and need some help, my 2d player keeps spinning when it goes into walls
how do i like stop that
colliders, and possibly freeze that axis rotation if not needed
TYSMMM
Hi
"Hi there! If you’re looking to update a Gorilla Tag custom map, I can definitely help point you in the right direction. Adjusting textures and repositioning or removing scene objects is a normal part of polishing a level, and it’s great that you’re focusing on the visual and structural details.
Before you get started, make sure any work you do is within the game’s allowed modding guidelines and only used in approved custom-map environments. If you’d like feedback on your map layout, texture choices, or general workflow, feel free to share what you’re working on. I’m happy to help with guidance and best practices."#💻┃code-beginner message
is this ai
It is indeed IA 😂
guys i want to switch my camera in between by pressing a specific button with using cinemachine in my 3rd Person shooter game . how to do it?
help please
you can create a custom script which switches between em'
i did but i wanna learn to switch using cinemachine
Why cant i move this file?
it might be locked by another process
click Cancel, then try moving the folder again from the Project window, not from Windows Explorer, maybe3 it will help
that is in Unity, not windows explorer
my move tool has theese arrows, how do i make it move freely again?
like the X and Y arrows (im working in 2D)
what?
like its
idk i pressed something now it uses those arrows where i have to go updown then left right instead of moving the sprite freely anywhere with my mouse
look for toolmode toggle or check gizmo
thanks
Hello, im making some UI for my game, and am trying to put a shadow image beneath the ui button, but also be a child of the object, how can i do this?
yay!
this is unrelated, but while coding in unity, i randomly get this thing where when selecting, it replaces the current character ive selected, instead of your normal add a letter next to it, anyone know what im tlaking about?
i don't get it
Press the insert key to switch it from overwriting the character . . .
above the arrows on the keyboard . . .
yes, it's not unity-specific. just normal . . .
is it normal for rigidbody objects to float above the ground? Because my player is like half a unit above the floor and it really messes up the game because I don't want my player half their height in the air
You'd have to explain what you mean by that . . .
I think my raycast was too long
So then whatever you're doing to detect the ground is probably incorrect
my playet thought it was on the floor oops
i think your colliders are slight bigger
yes thats what I said
now I must figure out the mystery of why in the world my player is bouncing... do the physics modify the force when an object hits a floor or wall?
physics material maybe
How do I change that theres nothing mentioning a material on this rigidbody thing
its a separate component aint it
no?
what are you even asking?
The Physics Engine looks at the Physics Material attached to that Collider
ohhh tehre it issss
Have you checked Physics->Contact Offset?
no bounce, and yet my player still boUNCESSS
i fixxed that, my floor detecting raycast was half the player too long
If this again happens only with your custom gravity code and not with the default setup then it's again something you've done wrong in the custom code
I removed custom gravity and friction altogether im gonna let unity do that
I STILL BOUNCE I SET BOUNCINESS TO ZERO WITH MINIMUM BOUNCE??? WHERE IS THE BOUNCE COMING FROM??
also friction is at 99/100 WHY AM I NOT EXPERIENCING FIRCTIONNNNN
this isnt scripting
gonna go to the physics channel
did you restart your pc and asked nicely?
|:
How are you moving the character?
That doesn't answer the question. By which method are you making the character move
Are you setting velocity, using moveposition, or add force?
or something different entirely?
moveposition
So, you're giving it a specific position to move to every frame. Are you factoring in friction into that math?
no
So that would be why you're not getting friction
I use the material's friction
Teleportation notoriously does not respect the laws of physics
If you want realistic physics, you're going to need to use realistic movement, meaning AddForce
Oh ok
so far my movement doesnt work ): im gonna get that fixed
and then everything ekse
its my friction isnt it
use a proper physics based movement
I am
MovePosition exerts forces, but doesn't respond to them. It's so you can have a more specific point-to-point control while still being able to push and collide with things
Yeah, that will let you get some friction from the object that you're colliding with
yep 👍 now I need to make my player actually nice to control
especially mid air
I want the player to have a lot of friction but for friction to almost fully go away when I am trying to move
what is wrong with my code ? why it is not working?
could you tell us what pdf means
oh im sry it was my mistake
and now tell us what is not working.
i want my camera follow my mouse and i have made this script(mentioned above) but is is not working
someone help please
you need 2 floats where you store your axis value and then add the Mouse X / Y to them
!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.
is this to help me?
Xcursor and Ycursor is storing them and they are floats
you override them every frame
yes, you should provide code properly
should i paste it here in this chat?
or wht
formatted properly, sure. or, since you're asking about quite a large chunk, see the "large code blocks" section
i clicked one of the link and pasted my code there and now?
so im making this galaga "remake" thing for a school project-like thing. any idea why the projectile prefab only spawns like 1/15 of the time when i press the button to spawn it? (movement.cs is for the player character, being where the projectile spawns at, and bulletmovement.cs is pretty self explanatory
ill try to record it in a sec
clicking as fast as i can here
you have the user Input inside FixedUpdate, that should be the reason why your Input is not being detected every frame
code's probably pretty messy as its basically just a concoction of code from different tutorials but yeahhhhhhhhhhhh
movement script works fine while also being in fixedupdate though, where should i try moving it?
movement also doesn´t work fine but you just don´t notice it because it is not as frame dependent as the instantiating method. You´d change it to Update() instead
so changing FixedUpdate to Update, or making a new group or whatever its called?
Sir is this fine now?
we need to see the whole script as code
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
pasteofcode is cool
i dont know how to use
is there a good way to apply friction on my own? with code? I want to make it so I slow down faster when I stop walking
just click on the link slap your code into the empty field select c# and paste, then share the link
yeah kind of but it is confusing that you use 4 floats. you only need Xcursor and Ycursor
Xcursor += MouseX
Ycursor -= MouseY
how do I apply friction with code
and multiply theem with a sensitivity float of choice
with the king float which is in your case 1 and doesn´t make sense but ok
do i have to do this rather than, yak += Xcursor;
yawn += Ycursor;, it is more efficient?
yeah declare these 2 floats at class variables as you have yawn and yak
you want to keep these values outside of update method
like Xcursor += MouseX * 4f; (for example)?
for example yes, but i used pseudo code, do it right
i didnt get your these things you said (my english is weak , sry)
okay sir , i will try
can you show your current code
it is same as before , i didnt change anything cause im understanding by you first
A tool for sharing your source code with the world!
still take it (it is same)
is there a way to make my horizontal movement be capped
what do you mean by capped?
sir ive a question that why did you do [ Xcursor += Input.GetAxis("Mouse X")*king;
Ycursor -= Input.GetAxis("Mouse Y")*king; ]? like you did += in mouse x and -= in mouse Y
reason?
so you can store the value and add current value to it
ummm i guess i need a tutorial just to undrstand this " += and -+ "things
is it working now or not
also these are c# basics
myFloat += value is same as myFloat = myFloat + value
nope
do you have any errors in your console you are using the old Input class
camera is following but not moving as we want
nope i have changed it to "both "earlier
yeah but we did not touch any of the moving code , you only wanted the rotation
why not use cinemashine actually
X+=Y means X=X+Y
yea and given code by you is not working too
you said it is rotating so it indicates that it is working
i want to use cinemachine but it is too complex for me to understand or you can say that i dont have anyone to teach me or guide me towards it , i tried it before too but i had hard time doing what i want from it so
take a look at cinemashine it is really powerfull
i have seen people using cine so easily and when i get motivated and when i open it , it looks like a mess to me so my brother and one other person on different server suggest me to do it using code
also while im here, how do i make it so the movement is at a constant speed instead of accelerating when pressing down, and deaccelerating for a bit when pressing off?
trying to make the movement more accurate to the original
!code Elate
📃 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.
the movement code is attached to the message i replied to
oh wait i should probably post the updated version
you are using transform.position this is not the right way to move your gameObject, you´d have to use physics based movement instead
heres the updated version that also has void Update now
how do I multiply only the x of a vectorrrrr
thanks
suggest me some guide for the cinemachine
use a new Vector3 feed your values in and edit the x
it is really hard and complex for me to understand
#🎥┃cinemachine it is time to switch the channel
there are guides and documentation pinned in #🎥┃cinemachine
Vector3 v = new Vector3(1f, 1f, 1f);
multiply just the X value
v.x *= 2f;
v.x is the X part
v.y and v.z stay exactly the same
ig taht is how it is done
why is this code not working??
where do you call the Move() function from?
!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.
btw, thats just (1) piece of the puzzle.. it has the methods you need like the Move() function but it isn't called within that script..
looks like Brackey's 2D Character Controller script.. (he creates other scripts in that tutorial)
yes it is
im now watching and it worked btw so nvm but thank you
If I have a scene with objects laid out in front of a perspective camera like this, with their local forward vector pointing about- How can I take that forward vector and convert it to a 2D one from the camera's perspective? So it's described exactly how I see it on the flat screen? Green is up, red is mostly to the right, blue is between them etc etc?
WorldToScreenPoint from the object position to its position + right, up and forward
french ?
hey yall can someone explain to me
is the documentation for Mathf.Repeat wrong?
it says "loops value t so it's never larger than length and never smaller than zero"
but if you do mathf.repeat (3,3) it returns zero
3 is not larger than 3
They won't be publish wrong documentation
Smaller than 0 and equal to 0 are two different things
If you read the example they give in the doc they explain if the value is the same as the length it'll be zero
"In the example below, the value of time is restricted between 0.0 and just under 3.0. When the value of time is 3, the x position will go back to 0, and go back to 3 as time increases, in a continuous loop"
Example
using UnityEngine;
public class Example : MonoBehaviour
{
void Update()
{
// Set the x position to loop between 0 and 3
transform.position = new Vector3(Mathf.Repeat(Time.time, 3), transform.position.y, transform.position.z);
}
}
you're right
it might be that the documentation is correct
and it's just the embedded comment on the function is wrong
i didnt think of that
anyway now i know the behaviour is not as described there, ty
What part of that comment (embedded description) is wrong?
From the looks of the examples it give it looks like all it does is get the remainder of a time and devider no? What is the point of this function if this is the case
if it loops the value t so it's never larger then length, implied is that when t is not larger than length nothing need occur
Which in code is the same as doing float Remainder = t % length;
This function is just a beautified modulo, why
Most useless Mathf function ive seen yet
it loops when t is equal to length. this stops t from being larger than length. when it's smaller, there is no reason to loop . . .
☝️ are you saying it doesn't do this?
im saying that i checked the description of the function to determine what my len value should be
and i got it wrong because the behaviour of looping when t is equal to length is not mentioned
thats all
the comment omits this
it says larger
instead of "larger or equal"
which is different
thats all
i just came in to check if anyone else has encountered this
oh, i gotchu. you expected t to remain at the value of length instead of starting back at 0 . . .
ya
as @rough granite mentioned, it's a modulo operation. when t is equal to length, the remainder is 0, therefore it resets. also, i believe that 0 is inclusive, and the length is exclusive, so it never actually reaches length, but resets when it's close enough . . .
I didn’t realize this would be 2inchs (50mm) when i had ordered it
It’s roughly 2600pages
Looks like a nice book. You could probably learn most of that within an hour though with a video. General coding in unity is easier than basic NET. However if reading is your hobby, I’m sure it would be educational
I’ve watched many videos and I can’t seem to truly understand
Hey y'all, I'm trying to code in a script where I can put in a bunch of data. The plan is to have one script with access to lists of a large number of things in the game, and then the rest of the game can access it. I use this script to place everything inside of it. here is what I've got:
using System.Collections.Generic;
using UnityEngine;
public class ContentDrawer
{
//contains all of the games data that isn't part of the core functionality. Here to be added to.
public static List<StickerData> StickerList;
public static List<GameObject> CharacterList;
public static List<StatusData> StatusList;
}
I made this version. Ideally I would use scriptable objects to add new objects in the editor and then drag them in. However, I don't think this implementation does that, as per the Not Letting Me Do That. So how would I do it instead to let me assign things from editor into a script that holds all the data?
I have two other ideas since now I'm thinking this approach might just be... not good. One is to instead to define all of the data within the script instead of in the editor, in code. Issue with that is that there are some things I don't know how to get in the code... Like Images. Each StickerData contains an Image and I don't know how to code that in without "getting" it from a folder, and I don't know how to do that either... it also feels like a fragile system. Plus I don't think I'm high enough level in programming to really do that, since folders are different on different devices and such...
Other idea is similar, ignore this "content drawer" and pull the scriptable objects from the folders themselves, which I also don't know how to do.
Third idea is to make it not static and place the script in the scene but that just feels so messy and like there's better practice.
any advice appreciated :3
Well, book it is lol. Coding isn’t for everyone.
I might just be expecting too much of myself as I haven’t had enough experience to be at where I expect to be, if that makes sense
You are actually very close. What you should learn is what “DoNotDestroy” means. This will allow that single script to persist through all of your scenes and other scripts in those scenes can find that object
they say i need to destroy and initialize but i don't understand what i need to do
The code you highlighted, use CTRl+X to cut it, then you can use CTRL+V to paste it. It needs to be inside of the { } brackets for example
{
Destroy()
}
awesome, now i know how to use Ctrl + X to cut
Generally i've used scriptableobjects to hold all of that stuff, then 1 scriptableobject to hold all the holders and a single monobehaviour singleton that contains a reference to that, a rough example being
public class ScriptableManifest<T> : ScriptableObject
{
[field: SerializeField] public List<T> Content {get; private set; } = new List<T>();
}
public class ScriptableManifestManifest : ScriptableObject
{
[field: SerializeField] public ScriptableManifest<StickerData> Stickers {get; private set;}
[field: SerializeField] public ScriptableManifest<StatusData> Statuses {get; private set;}
}
public class GameManager : MonoBehaviour
{
//Typical singleton stuff you can find online
[SerializeField] private ScriptableManifestManifest mainManifest;
public static ScriptableManifestManifest Manifest => Instance.mainManifest;
}
what does public class ScriptableManifest<T> mean? I see <T> but I've never actually understood what it is...
So you don't have to dive too deep into them to get this going but that syntax (the <letter>) is called a Generic
The general idea is you can use generics to construct code where you don't actually have to know and care about the type that code will be referencing
almosttt like a kinda placeholder
Idk what generic means 😔
but mostly what I'm seeing here is... it's the same as the idea I said I didn't wanna do?
My old version had the script as a monobehaviour on an object in scene with all the scriptable objects in lists, ofc with it being a singleton
The difference between that and this is that while yes the initial reference is tied to the scene (the ScriptableManifestManifest in the gamemanager) the rest of the references are owned by the scriptableobjects outside of the scene
in theory you could load that manifestmanifest via resources.load if you really don't want anything in the scene
hmmm ic
would it be viable to try to create the lists directly in the script and get images from folders somehow? or is that too complicated? I just feel like surely I can do that
and if you want that original snippet for convience, you could manually setup up kinda "forwarders" by doing
public static class Content
{
//contains all of the games data that isn't part of the core functionality. Here to be added to.
public static List<StickerData> Stickers => GameManager.Manifest.Stickers.Content;
public static List<GameObject> CharacterList => GameManager.Manifest.Characters.Content;
public static List<StatusData> StatusList => GameManager.Manifest.Statuses.Content;
}
That is something you could do, but honestly some form of what i'm recommending would be strongly preferred imo
hmmm ic lemme try smn
You know how youd write List<float>();? The type there is generic, it's List<T>();
i don't know if this visualization helps understand generics much but for example here the T is kinda placeholder value for whatever you actually use when referencing and/or defining the ScriptableManifest<> class
so here, defining Stickers in ScriptableManifestManifest is passing in StickerData to ScriptableManifest?
the most confusing part to me is why we're using ScriptableManifest at all
I thought surely we could just do List<StickerData> and List<StatusData> directly because it seems the same to me?
oh wait I kind of get why you do this now, I like it
other questions still apply :p
-
The Type yes.
-
You could absolutely do direct lists in the ManifestManifest and functionally in this context it would be the same result, yes.
The reason I do it and the reason I recommend to do it is to further separate each type of "Content" into it's own thing with it's own responsibility.
eg. should this one big scriptableobject be in charge of the list of every type of content? or should each type of content have it's own kinda "leader" which talks to the big scriptableobject
oh wait I think I know what you mean?
I would create a scriptable object for each list
and populate those lists
and then the manifestmanifest has each of those lists separately
okok got it
I think this should work!
thanks a lot!
No worries, let me know if you have any questions 😄
ofc :3
oh I do have a question
what is a manifest? I seem to be poor at googling ._.
It might also be my instructor’s poor communication skills
Just a applicable word I tend to use
it's not a c#/unity specific term or anything
Very fair
programming be like that 😭
keep getting this error when trying to create a ContentDrawer scriptable object. Here's my code:
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "DataDrawer", menuName = "ScriptableObjects/DataDrawer")]
public class DataDrawer<T> : ScriptableObject
{
[field: SerializeField] public List<T> Content {get; private set; } = new List<T>();
}
this just doesn't work. In comparison, this does:
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "DataDrawerDrawer", menuName = "ScriptableObjects/DataDrawerDrawer")]
public class DataDrawerDrawer : ScriptableObject
{
//contains all of the games data that isn't part of the core functionality. Here to be added to.
[field: SerializeField] public DataDrawer<StickerData> Stickers {get; private set;}
[field: SerializeField] public DataDrawer<StickerData> Characters {get; private set;}
[field: SerializeField] public DataDrawer<StickerData> Statuses {get; private set;}
}
no issue here. not sure why. Not sure what's different... I might be misunderstanding the purpose of this SO. but now I'm confused how I'm supposed to populate the list otherwise...
I'm sorry I forgot one small thing with this that you only have to do because Unity is silly
so c# wise this is all good but on unity's end for the data drawers you need to make a script per type of drawer you want to use to "define" the generic that's going to be used, eg.
StickerDrawer.cs
[CreateAssetMenu(fileName = "StickerDrawer", menuName = "ScriptableObjects/StickerDrawer")]
public class StickerDrawer : DataDrawer<StickerData> {}
CharacterDrawer.cs
[CreateAssetMenu(fileName = "CharacterDrawer", menuName = "ScriptableObjects/CharacterDrawer")]
public class CharacterDrawer : DataDrawer<CharacterData> {}
its cuz Unity wants a straight and direct answer on what that thing "is"
its still worth it imo
anyone know why I can't do
using System.IO;
.
.
.
var dbPath = Path.Combine(Application.persistentDataPath, _saveFileName);
and need to do this instead?
var dbPath = System.IO.Path.Combine(Application.persistentDataPath, _saveFileName);
You mean the using directive? Because I don't see any other difference.
Using directives can only be specified at the global/namespace scope AFAIK. Definitely not in method bodies. At least in the namespace case.
yes... i put the using directive at very top
but it become like this, if i try
but this is okay
Do you have a class named Path in your project?
Yes. Compiler would prioritize types in your namespace/assembly.
should i add name prefix to my class then?
You can. You can also use explicit using in that file using Path = System.IO.Path
ok thx ❤️
can I put these in the same file? I get this warning "No script asset for CharacterDrawer. Check that the definition is in a file of the same name and that it compiles properly." which I assume is because it's all in the same cs script. I can see why it doesn't like that but it isn't an error and I don't think the script reference matters anyway? alternatively if this is "bad practice" I'll change it to different scripts as well 😔
😢
u want make a menu in topline bar ?
I'm pretty new to Unity... I gave my player a character controller. I implemented Jump. Now when I start my game, my capsule stays in place with the collider, everything is correct, but the velocity for the ground check just keeps falling. I did everything in the tutorial exactly as mentioned, but I'm just not getting anywhere.
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerMotor : MonoBehaviour
{
private CharacterController _controller;
private Vector3 _velocity;
[Header("Movement Settings")]
public float walkSpeed = 5f;
public float sprintSpeed = 8f;
public float gravity = -9.81f;
public float jumpHeight = 1.6f;
[Header("State")]
public bool isSprinting;
private void Awake()
{
_controller = GetComponent<CharacterController>();
}
private void Update()
{
ApplyGravity();
}
public void Move(Vector3 input)
{
float speed = isSprinting ? sprintSpeed : walkSpeed;
Vector3 move =
transform.right * input.x +
transform.forward * input.z;
_controller.Move(move * speed * Time.deltaTime);
}
private void ApplyGravity()
{
if (_controller.isGrounded && _velocity.y < 0f)
{
_velocity.y = -2f;
}
_velocity.y += gravity * Time.deltaTime;
_controller.Move(_velocity * Time.deltaTime);
}
public void Jump()
{
if (_controller.isGrounded)
{
_velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
}
// from PlayerController.cs
private void Update()
{
HandleMovement();
HandleJump();
_motor.ApplyGravity();
}
do you want only gravity when you are grounded?
where did you find that code?
and you dont need 2 scripts for this.. you could handle all of it in the PlayerController instead of calling methods from another script.
hi! im making a upgrade tree ( or trying to ) and wondering how i can make loads of diffrent costs and texts without making tons of scripts, is that possible?
i can provide some scripts if need be
heres my button cost, thats the one im going to try tackle first as it seems the hardest
Scriptable objects is probably the way to go
You can then make a bunch of other objects to be used in the same script and just change the variables for each
i think you are not aware of oop. You can use serialized fields for that
ooh ok yeah ill try that
as Cozies also pointed out
thanks 👍
one small advice, use TextMeshPro instead Text for crispy looking Text
i like the style of it, once everything works im gonna add some pixel filters and such, but thanks for the advice!