#💻┃code-beginner
1 messages · Page 460 of 1
wym drag in the one
Click the mouse button when hovering over one, and move the mouse without letting go of the mouse button, until your mouse is over the variable you want to assign it to, then and only then, releasing the mouse button
oh literally drag it
thats what drag means yes 💀
Unless there's stage lights and dance music, then it means something else
can anoyne help imhaving trouble with my save and load and nothing working none of the debugs are finding anthing i dont know if the button it on and i cant find the files for json that they are being saved to
show code? and more information?
We would need something to see for us to help you
How do i make an infinitely moving sprite effect, where it infinitely moves in a direction? I have a sprite renderer with a Tiled Sprite.
https://gdl.space/xinipihabe.cpp this is mainmenu this one gamemangerhttps://gdl.space/\ so what im trying to do is when player hit play start new game dont load save file start spawn player that it everthing lock etc. the other thing im trying to do is when the player hit save save player postion and where the camera is so i quit the game gull i can comback hit load game get the json file
does anybody have a tutorial for how to create the weapon sway made in the gif below?
(Credits: Karlson by Dani)
@deft grail @steep rose i posted it
double check your links, mate 😉
simple rotation in the opposite direction the mouse is moving i guess
i used that link that you guys gave me
you certainly did, you even used that exact link as your gamemanager code
Dont ping me randomly dude
ok
you still need to fix your link
i fixed it
you most certainly did not
Why did you attempt it like that
Just put the link in. No fancy formatting
Search on YouTube? It should be first or second link
I believe dani himself made a tutorial about weapon sway as well
and have you confirmed that the code is running and that the objects being assigned are the ones you expect?
yes
everthing is hooked up to where they should be
it sayin in debug player posting is saved game is save but when i hit load it loads me back to start and not to where player postion was or anthing
wait, is this happening when you like return to the main menu then go back into the game scene? or is it happening when you've closed the game and relaunched it?
happening when you've closed the game and relaunched it
but when i open the game up agin then hit load i get loaded back to where i started
and not across the hallway
and you have confirmed that it loads the data and has assigned everything correctly after loading the data?
yes
prove it
how
show how you verified that
you said you confirmed it, how did you confirm that? because i don't believe that you did and i can see at least one reason why you did not in this code
i was using prefs edior
how did you confirm that the data was correctly loaded and the fields/properties are being assigned correctly? that part has nothing to do with looking at the save data
then i would not know then
so then the answer to "have you confirmed that the code is running and that the objects being assigned are the ones you expect" is "no, i have not confirmed that, i have only confirmed that the data is saved i have done nothing at all to ensure it was loaded and applied correctly"
here's a fun fact: that GameManager object will not exist until the scene it is in is loaded
don't ignore the errors in your console
screenshot your entire editor window with the console window open when this issue is happening
do you have your player, vcams, and gamemanager all in the main menu? 🤔
are those the same exact objects that are in your game scene, or are they perhaps different instances of those objects? keep in mind they would need to be DDOL to be the same objects
so you aren't setting the player's position, you're changing the position on the prefab which won't affect the instance already in the game scene. and as you can see from your own warning log and that last screenshot (which is really the only one out of all of these i needed), you don't have the vcam you were trying to assign in this main menu so naturally that cannot be assigned as well
you need to load the data after you've loaded the correct scene and assign to the objects that are in that scene
oh so get rid of all clearshot from the code and change the positon to set and save player postin on save and load
instead of the other one
you already are trying to set the player's position on load, but you aren't doing it to the right object because the object you want to affect is in another scene
just like all those vcams i assume
yes
and the reason starting a new game works is because you likely have the gamemanager with the correct references set up in your other scene and you destroy the one from the main menu when you start a new game
I'm making a game that has a system that checks if placing something in a certain position would collide with the eventual predicted path of the player. Currently, I'm instantiating an object, using Physics2D.BoxCast with the predicted path of the player, and then destroying the object. The issue with this is one of memory. I have no clue how Unity handles memory internally, but if I'm calling DestroyImmediate() on the objects, why isn't the memory immediately deallocated? I'm 90% sure it's due to the objects since the only other thing that would be using memory is just variables and structs, all of which should be WELL under a megabyte. I can't use VS memory viewer since it just... doesn't work for some reason
Garbage Collector is an independant system that handles memory cleanup. THere are ways to force it to clean up, but not sure if you have control over that in Unity
You can see the calls in the profiler btw, called something like GC.Alloc and possibly the clean up too, I forget
Why are you creating and destroying objects instead of just recycling them?
THat ^^ switch to object pooling if it's a real issue
Basically the garbage collector IS a giant pool of objects, where the objects are sized memory chunks
i tried it, i'm not sure why it wasn't working but it wasn't. could've been something else completely
everything's happening all in one frame
so i think it had something to do with moving objects not being registered by physics until the next update or smth
idk
It doesn't matter, and also this is going to be either fundamentally flawed design or very premature optimization
it's not premature, for longer "levels", my RAM usage goes up to like 12 gb lol
That's not normal for any use
the part about "I'm instantiating an object, using Physics2D.BoxCast" doesnt really make sense. you dont need to create an object to use physics functions on
also ideally you shouldnt be using it for pathfinding like that
i'm instantiating an object and checking if it is hit by a boxcast from other points
something smells wrong if you're using 12gb up lol
if it is, that means it would be in the way of the path, and i need to not spawn the object there
yeah fr
i wanted to use the memory thing in vs debugging tools but it just doesn't work
give me c++ and allow me to manage memory myself 😔
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal?view=netcore-3.1 have fun
wait actually i don't think it gets up to 12 gb anymore, that was in a worse version of the code. it gets to around ~ 5 gb and then hell breaks loose because i'm using a recursive algorithm (i'm GOING to make it iterative eventually, trust)
stack overflow and such
you obviously have a memory leak somewhere
it all gets cleared the next frame
Just post the code
it's a bit
how many objects are we talking about here?
idk how this server works but usually people don't like long code blocks
all the relevant code is pretty long though
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Use paste sites
Also stop using DestroyImmediate before you accidentally kill a prefab
there's zero reason you should need it for this
or Destroy in general
how would i be referring to a prefab
if i only ever destroy instantiated objects
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Why use DestroyImmediate
that's all the relevant code
DestroyImmediate can only destroy assets if u use the 2nd param, but u should be using Destroy anyways
i thought it would immediately free the memory
i just haven't changed it back
needing to free the memory at all is the issue
i don't know where the leak is coming from, that's what i'm trying to figure out
i thought it was coming from objects' memory not being deallocated after their destruction
Even if it was
How are you possibly creating enough to use up 12gb?
like put that into context
you are using more than most computers had a few years back purely for a boxcast
use the profiler, deep profiler will quickly point you to the line causing issues
so i did a call by call analysis using breakpoints. every call, the RAM usage went up ~ 30 mb. it can get hundreds of calls deep
i have NO CLUE
For starters, learn to refactor code to methods that perform a single task, see SOLID principles
how 30 mb were being used
it can't be from structs and variables because... well, it just doesn't make sense
so i thought it must be from the objects being instantiated
also, ik i shouldn't ever be getting this deep into calls, i WILL rewrite it using my own stack, but i'm trying to figure this out first
it's not getting 12 gb anymore, it gets to ~5 and then it overflows (probably just due to the amount of recursion). stack size is 1 mb, which means that my structs and variables are the things going over that 1 mb limit. therefore, the other 4.999 GB has to be stuff on the heap. i'm not doing anything with the heap besides instantiating gameobjects
so it has to be that, right?
Have you used the profiler with deep profile enabled as suggested?
#💻┃code-beginner message
i'll look at it, lemme check
ah okay so
everything happens in one frame
meaning that unity hard lags
like i can't do anything in unity until the generation is done
won't that affect my ability to use the profiler?
the profiler will tell you why its lagging in the first place
you staring at the ram in task manager wont do anything
i've been using the vs debugging tools
i'll successfully generate a level and i'll look at what's taking so much ram
for (int j = 0; j < bounceInfo.Count; j++)
{
GameObject currentPeg = Instantiate(obstacle, bounceInfo[j].pegPosition, Quaternion.identity);
THat looks scary, physics can cause lots of bounces you might not even see
i destroy it
like 4 lines down
what that section of code does is generates pegs where it believes it is going to need to, and then checks if those pegs would interfere with the bounce it currently wants to do. if it does, then it'll change the direction of the bounce
have you ever used Extract Method in VS?
just use the profiler
i'm trying to figure it out 😭
idk how to jump to a specific frame
When you see a big spike, click on it, it will pause the game and you can scroll it it
oh wait i'm dumb as hell, profiler only captures like 300 frames
i need to pause quicker
alright cool i got the spike
what am i looking for?
look in the timeline section, change it to heirarchy and see what's causing it
or make it full screen and post a pic of it here for more tips
oh my LORD i have to comb through the entire call stack
it's like 1000 calls deep
...yes
i have explicitly stated this
it is a recursive algorithm
it should still not be using 30 mb of memory per call
whether or not it's recursive or iterative, it's 30 mbs every time the code is being ran. i need to know why
well for debugging purposes, I'd put a clamp on hte depth of your recursion to maybe like 5
oookay well now I'M stumped because the profiler is saying it's not even allocating that much memory
only like 120 mb, which is about what i'd expect
like for the 137 call deep recursion
wait does printing stuff use a lot of memory?
you might wanna rethink your design if your doing a 130 recursion deep call
i will
It isn't free, but it's more CPU intensive than RAM intensive
it will become iterative
i know how to mate it iterative
i'm trying to figure out this issue first
Still, if you're trying to profile, you should disable prints
okay so just doing nothing besides using a midi player thing, unity's taking 2.5 gb ram. so the "5 gb" it's been taking is really more like another 2.5, but i'll see what it is without prints rq
there is also the memory profiler if you want a deeper look specifically
The amount of ram unity is using in task manager has very little to do with your game's performance
I'm doing nothing and just staring at the package manager and still use ~10gb
10 gb is wild though
like that's more than a lot of systems have to offer
It doesn't really matter, the game itself barely uses any
A build doesn't have all the overhead of the editor
ikik
i'm not talking about the build
i'm talking like... just being able to open the editor
10 gb doing nothing?
Still doing better than firefox probably
rich alert >:(
is rider worth it?
i've been meaning to buy it but i don't do anything with c# outside of unity
not my language of choice
It's just an ide
I've never used VS, so not really sure what the differences there are
yeah but why would you pay for it when other ides are available?
can't say the same for autodesk software 😔
anywho, i'm gonna look at the unity memory profiler ig
it was the printing
that's what the memory leak was
lord have mercy
😭
i guess maybe it was all piling into a queue since it was all happening in one frame?
everything runs 100% fine now
mines only taking 4.7k mb
printing will always be relatively slow, but now that i look at the code you have a bunch of string concatenations. string stuff always produces lots of garbage
dont crosspost #854851968446365696
https://docs.unity3d.com/ScriptReference/Transform.TransformPoint.html
to get a local vector, which is seemingly what your Vector3 is, to world space. but im not really sure what you're trying to do with those local positions
Anyone have an algorithm that spirals out from the center of a grid instead of a double for loop that just goes left to right and top to bottom?
well for the fun of it I thought I'd try a little AI for a change, it failed miserably
https://gyazo.com/049789767587b028529844020747f1bb
Something like this?
void spiralHeight(int centerY, int centerX, int maxY, int maxX, int height)
{
int y = centerY;
int x = centerX;
int da = 1;
board.rc[y][x].height = height;
while (y < maxY && x < maxX)
{
for (int i = 0; i < da; i++) fillSpiralH(--y, x);
for (int i = 0; i < da; i++) fillSpiralH(y, ++x);
for (int i = 0; i <= da; i++) fillSpiralH(++y, x);
for (int i = 0; i <= da; i++) fillSpiralH(y, --x);
da += 2;
}
}
void fillSpiralH(int y, int x)
{
if (y < board.n && x < board.n && y >= 0 && x >= 0)
{
int low = 99;
int high = -99;
for (int dy = y - 1; dy < y + 2; dy++)
{
for (int dx = x - 1; dx < x + 2; dx++)
{
if (dy < board.n && dx < board.n && dy >= 0 && dx >= 0)
{
if (board.rc[dy][dx].height != -99)
{
if (board.rc[dy][dx].height < low) low = board.rc[dy][dx].height;
if (board.rc[dy][dx].height > high) high = board.rc[dy][dx].height;
}
}
}
}
if (low > high) low = high;
int h = UnityEngine.Random.Range(low - 1, high + 1);
board.rc[y][x].height = h;
}
}
Thats a 3D one.
This is a 2D spiral
void spiralType(int centerY, int centerX, int maxY, int maxX, int type)
{
int y = centerY;
int x = centerX;
int da = 1;
fillSpiral(y, x, type, centerY, centerX);
while (y < maxY && x < maxX)
{
for (int i = 0; i < da; i++) fillSpiral(--y, x, type, centerY, centerX);
for (int i = 0; i < da; i++) fillSpiral(y, ++x, type, centerY, centerX);
for (int i = 0; i <= da; i++) fillSpiral(++y, x, type, centerY, centerX);
for (int i = 0; i <= da; i++) fillSpiral(y, --x, type, centerY, centerX);
da += 2;
}
}
void fillSpiral(int y, int x, int val, int centerY, int centerX)
{
if (y < board.n && x < board.n && y >= 0 && x >= 0)
{
if (board.rc[y][x].type == -1)
{
int d = Mathf.RoundToInt(Mathf.Abs((centerX + centerY) - (y + x)));
int r = UnityEngine.Random.Range(0, d+1);
if (r <= d / 2)
{
board.rc[y][x].type = val * 11;
board.rc[y][x].sizex = val;
board.rc[y][x].sizey = val;
}
}
}
}
Thanks, will have to try that, how sad the results from chatrgpt's version
I've added a 0 Friction Material2D to the boxcollider, I set the Rigidbody2D to Interpolate.
Still my player Square (placeholder) is jittering as I walk on the Floor in the game. Why is that?
I've seperated the input and physics as one should, I dont get it.
public class PlayerMovement : MonoBehaviour
{
public float XInput { get; private set; }
private Rigidbody2D rb;
private BoxCollider2D collider;
[Header("Movement")]
public float walkSpeed = 2.5f;
// Transition Movement
private float moveDistance;
private bool isChangingLocation = false;
void Start()
{
rb = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
moveDistance = collider.size.x * 2;
}
void Update()
{
if (!isChangingLocation)
{
XInput = Input.GetAxisRaw("Horizontal");
}
}
void FixedUpdate()
{
rb.velocity = new Vector2(XInput * walkSpeed, rb.velocity.y);
}
private void OnEnable()
{
LocationTrigger.OnLocationTriggered += HandleLocationEntered;
}
private void OnDisable()
{
LocationTrigger.OnLocationTriggered -= HandleLocationEntered;
}
private void HandleLocationEntered(string locationName)
{
if (!isChangingLocation)
{
StartCoroutine(AutoMoveTransition());
}
}
private IEnumerator AutoMoveTransition()
{
isChangingLocation = true;
Vector2 startPosition = rb.position;
Vector2 endPosition = startPosition + new Vector2(XInput * moveDistance, 0);
while (Vector2.Distance(rb.position, endPosition) > 0.01f)
{
Vector2 newPosition = Vector2.MoveTowards(rb.position, endPosition, walkSpeed * Time.fixedDeltaTime);
rb.MovePosition(newPosition);
yield return new WaitForFixedUpdate();
}
rb.MovePosition(endPosition);
isChangingLocation = false;
}
}
Currently brainstorming how I could create a grid out of the space occupied by a shape. This would need to account for exotic shapes like L shapes. Any ideas?
should i seperate Main Menu and the game itself in different scene ?
easy. Make a byte[,] of a rectangle that encompasses the shape and then set the individual bytes of that array to 0 (not used) or 1 (used)
generally, yes as the controls of the menu will differ from the controls of the game
Gotcha. Also, I don't suppose this is doable with the built in grid component?
kinda, yes, you can use null not null for the individualy parts of the grid
Would it be better to just create a custom grid?
I would, It will be much faster to process it
!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 #854851968446365696
Do NOT DM people without their permission @dense pike
@languid spire my apologies
I need to create a script where the player has money and can buy guns off walls
And you obviously did not bother to look on google
Hi, i beginner in unity, and i don't know how to create a pickup script, my game is 2D, and i want doing :
- the item is impacted by gravity.
- press "E" for pickup WHENE my player touch this with a Box Collider2D.
- the item destroy in my game for add to my inventory.
If someone know how to do that ? (please help me if you know)
Someone else who, apparently, does not know that google exists
thanks for your critique... i'm beginner and my english is very not perfect, i don't very good understand a code system, i'm lost for the moment, pls don't tell me that, and i search someone for explain me explain how the 2D pick up works
It's crazy how people still assume everyone speaks the same language and has the same skills. 
I'd advise that if you want a more "one on one" style, you could try out ChatGPT. Just don't expect it to completely get everything right. Expect its outputs as more a rough draft than anything else
dont suggest chatgpt, especially not to a beginner.
crazy assumption how the person writing in english speaks english?
it's sh*t for code (i think)
That's not my point. But sure, double down on the aggression. 
I don't write very well in English, and it's 100x worse orally (I'm 16, and English in France is not crazy)
Elaborate?
as stevesmith (somewhat) suggested, use google and you can either lookup a tutorial or each individual task you want.
Gravity comes with rigidbodies, google how to learn when E is pressed and when something is in contact with a box collider. Etc
We cant really help without there being code that you're asking about
AI does not understand code. It simply regurgitates what it was trained on. If you ask it to write a Harmony patch in json it will Even though that's impossile. lol You still need to know the basics before assuming AI does.
ahhhhhhhh wait
my InventoryManager :
oh
honestly ive gone through this talk too many times
theres a thread here where it was talked about https://discord.com/channels/489222168727519232/1267346441270067222
how to make code here ?
It also doesn't understand art, but it's been taking artist's jobs in recent times
!code but also look at the #854851968446365696 on how to ask. keep it in 1 message if you can and also try to ask something specific rather than how to make an entire system
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
no it's must big
mmmmh, ok i'm thinking, thx 🙂
was doing visual scripting, and then all my scripts dissapeared and this error popped up, scripts are still functional though
Hi, how to do for my item don't cross my ground, he's trigger, and i want that he has a physics, how to do that ?
void OnCollisionEnter(Collision coll){
if(coll.collider.tag == "Obstacle"){
Debug.Log("We Hit:", coll.collider.name);
}
}
can I make a debug log like this or do I need at least 2 Debug Logs
its giving an error
Argument 2: cannot convert from 'string' to 'UnityEngine.Object'CS1503
Collider Collision.collider { get; }
The Collider we hit (Read Only).
look at the docs, the second parameter takes an object
Debug.Log("We Hit: " + coll.collider.name);
thanks
why i cant destroy my GameObject (i have tried DestroyImmidiate but it dont work)
Destroy(GlassBottlePrefab);
GlassBottlePrefab is a prefab asset, not an instance in the Unity scene hierarchy.
ohhhhhhh
You want to destroy the object you instantiated, not the prefab
ty
is there something intrinsically wrong in tweening an Anchor in the UI? 🤔
it is working, I just want to know if this could be considered a bad practice or not
the only thing I can thing of is it's going to put huge overhead on the canvas as it will be recalculating the whole canvas every frame
make sure to keep animated UI on a separate canvas to avoid redrawing the entire canvas as it will only redraw for UI that are constantly updated . . .
What I thought 🥲
but I need to bring something from "outside the screen" to "20% of the screen"... in any resolution ever made
The only thing that can always give me a good "outside the screen" is a -0.2 anchor and then I tween to 0.2 anchor...
is there a better way? 🤔
I don't get why the entire canvas would be recomputed every frame. Surely just the transformation matrix of the object being affected and its descendants?
i heard that anything changing on a canvas causes everything on that canvas to be recomputed. because of unity's bad code? idk. that's why it's recommended to split up your canvas into multiple canvases
shitty unity code
actually, the fact that unity separates two canvases ain't that bad 👀
in unreal, changing one canvas recalculates all canvas from down there
because it actually makes sense, if a brother changed, maybe I changed
I'm genuinely surprised. Unity's engineers are far from bad. They'll cut corners but there has to be a reason if this is the actual behaviour
you know that's the default behaviour in Windows as well unless you go to a great deal of trouble when processing WM_PAINT messages
hi,
my player can move left and right even after death of player.
how do i stop player from moving left and right?
disable the player input/controls . . .
how?
you can disable the component (used for input/controls), or set a bool (on the component) to false when dead. you only receive input when the bool is true . . .
private void OnDrawGizmosSelected()
{
Gizmos.color = new Color(1, 0, 0, 0.8f);
Gizmos.DrawCube(transform.localPosition, new Vector3(.4f, .4f, .4f));
}
Whats happening here? It draws the cube with offset.
is this the only place where you receive input?
what position is it supposed to be at?
Gizmo should sit on the red cube.
where do you move the GameObject?
I lifted it up so it is visible
because you use a local position not a world position
It is parented to my player but it manipulates the transform
when I try to change the local position
Then it does not rotate with my player though. Like it faces a fixed direction when I use transform.position
my player only get all movement from playercontroller
My player is looking to the right but the cube is facing forward.
drawcube does not have a rotation
where do you call the method to move the player?
just post your !code for us the see . . .
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Ah okay
i dont understand why i cant get the reference.
// Start is called before the first frame update
void Start()
{
cinematicTuyauEvent = GameObject.Find("CinematicTuyau").GetComponent<CinematicTuyauEvent>();
}
// Update is called once per frame
void Update()
{
if (cinematicTuyauEvent.PlacePotion)
{
Destroy(gameObject);
}
}
}```
hi all for some reason my player just starts floating whenever it collides with another surface, in this case the plane does anyone know why this is? https://hastebin.com/share/ubetalujuh.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so in that case there are two things that might be null:
- the gameobject with the name "CinematicTuyau"
- the component with the name "CinematicTuyauEvent"
does this name here have a space in it?
it's a bit hard to tell
ok
Just don't use Find
^^ this too
there's nothing wrong with making a public field
and just assigning it in the inspector
but i got this if i put public on a prefab
oh it's a prefab? then you can't reference an existing object via the inspector
but i have put reference for a script ```if (cinematicTuyauEvent.PlacePotion)
{
Destroy(gameObject);
}
}
}```
yeah so then assigning it in start is your best bet
so GameObject.Find(" ").GetComponent<>();
no its when its instanciate
oh alright
yeah
When you instantiate the prefab, pass the reference then
make sure that the gameobject you're referencing with .Find actually has that component
it was what i have used but it dont work
or this
var newThing = Instantiate(prefab)
newThing.variableToAssign = reference;
There is never a reason to use find
ohhhhh ty
.Find is pretty slow and awful so it should be a last-resort thing. i use it because i'm lazy
but best practice is to not use it
The worst part about find is using a gameobjects name
There are the tag and type varieties if you really need
oh
Seriously though, never ever use find
but i dont want see all my variable in the editor
The tag and type varieties are still very subpar
Make it private or use [HideInInspector]
Pass the reference into a method. I call mine Init()
ty
is there a way to make headers have like a drop down arrow
so you can hide/reveal the contents under the header
With #↕️┃editor-extensions yes
Or OdinSerializer or NaughtyAttributes
Or make the variables in a struct and then reference THAT , the struct will open and close
sorry, i was away. you placed the isDead check in Update for the input but you handle the movement in FixedUpdate. HandleAnimation will still use the Xinput if it wasn't 0 before the player dies. if this is true, then HandleMovement will apply velocity to the rigidbody. i'd move the isDead check to FixedUpdate instead. This will block all movement . . .
i have tried this it work but now i have this and i dont know what is it
That is not from anything you did.
See how the location starts with UnityEngine?
Close any graphs (like the animator) and restart unity
ok ty
its fine, solved it 😄
no problem. moving the isDead check to FixedUpdate will fix it . . .
Kinda funny how a single missing letter changes this statement from "Solved it! 😄 " to "Solve it. 😠"
I will need more help in future, hoping to be befriend 😄
so im trying to make a ledge climbing function and it works but the problem is that the player instantly transforms onto the object like u can probably see in the code, how can i make sure that the player is like slowly getting on the ledge once he collides with it?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
not sure if this is the right place to ask but does anyone know how to fix this?
this is a coding channel, no its not the right place
also thats flipped normals
In a procedural generation is it better to generate all of the map at the beggining or room by room (roguelike game)
wat are flipped normals ;-;
google "flipped normals Unity" and you will get your answer
alrighty thanks and sorry for asking this here
all good 👍
Trying to follow a tutorial but this won't be recognized, anyone know why?
thats not how you write methods
you def copied it wrong
Because the syntax is completely wrong
Try copying it correctly
Also make sure you capitalize things properly
And spell them correctly
The IDE will help with those though, once you start using the correct characters
what would be the best way to get a float within a given range and round to the nearest decimal. For example, if the range is 1.3-1.6, I want equal outcomes of 1.3, 1.4, 1.5, and 1.6. If the range is 1.75-2, i want equal outcomes of 1.76,1.77, etc all the way to 2
is this able to be done generically ?
something something math.pow
Start with the lowest number in the range and add whatever your increment is until you reach the top.
One issue though is that 0.1 and 0.01 are infinite repeating decimal representations in binary
So you may wish to do things with integers. E.g. an int which represents the number of one-hundredths
so multiply by 10, 100, 1000, etc first?
how would I check how many decimal places the number has?
without using strings preferably
The decimal type is more appropriate if you want to store fractions in base 10.
Would this work?
private decimal minValue = 1.3m;
private decimal maxValue = 1.6m;
public int decimalPlaces = 2;
...
decimal randomValue = (decimal)Random.Range((float)minValue, (float)maxValue);
var roundedVal = decimal.Round(randomValue, decimalPlaces);
Debug.Log($"Rounded{randomValue} random number: {roundedVal} ");```
don't even need to use decimal for this, unity has the Snapping.Snap method that can be used for floats
TIL
of course that would still be affected by floating point inaccuracy though
this is kewl
var randomValue = Random.Range(minValue, maxValue);
var roundedVal = Snapping.Snap(randomValue, stepSize);
Debug.Log($"{randomValue} Snapped random number: " + roundedVal);```
Anyone know why these aren't distributing in a circle?
I would use Radianscs int maxPlayers = 6; float radius = 200f; float angleIncrement = 360f / maxPlayers; for (int i = 0; i < maxPlayers; i++) { var angle = i * angleIncrement; var angleRadians = angle * Mathf.Deg2Rad; var xPos = Mathf.Cos(angleRadians) * radius; var yPos = Mathf.Sin(angleRadians) * radius; var player = Instantiate(playerPrefab, transform); player.localPosition = new Vector2(xPos, yPos); }
float angle should be Mathf.Pi * 2 / MaxPlayers
Since Sin and Cos are looking for input in radians
Ahh thank you guys, the video I was watching about sine and consines was using degrees. Thanks!
also this makes no difference since you happen to be doing a division that works with ints, but you are doing integer division with 360 / 6 so it results in an int not a float
Thanks wasn't sure if the f was beneficial for whole numbers
Beautiful! Thank you!
if you want the result to be a float then at least one of the numbers in the operation must be a float. otherwise it's an integer that gets implicitly cast to float. so 1 / 10 would be 0 instead of 0.1
this worked perfect
Any easy ideas on how I could turn this evenly distributed circle into an evenly distributed oval?
Oh maybe just multiply the axis' with different radiuses
ya xPos = Mathf.Cos(angleRadians) * radius * xScale; .. I think
Yup that works!
Use the ellipse formula 😉
What is the best way to program a procedular generation with a center room which stays the same? Or maybe, what is the way you like the most?
Hey, I want to have an object move along a path defined by a Spline from the Unity spline package, is there a script for this in Unity already?
open the components like spline Animation and see how they're constructed, thats how I learned
Oh, thank you!
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.GetNearestPoint.html
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineContainer.EvaluatePosition.html
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/UnityEngine.Splines.SplineUtility.html
basically you're mostly using these type of methods
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
I dont know what im doing wrong, but when FPS is low, it shakes faster
https://hatebin.com/jydttcfmpk
Is there any consequences to redundantly defining a variable as public when you could just use [SerializeField]?
fucking up your own code later on, or if with a team, someone accesses/changes something they are not supposed to without knowing, cause its public access
not sure, but that lerp should be made better https://unity.huh.how/lerp/wrong-lerp
So it won't increase load times or increase file size or anything like that? Basically I'm trying to decide if (as a solo coder) it's worth going back through all of my scripts to change things that don't need to be public to just [SerializeField].
thank you 👍
also would change " yield return null;"
to yield return WaitForFixedUpdate
if you're gonna do stuff with rb
okay tysm!
How can I program a procedural generation with a central area from which the rest generate?
no its simply encapulation, it has no effect on code speed/size
Cool. I won't bother changing my public variables then, just make sure I'm using [SerializeField] going forward for good practice.
yeah its always better to have everything private and onyl explicitly make something public
for fields, use properties for public access
Also I don't need to do "[SerializeField] private" right? It's just private by default?
they are default to private yes, SerializeField is a unity attribute(you need to explicitly put that in). That just exposes it in the inspector
Hi all,
Another brainfart moment from Spud.
if (isRotating == true)
{
float currentMouseLateralPosition = Input.mousePosition.x;
float mouseLateralMovement = currentMouseLateralPosition - startMouseLateralPosition;
cameraLateralRotation.Rotate(Vector3.up, -mouseLateralMovement * orbitSpeed * Time.deltaTime);
float currentMouseVerticalPosition = Input.mousePosition.y;
float mouseVerticalMovement = currentMouseVerticalPosition - startMouseVerticalPosition;
cameraVerticalRotation.Rotate(Vector3.right, -mouseVerticalMovement * orbitSpeed * Time.deltaTime);
startMouseLateralPosition = currentMouseLateralPosition;
startMouseVerticalPosition = currentMouseVerticalPosition;
}
I have this 'orbit camera' code that works great, but I can't for the life of me remember how to clamp the Vertical rotation of the cameraVerticalRotation Transform. 😕
Alright, thanks for the info!
Does somebody know how to create a procedural dungeon map with an unchanged center room???
Im sure many people do
I made something that does what you want a while ago, but tbh it's horrible coding and if I posted it here I'd more than likely get shouted at. lol.
Ive been searching for a good tutorial almost all my evening and I haven´t found anything like what I want honestly
Okay, like I said, terrible coding, but it might give you ideas? ((Please nobody throw rotten fruit at me. lol.))
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
does the map have different biomes?
No, it's literally just rooms and corridors
oh okay, thanks a lot anyway!!
why isn't this enabling and disabling shadows? they're just always disabled
Not much can be said unless you show what you tried. Rarely tutorials will have exactly what you need.
You could always take that procedural algorithm, check if it's the center then use a hardcoded result
I haven´t even started and this case is starting to make me feel frustrated, I´ll leave it for now
I'm not 100% sure on this one, but maybe you need to specify hard/soft? Like I said, I'm not sure.
alright ill try that out
Just curious, but why enable/disable them? I understand the idea behind it, but as for example the sun goes below the horizon it will stop creating shadows on your 'landscape' anyway?
when the moon has shadows enabled
then the sun doesnt make any shadows?
only when the shadows of the moon are disabled then they show up
this error happens: Cascade Shadow atlasing has failed, only one directional light can cast shadows at a time
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
i have a question
im new to c# and im still learning
im watching brackeyes course on c#
im on the 4th ep im just learning about loops
so heres ny question
is there any better courses i can take? after this one?
check pin
repetition is important, if you are learning a concept, repeat doing / using until its clear whats happening
i don't teach code at all lol Just show specific Unity features you may not know about 😛
ok thats a funny coincidne actualy i finished brackeyes ep 4 yesterday but i wasnt fully sure about it so i reapeated it again today
the brackys c# are probably one of the worse ones he has
while some are okay c# + unity. you generally want to learn that separately (microsoft learn site is good)
When I started I liked this one because it mixed a bit of unity context and a bit of c#
https://learn.unity.com/project/beginner-gameplay-scripting
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
pastebin sucks
any reason why? doesn't it do the exact same thing as the others?
cause most of the page is garbage scam/adware
also heard they were sketchy at some point
Is it? Lol Idk i have ad blocker on all the time
I'll take your word for it tho
there is a reason its not in the Code bot
who does a codewebsite with half the layout being this shite
https://hastebin.com/share/jejoduvetu.csharp
Currently running into the issue with this "lock on" mechanic where moving the mouse away from the target still keeps the transform locked to the target.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
And admittedly hastebin is much better just cause it was like 3 button clicks and "just works"
gonna bookmark that, I've just been using pastebin out of habit
is there a video you could record
My inital thought was to just set the lockOnPosition to null in a OnTriggerExit, but then I run into the issue of, what if I have multiple targets inside of the triiger, but I only exit one?
I can tryyyy?
im confused why a reticle has a trigger
its supposed to act as a lock on
gimmie a sec and I'll show u
Running OBS for the first time on this OS
use mp4 to embed video in discord, mkv requires being downloaded
looking at your code though:
if (lockOnPosition != null)
{
this.transform.position = (Vector3)lockOnPosition;
}
else if (hit.collider.gameObject != gameObject)
{
this.gameObject.transform.position = hit.point;
}
unless lockOnPosition is set to null (which only happens if something other than an ICanBeDamaged object enters the trigger) the position of that object cannot follow the mouse
Whoops, yeah I suppose that's true
I've been meaning to fix that
guess now is the time
also you might want to consider using a physics query instead of relying on trigger messages, that way you won't end up with the issue of OnTriggerExit being called for only one of multiple objects in the trigger
I was wondering if the was a better way to go about it. What is a physics query? I only know about it in the context of "queryTriggerInteraction"
like an OverlapSphere, SphereCast, etc
instead of having a sphere collider that you stick to the object when it gets detected, you instead use the physics query to check the area around where your mouse is (keep the current raycast from the mouse position and just use the query at its hit position)
well those are the ones for the Unity Physics package which is for DOTS. so if you are using DOTS and the Unity Physics package then yes, but from the looks of it you are using the built in physics (which is physx not Unity Physics) through the Physics class so look at the documentation for that
Will do
gotta refresh my memory on how to use layermasks first to fix the first issue
Also is DOTS, the same as that one system in unreal?
dots is the data oriented technology stack. i'm not familiar enough with unreal to know what "that one system" is referring to, but if you want to look at what it is then either check out #1062393052863414313 or
it
Oh nvm, yeah no I thought it wouldve been something completely different
Dude unity.huh.how - how have I not found this til right now?
Thank you very much for the link
it's an excellent resource made by one of the mods here
guys how would i use the on triggerstay to get the position of the object i just entered its trigger?
Image
like use the postion of the object for the grapplepoint
Position is accessible on the Transform, and the Transform is accessible from any component (like a Collider2D - the method provides it as a parameter here), so you should be able to get the position from the collider.
ahhh ok thanks
How do I make the object being dragged respect the colliders of my game's borders? Right now I can simply drag the object through them. Heres the code:
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
guys, I want to throw a projectile like a hook using an animation, and then when it hits something, to come back from where it came from. how should I proceed?
I would like to also add something like curving to the trajectory or follow a different trajectory when it comes back
I'd look into using a bezier curve possibly and just manually move it along the point so you can use physics queries. Otherwise you'll be trying to use like overlap functions during the animation which might be more inaccurate.
Then for pulling back it's just a different curve
Hi
Does anyone know if there's a way to use Physics.OverlapCapsule to actually identify overlaps? I'm trying to use it but it's detecting edge touches as well, just like IsTouchingLayers would, do I have to provide something for it to detect actual overlaps?
What do you mean actual overlaps? Like if something is entirely encapsulated
Like, for me one thing is when two things are just touching each other, another thing is when a certain amount of the thing 1 is actually inside the thing 2, which I would call an overlap, that's how I thought OverlapCapsule works, but apparently it isn't
As the name suggests, that is how overlap functions actually work.
Like here, the player capsule collider is considered to be overlapping with the climbingTilemap
people are telling me not to use tutorials but then if i ask something in the begginer section of any unity discord server they say to use tutorials so im confused ... so like what am i supposed to be doing to start
Then yes it is, assuming you used the correct values in that overlap check. It wouldnt make sense if unity said "oh well it's barely touching might as well say its not"
do you have a project you want to make in mind?
how much of unity and c# do you already know?
to break out of "tutorial hell" you should plan a project from start to finish and break down the features you need to do
but that's what I'm saying, they are just touching, not overlapping, why is OverlapCapsule truthy then? Or is that just how it works?
when you break down what you need to do and focus on each individual task, youll learn how to do each task and inevitably watch tutorials on the way
i am trying to make jump mechanics for my platformer game but i am getting abnormal values even though i am not jumping
Who said not to use tutorials? You shouldnt be blindly copy pasting them and ideally stay away from the ones that are "build a whole game in 5 minutes!". Look up specific concepts, then build your system. Example: how to build a shop system is gonna get you an exact tutorial thatll be hard to extend upon for what you need. You'll be better off just taking the part where they look at an item to know how to "buy" it
you watch tutorials to complete a project you want to make, not watch tutorials with the sole goal of learning unity
Ok, Got It
🤷♂️ they are overlapping, at the point of them touching. You cannot define when something is overlapping vs touching here because it doesnt make sense
I must be getting something wrong then, for me touching and overlapping are two different things, I mean, it's possible that I'm touching AND overlapping, but it should also be possible to be touching AND NOT overlapping
I'm not sure what's confusing, and cant really say more without repeating the above. There is no difference between overlap and touching. That is all.
I would assume that for digital things to touch they would have to overlap... like, otherwise, touching vs overlapping would be a matter of floating point rounding errors, right? "These things are touching but not overlapping if they're positioned exactly one floating point blind spot from each other" 🤔
Edit: or I guess just an arbitrary threshold
can you just make the collider slightly smallre?
That wouldnt matter. Now you're just overlapping with a smaller collider
how about couple a distance check along with the collision?
I think I get what you're saying, I was just wondering if there was a way to identify an actual overlap, like when a certain amount of a layer is actually over another layer, I'm working on making the player not able to climb up unless they're actually overlapping with a tile in the climbingTilemap, hence the importance of understanding how to do this
I dont know much about 2d or tilemaps but I'd assume it has a way to know what tile you're on by location or something. Otherwise it wouldnt really be a map
yeah, I'm also thinking about doing something like that, like checking if the player is in a tile from the climbingTilemap right?
this community is so nice
any idea?
i can share the code if needed
bunch of programmers with strong egos, it can quickly go sideways lol
I would guess it's the constant effect of your gravity
so basically a bunch of programmers
Idk enough about 2d to say anything. Maybe someone else will chime in. You could probably write this as a new question
if i am going up the slope without pressing jump button the velocity.y is changing and that messes up my jump animation, any idea about how can i alternatively make the jump animation
why doesnt this work?
Because that's a method, and it looks like you're trying to use it as a field or property
Read the error
yes but cant u raycast in the mouse direction?
You can do whatever you'd like, you just have to obey the rules of C# to do it.
I'm not great with animation stuff... Maybe you could just pass 0 in as the animation parameter if you're grounded? There may well be a better solution
Look at the character right after ScreenPointToRay, and think about how methods (like ScreenPointToRay) are supposed to look
ye i know i should write it like this, but isnt there another way?
What do you mean another way?
like this? so i sent the raycast from the camera perspective and i want it to go in the direction of the mouseposition, why isnt this possible?
which parameter
What makes you say it's not possible
What's wrong with this way
Can someone help me with post processing? https://discord.com/channels/489222168727519232/497873924504420362 How can I remove URP? Should I use URP? What should I use for a small project? (Saying that here because this channel is active)
look at the photo i answered on, i get errors, how could i fix that
By doing it like this
Which is the right way
velocityY, such that if you are touching the ground, gravity's acceleration would not be reflected in the animator.
Alternately, depending on how gravity is applied, you may be able to set that parameter prior to the velocity reflecting gravity
so camera.screentopointtoray is not a vector 3? thats why it cannot be in the direction argument?
Of course not.
First of all of like it says, it's a ray
Read the documentation to see what the function returns
Vector3 direction
Second of all, you failed to properly call it as a function
Which requires () and providing the parameters
Ray and Vector3 are not the same
anyone has a reference to the mario bros movement? im making the 1-1 level of smb with learning pruposes but my movement is not to mario, any improvements or resources out there?
in the documentation stands a vector3?
Scroll down, there are overloads that take a Ray directly. C# automatically chooses the right one depending on what you're feeding it
You can see which overload it selected by putting the mouse over Raycast in your code
Camera.screentopointtoray is not a vector 3 so i cant put it in those arguments?
Look it up on docs
what are you even trying to do
Raycast from the mouse position into the scene, apparently
Which works, it's a matter of reading the documentation
there are some great tutorials for that out there actually
Because ScreenPointToRay is a method, and what you wrote there simply doesn't make sense. Which screenpoint do you want to be a ray?
You have to pass in the screenpoint
Some versions take a Ray, scroll down
ahh ok got it, thanks!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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 the proper way to Invoke a method from another script it isnt worming so obviously not but how would I?
script.fadeIn();
Invoke("script.fadeOut", 1);
do you mean actually calling a method from another script or using the Invoke method?
no, Invoke does not work like that. It searches the object it was called on to call the method with the name passed to it. Consider using a coroutine instead
Using the invoke
Invoke will only call methods on the GameObject itself . . .
but yeah, do what box mentioned . . .
Okay coroutine where should I learn how those work? Any video that is good or the docs do fine
Don't use invoke here. Call a function on the other script that invokes itself
Coroutine is better too, yea
Okay good to know im pretty new so i dont know these things yet
But regardless, let it handle its own invoking
Okay will do thanks for the help!
my game is 2d if that changes anything
it does not
sweet thanks everyone
hello
rb.AddForce(0,0,-1000 * Time.deltaTime);
how to apply force for a certain amount of time
a timer or coroutine
like in the mobile games you hit an obstacle you go back a bit then stop
for that a simple impulse force would be all you need rather than applying force over time
also don't multiply your forces by deltaTime, ForceMode.Force already takes that into consideration and you must be applying constant forces in FixedUpdate rather than Update
you do not multiply by deltaTime when using force . . .
originally this was for keeping the player running
basic game tutorial
I just thought it'll work like this also
you want this to apply with user input or not? just to be sure
void OnCollisionEnter(Collision coll){
if(coll.collider.tag == "Obstacle"){
Debug.Log("We Hit" + coll.collider.name);
plrmovement.enabled = false;
rb.AddForce(0,0,-1000 * Time.deltaTime);
}
}
"impulse force"
I think we're in beginner
oh
sorry man
impulse force let me try
rb.AddForce(0,0,0, ForceMode.Impulse);
like this?
try it and see
well that won't actually do anything on account of it adding 0 force on all axes
add more force?
change gravity and stuff
or wdym by "faster"
Instead of one number, use a bigger number
and make sure you aren't doing something silly like completely overriding the velocity of the RB somewhere
I did something like this
IEnumerator MovementAfterForce(){
rb.AddForce(0,0,-10, ForceMode.Impulse);
yield return new WaitForSeconds(2);
plrmovement.enabled = true;
}
void OnCollisionEnter(Collision coll){
if(coll.collider.tag == "Obstacle"){
Debug.Log("We Hit" + coll.collider.name);
plrmovement.enabled = false;
StartCoroutine(MovementAfterForce());
}
}
it works alrighhtt
use CompareTag instead of .tag
slight problem
What would happen if you hit twice 
Except the first coroutine might've reset the player movement before finishing the yield for the second
but my character's speed slowly increasing is there a way to make it straight
its an impulse, so should be instant already, unless you mean another bit of code that you havent shown
like I hit the obstacle high speed and my -10 force does nothing and I hit it again when plrmovement is enabled
yeah
use a higher number perhaps
and also #💻┃code-beginner message
how does that even work
Impulse should occur immediately. Are you accounting for friction and whatnot?
reset the player's velocity to 0 before adding force, otherwise the force needs to overcome its existing velocity
you click it, it takes you to a message
yeah I know
how does "completely overriding the velocity of the RB" work
how do I even do that
well if you assign to its velocity property anywhere that overrides what the velocity currently is
for example if you do rb.velocity = ... you would set it
rb.AddForce(0,0,forwardForce * Time.deltaTime,ForceMode.Impulse);
forward force is 10
dont use deltaTime
okay
you were told this earlier
Remove what?
Do you mean Update?
void loop?
Void is just a return type btw. Don't use that in the name
Good game name 🤔
Always apply forces in fixedupdate() btw
With a few exceptions (forcemode.impulse called once for example). But yes
it works great in normal update
It aligns with the cadence of the physics internal update
So far. You definitely should not do it for continuous movement
I did not know that 😅
Don't call it void. That is the return type. Just say FixedUpdate
But yes
you cant make multiple i think
letme try
Oh, if you have one already, then just use that
You absolutely cannot have multiple
I can do that
Show what you did...
Ok, I thought they were saying you had more than one FixedUpdate
Update and FixedUpdate are obviously perfectly fine
so I dont need two updates
Time.deltaTime is the time since the last frame (or physics update, depending on where it's used) in seconds. So it's useful to figure out a distance from a velocity, for example - you multiply the velocity by the amount of time which has passed.
But it doesn't make sense to multiply an instantaneous force by a time. You want all of the force now - no reason to scale it down
Remove deltatime, its arbitrary when in fixedupdate
One Update and one FixedUpdate
Never ever use deltaTime in AddForce
they are different things
Or with velocity
I hope my capsule dont fly
Well lower the force of course
Multiplying it by deltaTime (a tiny decimal) will of course reduce the force a lot. So when you remove it, you have to decrease the force
I saw something that update is working every frame so more fps I got , more speed I got
delta time is making it
AddForce ALREADY has deltaTime in its force internally
eh how can I say
Never ever ever ever use deltaTime in AddForce
my capsule was flying around in 10 force
Reduce it
if this is just to move it continuously, then do not use ForceMode.Impulse for this, ForceMode.Force would be more appropriate. Impulse is for an impulse of force, or one-off forces that should apply all of the force all at once
Also, why are you using Impulse -ah too slow
I dont know bro just trying different things
okay
thats why he flyin
pretty sure it running every frame is not what he wants, and impulse is what he wants
but who knows 🤷♂️
so I dont use deltaTime in fixedupdate
Impulse in the OnCollision message made sense 👍
let me try
this seems unrelated to the previous code, i think this is what they are using to just move the object forward already
ah
No, you don't use deltaTime with ADDFORCE
so I use for impulse for back off
thought you just added a variable since it had the same value and you pointed that out
and dont use impulse for continuesly
You can certainly use deltaTime in FixedUpdate (it will convert to fixedDeltaTime though)
void FixedUpdate(){
rb.AddForce(0,0,forwardForce,ForceMode.Force);
}
so Like that huh??
?
for your impulse to knock it back, you will also want to reset the velocity to 0 immediately before the knockback
so it doesnt get affect by speed
am i right
right, since your knockback force is similar to the amount of forward force the object will already be affected by if you don't reset the velocity before the knockback at best it might be knocked back only a little bit
thats what I was talking about
so how do I set velocity 0
rb.velocity?
the guy said
rb.velocity = vector3.zero
vector3.zero is the same as writing new Vector3(0, 0, 0)
which would make the velocity to 0 yes
yes bro 👍
I try and its good
but Im not sure if the player is always in same speed
how can I know that
I feel like its getting more speedy every second without hitting an obstacle
you can debug.log the values you need
Debug.Log(rb.velocity);
??
if the rigidbody does not have drag or any other forces acting on it, then yes you are constantly accelerating
angular drag of 0.05
That will work against angular velocity, but not linear velocity
Add some Drag
why
The running force will eventually reach an equilibrium with the drag force, effectively resulting in a top speed
it worked but I didnt understand how it did
hello i have a question regarding two scripts that i've written, one script takes a mouse input and info from a raycast and the other script takes this info and decides wether or not to deactivate itself, the code works fine, but when i duplicated the game object that would destroy itself and tested the code, both the og and the duplicated object were destroyed when interacted with. i basically need them to destroy when interacted with separately rather than both with one interaction. Could anybody help? id rather dm the code so its a bit quieter
You're accelerating your character by applying a force. The drag force is applied to your character in the direction opposite of their current velocity.
Drag force is calculated as a function of the magnitude of the character's velocity and the Drag value you set as a multiplier. So as the character moves faster, a greater drag force is applied against them. When the character is moving fast enough, the drag force will become large enough that it's equal to the force you are applying to move it - the two forces cancel each other out, so the character just maintains it's current velocity instead of accelerating.
When your Drag was set to 0, it totally disabled the drag force, so there was no resistance to the acceleration.
You can create a thread here if you're worried about the channel noise - better to have more eyeballs on the problem than to wait on a DM 👀
i also dont want people judging my code i have NO clue if it is effecient at all, im happy to post it here directly
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
your not the only one with bad code, pretty much everyone has something bad
so dont worry
i have it ready to post
that's a great way to improve, let outsiders judge it for you
` not '
thanks bro
// using UnityEngine;
public class SprayToggle : MonoBehaviour
{
public bool canSpray = false;
public bool spraying = false;
[SerializeField] LayerMask glass;
// Update is called once per frame
void Update()
{
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hitinfo, 5f, glass))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hitinfo.distance, Color.red);
canSpray = true;
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 5f, Color.green);
canSpray = false;
}
if ((Input.GetKeyDown(KeyCode.Mouse0)) && (canSpray == true))
{
Debug.Log("spraying");
spraying = true;
}
else
{
spraying = false;
}
}
this is the first script
hello, whats the blender donut equivalent of unity? i havent installed it yet but i really want to get started and i dont even know how to code
// using UnityEngine;
public class smudge : MonoBehaviour
{
public SprayToggle wipe;
private void Update()
{
bool spraying = wipe.spraying;
if(spraying == true)
{
Destroy(this.gameObject);
}
else
{
gameObject.SetActive(true);
}
}
}
second
you can do just if(spraying) if you didnt know
why using UnityEngine commeted out?
Probably the Unity Essentials and Junior Programmer Pathways on Unity !learn 👇. Not quite donut scale, but well worth running through 👀
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im not sure just a copy pasting thing, dont worry
thanks ill check it out, and what about youtube videos, any recommended content creators?
i did but i find it easier to read
personal preference
the issue is that when i duplicate the gameobject with the second script, when the first script interacts with the gameobject via the raycast both objects get destroyed
if that makes sense, i just need a way of indavidualising each gameobject somewhere in the script i think, but i cant think of anything
as for judging your code it actually doesn't look that bad, small concise methods, using some debug drawrays to help
I'm not too familiar with many creators, but I do like CatLike Coding, LlamAcademy, Game Dev Beginner, the Unity channel, Tarodev, and Sebastian Lague
thanks, also i found a 10h long video on unity, should i watch it in parts or should i stick to one learning way if yk what i mean
It's kind of hard for random YouTube videos to target their entire audience's skill level as it varies so widely. So some sort of foundational knowledge from more structured content is definitely useful before wandering out into the wilderness. But an introductory 10 hour video may offer that sort of structure 🤷.
I kind of followed the Learn content and challenged myself to integrate stuff I was learning about in my projects through other avenues along the way, which worked well for me, but I can't say if it would work well for everyone
That makes sense - all of the smudges will check every frame if wipe.spraying, and blow themselves up if so.
A more common solution to interacting with specific instances like that is to have whatever's performing the raycast try and get the "second script" component from whatever it hit, and if found, call a method on it. That way whatever functionality needs to happen is only executing on the relevant instance (and you don't have a bunch of objects constantly checking if they should do something 😁)
Well in the video (Code Monkey) says it's a full free course on making a game for beginners as well as intermediates. I think i will start my unity journey as i did with blender which is to mess around first and then look for a proper course. Thanks a lot for your help though, i really appreciate it
no worries, it's our duty to judge . . .
so make the first script deactivate the necessary gameobject rather than the second script? put simply
You could, totally!
But often times and definitely for more complex scenarios, it doesn't make sense to have all that logic relevant to those objects contained in the class which is raycasting. So instead the raycaster just calls a method on what it hit. This way, the class on the object which was hit is still responsible for all of it's own logic and behaviors - the raycaster just kicks things off
Although in this case, a wiper destroying smudges does sound totally reasonable 🤔
the premise of the game is a cleaning game if you hadnt guessed already
thank you very much for your help, I will defenitely fiddle around with that idea (and get back to you )
that's why I got into unity
really good course, honestly I dropped it like 2 thirds in after I learned what I needed to start my own game, afterwards I just try to make something with the info I know, end up messing up, so I either look up a tutorial, documentation or ask here if nothing else works. I recommend digesting the information and then applying it by yourself to your own ideas
i wrote another script that works fine for a vaccum, it works off of collision detection. I was hoping there would be a way to physically check if a raycast was touching a collider, by checking the tag, layer or name of what was outputting the ray and perform a method off of that is there ANY way to actually do this
a raycast can check if it hits tag layer or name yes
but could the object being hit by the raycast check where the raycast was coming from?
the object being hit has no knowledge of any raycast i think.
so you would have to manually pass that info your self
Just a note, raycast are not physical objects at all. They dont actually exist in the scene so they do not actually collide or touch objects.
yeah im just grasping at straws and trying to find an easy work around its not really working 😦
I didnt see what you're trying to do with it, usually this would be paired with trying to move an object (like a knockback). In which case you'd just make a method for this on the objects you want to be affected.
the code is a little above here ^ , essentially I'm trying to destroy a gameobject without its duplicate being destroyed too
Sounds like an issue with that logic entirely, not sure why its checking that spraying variable but both instances of the script are likely referencing the same object. Then both would destroy themselves
if spraying == true and the raycast is hitting the specific gameobject then it will deactivate itself,
there are two scripts posted
im just fiddling about with the logic as you said and trying different things, im sure it will click eventually 🙂
Nothing about this script affects what I said above, in that both smudges are just gonna read the same value and instantly destroy themselves.
yeah thats the issue
The spraying script should call a public method on the smudge script to let it know to destroy itself. At least that's what I assume you want
The smudge doesnt need to use update at all here
Oh cool, good to know
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class TimerController : MonoBehaviour
{
public static TimerController instance;
public TMP_Text timeCounter;
public TMP_Text highScore;
private TimeSpan timePlaying;
private bool timerGoing;
private float elapsedTime;
private void Awake()
{
instance = this;
}
private void Start()
{
timeCounter.text = "00:00.00";
timerGoing = false;
BeginTimer();
}
public void BeginTimer()
{
timerGoing = true;
elapsedTime = 0f;
StartCoroutine(UpdateTimer());
}
public void EndTimer()
{
timerGoing = false;
}
private IEnumerator UpdateTimer()
{
while (timerGoing)
{
elapsedTime += Time.deltaTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime);
string timePlayingStr = timePlaying.ToString("mm':'ss'.'ff");
timeCounter.text = timePlayingStr;
yield return null;
}
}
}
how would i turn this to add a highscore part
What would any of this even have to do with a highscore?
I would make that completely separate
i want to save ur time when u get a lower time then ur previous highscore
Man thank you very much I got it working thanks to you, so much simpler than i thought i dont even need the smudge script
Just asking out of curiousity. May someone explain how this line of code works? I've never used a ? in a line of code before
Ah score IS the time. Got it (based on at least)
i got it working thank you : )
ya sorry should have made that more clear
Then just a single if checking if current score is better than currentHighScore
Get some save and load functionality, hopefully using json or something (many guides online)
Bada boom, done
ok so i would save ur scores into a json file on ur computer?
and i should probably encrypt it so ppl dont change their scores right?
Thank you
Well, to have the score persist over runtimes, yes.
For a single runtime, make a singleton in DDOL to carry over scenes
Well, you would want it to be hosted on a server if you care about that
Any and ALL encryptions can (and will) be broken
Especially ones for games because people love doing that
You should have the script tbh. Calling a public method is much cleaner because you'll easily add functionality later. Right now your objects are limited to only being destroyed. You cant really play animations, sounds, have tougher smudges or anything
ok ill keep it as a json for now then i might see about keeping a sever database
thanks for the help
i guess so but i will cross that bridge, thank you anyway massive help 🙏🏾 🔥
if your doing leaderboards then just manually delete any "hacked" time, i would say
otherwise no point of any databases if its all local anyway
Aye fellas, im tryina get a wave system for this lil game workin. The OnDestruct is meant to keep track of how many enemies are currently alive, so im trying to get it to run within the enemy's script so it can trigger upon the death of the enemies, but it keeps throwin up the error in the first image. Anyone know what's up? (The last two are from the enemy's script)
you should include line numbers in your code screenshots
and best not use a screenshot at all !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
gotcha, gimme a tick to reformat it
https://paste.ofcode.org/mqEFpTN2uaWg9yFikZwsE6 (Enemy Script)
https://paste.ofcode.org/38S63szFwc8PG9eJfhXBwz8 (Spawner Script)
Its got a prob with callin the foreign function
so does this object have a MannequinSpawner script on it?
the object with EnemyClose on it
I sees I sees
you can get a reference to the object and use GetComponent on that
or just reference the script itself
I have a grid built and I'm trying to process mouse clicks on the grid. I have it more or less working with raycast stuff, but I want to make sure I only click the top of these tiles though. Any ideas?
Check the hit normal
check that the normal from the raycast hit is in the .up diretion
What about in the scenario of "ramp" tiles?
Check that the hot normal is aligned with the grid/cell up direction.
OnDestruct just substracts from the enemy count, it doesn't actually remove the GameObject from anything . . .
use a layermask to exclude other objects
Destroying the object is handled with the enemy script itself
What is a "hot normal"?
Er oh you meant hit
Just realized that while I was typing XD
i don't understand why you do GetComponent<MannequinSpawner>(); //Gets the spawner script in DeathTimer because you don't assign it to a variable or access a member from the script . . .
also, in OnDeath you set currentlyAlive = false then check if it's false in the next line. it will always be false because you just assigned it, so they if check is unnecessary. the same applies to if (isDead == true). you just assigned it to true right above, so it will always be true . . .
So what would an implementation look like here? My grid's upwards direction is in the +y direction. Would I just make sure the normal has a +y component?
Well, didn't you bring up the "ramp" thing? If it's a ramp, it's upwards direction wouldn't be equal to world up.
No, but from testing it seems like it would have at least some kind of +y component (if at least somewhat facing up), unless I tested it wrong
kind of confused right now with this error
so did you assign it?
I dont think I did and im pretty clueless on where to do it
you made it SerializeField which means its exposed in the inspector, just drag the script GameInput thats on a gameobject into that slot
the gameinput script was already in the player gameobject
oh I was looking at wrong script sorry
you initialized the Input script as local variable, just remove the first PlayerInputActions from the new() so its not a new local copy
mybad
Where do I go for information about serialisation and save systems for persistent worlds
Is this an incredibly complex thing that's typically handled by professional software Devs or
what do you wanna know ? its not that complicated
your best bet is using json or something easy like that
Mostly how complex it is, it's one of the main barriers im worried about at the moment lol but I haven't really looked into it
I guess I'm totally unaware of how it interacts with the engine and what's actually happening
not complicated, unity has built in methods for serializing into json for example
Alright, that's good to hear
Thank you for the help.
void SomeMethod()
{
SomeData someData = new SomeData(69, true);
var jsonString = JsonUtility.ToJson(someData);
File.WriteAllText(Path.Combine(Application.persistentDataPath, "saveFile.dat"), jsonString);
}
public struct SomeData
{
public int SomeNumber;
public bool SomeBool;
public SomeData(int someNumber, bool someBool)
{
SomeNumber = someNumber;
SomeBool = someBool;
}
}```
Very simple example
Oh very easy, alright cheers
just finished rewriting my recursive algorithm to be iterative, i feel like i've never been more with the call stack than i was during this project
I was going to mention record struct, but it's only available from C# 10.0
How do I use find on a list of structs? Getting confused by online resources
More specifically, I want to find a struct, based on only one of its elements being matched
I had never considered it before... If no match is found, Find() would still return a struct with every member set to the default value for its' type...
From what I'm reading, it sort of sounds like you'd need to test your conditions against Find()'s return value to see if it really found a match or not, which seems cumbersome.
One nice sounding alternative is to use FindIndex() instead (since it has a more definitive return value) and then just get the matching struct by that index, if it exists
Or you know just loop over the list and test the condition yourself.
If match break; simple as
That can get expensive, especially in my situation, where I need to check often
What do you think of something like this?
GridNode result = gridNodes.Find(node => node.gridPos == gridPoint);
//Result is a default struct. No match found. Safe to add into grid.
if (result.Equals(default(GridNode)))
{
gridNodes.Add(gridNode);
}
In my struct, I have an object, so it would be null as default iirc
For some reason, I completely forgot that Linq's Find method exists
I have always used First (FirstOrDefault) & Select
I'm the opposite lol
Though that's because I've been deep in unrealscript, where doing this whole find process is surprisingly easier and gives you the index in the list instead
Should work... kind of a bummer to allocate another struct each time though. You might just store the predicate somewhere and reuse it on the result (if this is happening really frequently, anyway - one extra allocation won't matter much otherwise).
But I'm pretty sure Find() is more expensive than a simple loop, what with all the call stack cycling and such.
I sort of feel like maintaining a separate index on the gridPos member might be worthwhile, if you do find this to be a performance bottleneck at some point.
Hmmm. Sounds like I might run a loop after all lol.
I guess this is all happening at start, and shouldn't really be happening afterwards, so whatever performance hit this gets only really happens once
Do you think find does not iterate the collection ?
I do, but I imagine that's a misconception at this point
If performance is an issue you could always implement your search as a parallel job
It is O(n) right now so performance really depends on the size and given how stupid fast cpu’s are I doubt you will see an issue
I agree, even more so since this is most likely only going to be happening in a "loading" phase
Could turn this list of structs into a dictionary too potentially
How would that help ?
All this is premature micro-optimizing. Surely you have more pressing issues to spend your time with
Lookups are O(1) iirc
The lookup of the list is also constant
Like list[5] will not be slower than accessing a dictionary with a key
Actually the index 5 here is the key
In a way ofc
Right, but in my situation, I wouldn't know the index. I would know the key though
What would be the key ?
In here I would be doing something like Dictionary.ContainsKey(gridPoint)
That would still loop over the key values until it finds one
Not faster than looping the list
;.;
I too dont even see how a dictionary would work here. You have vectors only, what value are you trying to associate it with
The answer is simple: profile it and see that it runs literally instantly anyways with a list.
If the list doesnt have 10k elements in it, dont worry about the speed
Even if does have 10k elements 🤣
I would worry for 100k to begin with
Like I said cpu’s are stupid fast
True
I'm curious, where would it even get bad?
When you start to notice lag spikes
Write a simple test and find out
Time to slam 5 trillion elements into the list 😛
You could literally add a for loop going through 0 to 1 million every frame and still be above 100 fps on most computers
Perfect opportunity to learn how to use the perf test framework https://docs.unity3d.com/Packages/com.unity.test-framework.performance@1.0/manual/index.html
UHHHH. 1 billion is ummm. Taking some time. Might have to do with having to spawn 1 billion cubes tho
Hello, I wanted to create a code so my animation can work, can anyone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
public float gravity = -9.81f;
public float jumpHeight = 5f;
public Transform groundCheck;
public float groundDistance = 5f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded = true;
void Update()
{
// Movements
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
Debug.Log(isGrounded);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
Vector3 move = transform.forward * x * speed;
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move((velocity + move) * Time.deltaTime);
}
}
here's the code
I already added the animation to the Animator tab, and I just need to code so the Animaton will work
What is your question though, I dont see anything animation related here
I mean, I want to add a code so that when I press the D key my character will play a walking animation
In this course, you'll explore the fundamentals of Unity’s 3D animation systems. You will: Review the core concepts for the animation systems in Unity Connect those core concepts to the functionality of the Unity Editor Apply your learning through creating and modifying simple animations Review key principles of scripting for animation
By the e...
You would do that by setting an animator parameter (bool/float/int) from your script
And having a transition that uses that parameter set up in the animator
Definitely check out that intro^
how do you code smth like this in the inspector tab so you can insert your own things
these are just serialized fields. just add [SerializeField] in front of a field in a monobehavior class, and as long as it's a supported type (most of them aside from multidimensional arrays and dictionaries) it'll show
is it possible with visual scripting too?
to be able to display an entire class (ie in the case of wanting to show something like List<Weapon>) mark the class as [System.Serializable}
No clue
thx
