#💻┃code-beginner
1 messages · Page 458 of 1
Keep in mind you need to calculate friction forces or else your character will slide
And change friction on inspector
Can't drag it to my character
nothing is wrong with the code but its been saying scalar calculations are faster than vector calculations?
is that... necessary?
Or not to your character, is it possible to drag it to the RB component in your character?
it gives slightly better performance. it's basically saying to group up the float multiplications
Basically the component that is giving physics to your capsule
i dont really understand what its referring to
the scalar calculations i mean. i'm not sure how i'd do that.
i don't have RB. I use character controller, and i guess physics is written in my code. I used some external code that i found i tought it can work since im beginner at coding, i don't think i can handle physics
instead of doing something like Vector3.one * speed * Time.deltaTime it's saying to do Vector3.one * (speed * Time.deltaTime) (this is just example code, not what you should be replacing your code with)
i used some code from ChatGPT.
this results in fewer multiplication operations since multiplying a Vector3 results in 3 operations. so Vector3.one * speed * Time.deltaTime would break down to Vector3.one * speed which is 3 operations, then the result of that * Time.deltaTime which is 3 more operations for a total of 6 multiplication operations.
Vector3.one * (speed * Time.deltaTime) breaks down to Vector3.one multiplied by the result of the second set of multiplications so a grand total of 4 multiplication operations
Oh, then my bad... No idea about physics by code at the moment, I usually use physics, don't really think is that hard to use them, just watch any simple tutorial and you'll get basics 😜
Oh good i'll do that.
Perfect!

tryna wrap my brain around this a bit
remember that a Vector3 is 3 floats. when you multiply a Vector3 by a float it results in (x * scalar, y * scalar, z * scalar). it does that for each multiplication. so instead of multiplying your Vector3 by two separate floats (the scalars) which results in doing that operation twice meaning 6 total multiplication operations, you multiply all of your scalars together then mulitply the Vector3 by the scalar. resulting in fewer multiplication operations.
remember that multiplication is commutative so it doesn't matter what order you do the multiplications in, it ends up with the exact same result either way
OH
so let's use some actual values with my previous example. Vector3.one is obviously (1, 1, 1), we'll call speed 2, and Time.deltaTime can be 0.02.
so Vector3.one * speed * Time.deltaTime is (1 * 2 * 0.02, 1 * 2 * 0.02, 1 * 2 * 0.02)
Vector3.one * (speed * Time.deltaTime) simplifies to Vector3.one * 0.04 which is (1 * 0.04, 1 * 0.04, 1 * 0.04)
wait my brain is trying to catch up now
so for each thing vector 3 has to multiply by, it multiplies all the axis by those values, so speed and Time.Deltatime are things it has to do separately
Yes
and then putting the parenthesis around the others will tell it to solve that first, and then multiply that (almost final) value to the Vector3
yes
thank you
Can someone help , How can I fix this ? the ball doesn't stop moving isnt there something I can do with the rigidbody ?
Could add physics materials with friction
I have one But the problem is what do I have to set the friction value ?
I've set it to 0.1
Alright
Also, you can add physics materials to the ground as well
Or set the friction mode to max or something
I've set to 1000 and still not workin , I'll try addin one on the ground
still not workin...
Then likely a movement code problem
Alright thx
I fixed it, I just increased the angular drag
am trying to bake my mesh but i csnt click on navigation pls help
do not cross post
wdum?
do not post the same question to multiple channels
ok
The navigation tab needs to bo opened. Window->AI->Navigation
i dont have a ai option
Did you install the AI Navigation package?
how do i do that?
package manager
is there like an event that fires whe a Grid Layout Group has completed adjusted items inside it?
i still cant select it
i think i need to import nav mesh components but i dont know how to
I don't believe so, but this shouldn't really be something you ever need to do. How did this come up?
seems there is one quite undocumented one OnCanvasGroupChanged()
having an issue moving a tranform to the position of another one at load up. Once it's up and going and I scroll mouse wheel it jumps right into the proper place
show code for how you're moving it, because this is definitely not the way to solve it lol. And your grid layout group settings
ye but i also need to download a navmesh component for the tutorial im following but idk how to do it, its from github
This packages replaces the old Nav Mesh Components system
this tutorial is probably massively out of date
float scroll = Input.GetAxis("Mouse ScrollWheel");
if (scroll != 0)
{
if (scroll > 0)
slotIndex--;
if (scroll < 0)
slotIndex++;
if (slotIndex > itemSlots.Length - 1)
slotIndex = 0;
if (slotIndex < 0)
slotIndex = itemSlots.Length - 1;
highLighter.position = itemSlots [slotIndex].icon.transform.position;
player.selectedBlock = itemSlots [slotIndex].itemID;
}
```https://gyazo.com/0e63805c99abb0798f102c46001c4c95
ok
Why is it not detecting the gallery button? https://paste.ofcode.org/R6fnmSpR5RunDQAdf2dHgu
but i still can use navigation
oh forgot to mention that chunk of code is in Update
alright, and I'm guessing your highlighter is just using layoutelement.ignorelayout?
it goes to the right spot after you move, but not on instantiation, correct?
When i click the first button it leads me to another menu, but then it doesn't detect me any button in the second menu...
yea, and if I put in that weird undocumented OnCanvasGroupChanged() the same position line of code it goes to the right spot, but if I maximize the game screen it's in the wrong spot again and only when I scroll the mouse does it jummp to the right spot. not using any layoutelemnt ignored thing
so this code is probably irrelevant, check how you're instantiating
not instantiating it, it's just an image on the canvas
oh, it's just your rect tranform not being set up right
public RectTransform highLighter;
no in the actual inspector
you're not setting up your anchors to keep it where you want
so when the canvas changes size it wanders off
you should go to #📲┃ui-ux and post your full hierarchy, because it's impossible to fix without
well I kinda was just putting it anywhere and moving it to the right place via code
that's fine
but dont be surprised when 'anywhere' is not the right spot to start
ok I might try over there then, I'm admittadly pretty newbish on UI
To make your life way, way easier just add a layout element, select ignore layout, and child it to your grid. At least then it will always be positioned relative to your grid
Cool, that alone solves it for both initial load and if I maximize game view 👍
Great, I'd recommend reading up on recttransform, pivots and anchoring though or this will absolutely be a running issue
Any ideas?
Learning what Mathf.Atan2 does and is, i wonder if u could write this as Mathf.Atan2(relative.z, relative.x) * Mathf.Rad2Deg;
if it would do the same and have the same outcome as they write it in the picture?
swapping x and z would give a different result, if that's the question
why? he calculates the angle between x and z right? thats the same as calculating it between z and x?
How would I get the rotation for one vector3 to look at anther vector3?
cause im trying to instantiate a projectile to go towards where the player is looking.
Atan2 is the angle between the x-axis and the ray to the point at the coordinates given by the argument.
So x and z there are floats representing the coordinates of a single 2D point (or two sides of a triangle). There's no such thing as "the angle between two lengths."
The angle to 2,1 is like ~30 degrees while the angle to 1,2 is ~60 degrees
but why cant u switch the two then? it stays the same doesnt it?
because 30 and 60 are not equal
so x is always 1? or?
i dont quite understand the math behind it lol
i know it calculates angles
but i dont understand why u couldnt switch the z and x in this picture
Edit: I messed up the Atan2 arguments in the illustration below - they should be reversed
the 1,2 is the 1 the x axis and the 2 the y? or the z?
I don't want my bullets to go through thin walls, but I don't want it to use rigidbodies cause of lag. How would I make it constantly go forward?
lerp
but If I make it run every frame, and in between frames it goes through walls. How would lerp help?
In 1,2 - 1 is the horizontal coordinate and 2 is the vertical (I just wrote it in that order out of habit)...
Mathf.Atan2() takes the vertical then the horizontal as arguments. But which components of a vector which you pass in might change depending on what you're doing - Atan2 works on a two-dimensional plane, but that plane can be anything
Raycast/Spherecast one step each frame so the whole path will get traced on the way
also if I set my rb to kinematic is there even any lag?
thats what i mean, in the code above i need to check the angle between z and x coordinates and then rotate the player to that, but i dont understand why he puts the x in the y argument and the z in the x argument
no
why would rigidbody cause a lag to begin with? do you have hundreds of them flying at the same time?
I'm not so sure about that. Bullets are quite fast so not many will be flying/simulated at once
Have you tested it to see if it causes lag before trying to come up with an alternative? In my experience, any performance issues with bullets comes from not pooling them
do u reccomend setting interpolation to continues cause its fast?
interpolation doesn't matter, it only changes the visuals, not the physics. the collision detection mode is what you likely mean and yes, it should be set to continuous
you know you are allowed, indeed should, test things yourself to see if they work with your use case
There's no such thing as "the angle between the z and x coordinates..." Coordinates define a single point. Atan2 retrieves the angle from the positive horizontal axis to the point.
By passing x, z in, you're treating the x-axis as the vertical and the z-axis as the horizontal... So you're retrieving the angle from the positive z-axis to that point. In the code you've posted, it's "the angle from this object's transform.forward to the target"
That order gives you an angle on the x/z plane, measured from the positive z axis
what would happen then if u switch them? u rotate to the wrong angle?
Yeah - my brain is spaghettifying at this point, but I believe then you'd get the angle to the target from this object's transform.right (it's positive x axis). Totally valid if you want an angle to which would rotate the thing such that it's right side faces the target 👌
But maybe try it and see?
well, my brain isnt braining anymore by now lol
that is such a hard thing to understand
This should shoot straight right? For some reason shoot at a 45º angle
I have tried both
whats wrong with
shotpoint.forward * speed;
not working
not a very helpful reply
how can I spawn something through script from assets on a spawner object?
with the atan2 function, is the x axis always 0 and the opposite 270 or -90?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnItems : MonoBehaviour
{
public GameObject itemToSpawn;
public GameObject spawner;
public GameObject Items;
float lastSpawnTime;
void Awake()
{
lastSpawnTime = Time.time + 5;
Debug.Log(lastSpawnTime);
}
void Update()
{
if (Input.GetKeyUp("h") && Time.time - lastSpawnTime > 5)
{
Debug.Log("Key was just pressed");
lastSpawnTime = Time.time;
if (itemToSpawn.name != "Shit")
{
Instantiate(itemToSpawn, Items.transform);
}
else if (itemToSpawn.name != "Shit")
{
Instantiate(itemToSpawn, Items.transform);
}
}
}
/*void FixedUpdate()
{
if (Time.time - lastSpawnTime > 5)
{
Debug.Log(lastSpawnTime);
lastSpawnTime = Time.time;
Debug.Log(lastSpawnTime);
}
}*/
}
how can I spawn 3 times with a delay of 0.5 seconds if the itemToSpawn is Shit?
do I have to create coroutine or what?
If you want a delay in your code you either need a coroutine, async, or to use a timer variable that you increment and check each frame
I have a problem with my seed. I have made it so that the seed is the same as a random number I'm generating, but the map does not change with the new number, only when I edit it manually in the editor. The seed that's currently generated is actually 8.
Forgot to say thank you for helping me last time, the mesh collider works👍
Serialized values in the Inspector will ALWAYS take precedence over values in the code
else if (itemToSpawn.name == "Shit")
{
Instantiate(itemToSpawn, Items.transform);
}
what's the best to use here to spawn Shit 3 times with a delay of 0.5 seconds?
Either start a coroutine with a loop or using a timer variable and mentioned and incrementing a counter
I think best is coroutine with a loop, how do I do it?
Do what? Which part?
So should I change the value to not be serialized? Or remove it from the inspector?
if you want to use the value set in code it cannot be serialized
Okok, I have to completely honest, I do not know how to change that🥲
is it a public variable?
It is a public int
so change it to private or, if it needs to be public, change it to a property
Okok I'll try that, thank you
Debug.Log("Key was just pressed");
lastSpawnTime = Time.time;
GameObject spawnedObject;
if (itemToSpawn.name != "Shit")
{
spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
}
else if (itemToSpawn.name == "Shit")
{
IEnumerator Fade()
{
for (int i = 0; i == 3; i += 1)
{
spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
yield return new WaitForSeconds(.5f);
}
}
Fade();
}
I tried this way but it doesn't work
how?
else if (itemToSpawn.name == "Shit")
{
IEnumerator Fade()
{
for (int i = 0; i > 3; i += 1)
{
spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
yield return new WaitForSeconds(.5f);
}
}
StartCoroutine(Fade());
}
idk
I have no other ideas now
I make it private, but the map stays the same. I've tried to make it a property, not sure if I'm doing it correctly, but that doesn't wortk either. I've tried using it as a property while its private and public and nothing seems to work, what would your next suggestion be
maybe share some !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.
""cs
Ag gorrel
'''cs
public int Seed
{
set { seed = Mathf.CeilToInt(RandNum); ; }
}
MAN
I keep pressing ewnter too soon
public int Seed
{
set { seed = Mathf.CeilToInt(RandNum); ; }
}
There we go
so if i understand this code correctly, the atan2() takes the input from the horizontal input and the vertical input then converts it into degrees and then the transform.rotation tells the object to rotate x degrees around the y axis, and the x degrees is the outcome u get from the atan2? is that right?
so you still have your public int seed ?
Just made it private, still doesn't work
I would send the whole code but it's about 200 lines of code
of course not, what you need is
public int seed
{
get { return Mathf.CeilToInt(RandNum); } }
that is why the bot message has a section about large code blocks
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is the whole script
you do not need any of this
private int Seed
{
set { seed = Mathf.CeilToInt(RandNum); }
}
void Awake()
{
seed = Mathf.CeilToInt(RandNum);
}
just do what I showed above
You're setting your seed in Awake, but getting the RandNum in Start. So you get the random number after you've already set the seed.
I'll try and move that
i'm making a 2d platformer, but there are hundreds of tutorials to make one. been looking through some, but all are different.
is there a base which you guys advice to use? one with most of the basics (coyote time, input buffering etc.)
The rest of it is for noise maps and things like that, generating the mesh. Should I make a new script for the seed?
I don't know if this has been covered here before, but the free version of ChatGPT is very good at answering questions about coding in Unity. At least for simple questions. I think it would solve a lot of problems for newbies in this chat, instead of waiting for an answer or asking again and again.
for simple things maybe but you are better off not using chatgpt
it can straight up be malicious in what you are trying to do and when you dont have the knowledge to filter good from bad info yet its not a good idea
how do i make circlecast ignore a kayer
You can input a layermask which has all but that layer
or make a layermask with only that layer and reverse it, then input it, easier if you add more layers
im kinda scared of doing that
whats scaring you? 😄
too many G.o
just do a public LayerMask, which lets you pick the layers in the inspector, then reverse it, i belive reversing a mask was mask = ~mask;
Choose one, watch it, research what it doesn't cover. You won't find a perfect tutorial showcasing exactly everything you need. Or even better, break down the kind of game you want to do into separate mechanics and research them individually if you don't know how to handle them.
i dont rly understand what atan2 is, i understand that its to calculate angles but first they say the arguments are (y, x) and then they say the arguments are (x,y)?
alright thank you, tbh was hoping for the easy way out this time. (i'm lazy)
!learn is always a good place to start, and it should have 2d platformer stuff in there too
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how do I make coroutine to work?
what is not working?
The arguments are always the same, unless you use a different method. When in doubt consult the docs:
https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html
doesn't spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
well i dont understand the docs lol, im so confused on this function, so he sets the arguments (y,x) to (direction.x, direction.z) why? is the direction.x the vertical axis and the direction.z the horizontal axis?
for (int i = 0; i > 3; i += 1)
->
for (int i = 0; i < 3; i += 1)
your exit condition is flipped
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Why did my falloff map stop working
https://hastebin.com/share/kebiyenexo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If you get yourself a pencil and a piece of paper and visualize it, you'll see that x and z are one both the "ground plane".
And yes, direction.x would be the vertical axis, direction.z is the horizonal axis. The rotation then results in rotating towards the target
If you're having a hard time visualizing something, it's always an option to just code it in and see by yourself how it works
so the y in atan2 is not actually the y that brings your object higher up? its the vertical line if u look from above your object? and the top of the vertical line, is that always 0°? and then right is 90° then -180° etc..?
Look at one wall in your room and then at the wall next to it
i thought if u look from above to your object u have the vertical and the horizontal and u set the direction.x = to that vertical line (y) and the z to (x) and then if u look straight ahead its 0° and if u go right u look 90°
One would be in xy plane, the other in zy plane
yes
Unless you have walls at weird angles, but these are still 2D planes
indeed
isnt this a right conclusion?
The short version is, as far as I'm aware: atan2(y, x) -> z rotation, atan2(y, z) -> x rotation, atan(z, x) -> y rotation
Not from above, but from a certain perspective to see one of the planes
Right axis is 0°
Thanks
Take this image as reference
yes i know this, but what my explanation right or wrong?
huh? right axis is 0? but in my tutorial he sets the y argument = the direction.x? and the top axis is 0° for him
how so not above? what certain perspective then? im in a 3d scene rn btw
Maybe you unchecked useFalloff in the inspector 🤷♂️
can someone help me setup vsc for unity it doesnt work for some reason
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I think there's was option somewhere to switch the scene editor cam to change view perspective to view one of the planes, but I'm not sure if I'm not confusing it with something else right now, and I'm not anywhere near my PC to check
Basically image yourself aligning with one of the axis, so that you look in the same direction as the axis is pointing
i thought i understood the function but the more u explain the function the more chinese it gets for me lmao, its not that i dont know what atan2 is its how and what to give in the arguments, u have to pass in a (y,x) but i dont understand why my tutorial passes the direction.x and direction.z in it?? why would u do that? he also said atan2 sees the object from top down view and the u have a vertical line and a horizontal line, the vertical line is the y and the horizontal the x, that makes it easy for me to understand why u set the direction.x equal to the y argument because u want to go forward and by 0°...
I'm using official unity asset character controller (using first person controller) why when I'm trying to slowly aim it's not aiming?
this is the script
https://pastebin.com/SgCeNYAj
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
atan2(y, x) where x is on the axis that's 0°
So if atan2(direction.y, direction.z) Z axis is where it's 0. If you flip it around you'll just get an angle with an opposite sign if I'm not mistaken (so 30 instead of -30 for example)
the problem is that it just can't aim slowly
he sets it like this atan2(direction.x, direction.z) so ur saying that the x argument(direction.z) is where its 0? that would mean to the right is 0????
I'm bad with verbally explaining math, it I were next to you I'd just do a few hand explanations and you'd probably get it lmao
the script is confusing idk how to fix it
I didn't unfortunately, wish it was that simple. I seems like the mesh collider is off (like not in the right position) now too? Even if I use the falloff map
oooh, so he actually tells atan2 that the y axis is the direction.x so left and right and the x axis wich is 0° is the direction.z so forward and backwards, and thats why forward is 0° because he says the x is the z axis?
Easiest to explain would be with an example.
If direction.x is 1 and direction.z is 0 then atan2(1, 0) = 90°, which means that if you're rotated as such that you're looking straight at the z axis, you need to rotate by 90° to look at the target.
It's the right shpe, but orientated wrong
is it off rotation by 180?
yes i completely understand this, but i dont understand the arguments, because in the explanation its (y,x)? do they mean the y axis and x axis or just 2 axis and if u put the axis in the x argument its gonna have that 0°?
Don't think of y and x as the literal y and x axis in unity
Just relative to the plane you're looking at
oohh lol, its just 2 axis that u choose?
Yes.
aahh so the y argument is not the y axis, its just like saying atan2(x1, x2) 2 axis?
Yes
lol, i completely misunderstood :/
so the axis u put in the x is gonna have 0°? so in this case its z so forward is gonna be 0°
ig?
yes
Pretty much
Yes
oof, thank u very much, im pretty bad at maths and i rly need to improve it... thanks for the explanation lol
Sebastion doesn't cover this in his tutorial, but the color map never lines up with the noise generation, it's due to the plane needing to be rotated about the Y axis 180 because the linear array is filled from 0,0 being in that upper right corner instead of the bottom left like the docs say it is
No worries, I'm not an expert at math either, just don't take what you read too literaly, math is abstract and can be applied in many different scenarios
sorry, corrected that, I meant Y axis
maybe it's a line with _cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
what does ClampAngle do?
Hi, really new here and in need of some help, currently I want to rotate my top half of my model to where my mouse is currently at, but for some reason the back of my model always follow the mouse not the front, and the model is not rotating properly either. I really need the help, and for those who will look at it thank you 🙂
Code for the mouse follow: https://pastebin.com/YFDVBcav
Note: already added an empty object to parent my top half of the model it did fix the issue where the model is facing up when rotating
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the problem is basically that my camera aim isn't sensitive enough
Nvm it work
was this
ChildScream = ChildScreams[randScream];
this is the line thats causing me trouble
it still lets me play and its an error that pops up only sometimes?
ChildScream = ChildScreams[randScream];
Child.clip = ChildScream;
Child.Play();``` heres tghe thing that includes randscream
maybe itl help idk
the only way that will cause that error is if ChildScreams has a length of zero, i.e. is an empty array
yeah but the thing is dont arrays 0 index/
it starts from 0
yes, but if Length =0 array[0] does not exist
Hi, i am kinda new to unity and i wanted to make a simple 2d shooter game to practice some things i learnt. i have a square with movement and jumping scripts and also interaction. but i wanna add a gun that follows the cursor but i dont really know much about rotation and cursor tracking
so should i change the 0 to 1?
no, check for zero length before executing the code
so an if statement?
like if lenght = 0 then idk
yes, how else ?
but like what do i tell it to do then....
like yes if lenght = 0 then do specificly what?
nothing
or print out the value just before accessing the array to at least see what it is trying to access
so im just putting an empty if statement?
you can do if length > 0 // Do the code you have
maybe you filled hte array in playmode and restarted it and it went back to empty
actually i think i found the issue
the array was somehow cleared?
i have 4 diff enemies and 1 of the enemies array had an empty array
yeș
sorry for wasting yalls time
thanks for the help tho
where do I find this error so I can try and fix it, I know in what script, just which array should I be looking at
can you help me with this camera setting ? I accidentally hit a button and now my camera movement is kind of odd so I want to revert it back but I don't know how.
read the second line
double click it, should open the code at the error
Is it line 32?
only one way to find out . . .
what do you think?
that or the computer got it wrong
i wanted to make a simple 2d shooter game. i have a square with movement and jumping scripts and also interaction. but i wanna add a gun that follows the cursor but i dont really know much about rotation and cursor tracking.
click the cube in the middle. you enabled orthographic camera
basically a 2d camera
thank you
np
this problem isn't gone even tho I tried to find the problem in the code
rotate the Z, you can find the direction from gun to mouse by subtracting their positions
i tried to track the mouse position but it doesnt work. its giving me an error that says object reference not set to an instance of an object
show code, but something is not assigned
Nvm I figured it out now, I just had to change this variable
here it is
did you assign mainCamera in the inspector?
😅i forgot to.its working now though. but how do i make the gun follow the cursor now?
need to change the guns rotation based on the direction to the mouse
can i use Vector3.RotateTowards?
Why do the colours only render if I update the script manually?
Did you include his code for public override void OnInspectorGUI() ?
need to watch his videos end to end a few times, he covers tons of details in that series
im following a tutorial and i should be able to look left and right but i cant? anyone knows why
xRotation -= mouseY?
ye to rotate around the x axis
I'm sure I did, I just don't remember in what script that is
found it
this is what i was able to make so far. how can i fix what's happening here?
I did, but it's not working. Very strange.
probably rotating the wrong axis?
its rotating on all axis. ill try to lock rotation on the z axis
you only want it to rotate on 1, cant remember if its X or Z or what
Maybe consider showing the !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.
ill try locking each one and see if it works
Remove Time.deltaTime - Brackey made a mistake.
Other than that, make sure the player variable has referenced the Player body object (not the camera) - assuming this component is on the camera.
I keep seeing this but even the unity docs shows multiply by time.deltatime, have a good link to why you shouldn't?
i tried "transform.eulerAngles = new Vector3 (eulerAngles.x, fixedRotation, fixedRotation);" but its giving me an error on eulerAngles.x i wrote the same line of code in another script and it worked. also, fixedrotation is set to 0
Get Axis is already normalized and relative to the delta. You do not need to interpolate it further relative to time.
The main doc should have discussed this.. one sec.
it says this: This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value., then they turn right around and multiply by time.deltatime....go figure
If the axis is mapped to the mouse, the value is different and will not be in the range of -1...1. Instead it'll be the current mouse delta multiplied by the axis sensitivity. Typically a positive value means the mouse is moving right/down and a negative value means the mouse is moving left/up.
This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value.
Get axis can be mapped to buttons or mouse. If it's mapped to the mouse, you do not need the delta variable because it's already a delta.
yes and then they do this
// Make it move 10 meters per second instead of 10 meters per frame...
translation *= Time.deltaTime;
rotation *= Time.deltaTime;
The example binds WASD as axes, not the mouse
ah!
The second example uses mouse and there's no deltaTime
Theirs was relative to buttons (horizontal and vertical)
interesting and confusing all at once lol
The physical explanation is: you moved the mouse X centimeters over Y seconds. Whether at 60 FPS or 3 FPS this doesn't change, so it's framerate-independent!
This is also valid for the new input system IIRC, the mouse movement is also passed as a delta so no need to multiply by deltaTime
With the delta time removed from the equation, you should be getting more responsive results. If nothing is still happening, you've likely referenced the wrong object as the Player.
i have a weird bug with my camera when i move with my player (wasd) my camera spins around like crazy
Maybe consider showing the updated code
How to post !code
Use links for large code blocks or you can embed some statements here if they aren't too long/large using backticks.
📃 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.
So I have these 2 lines
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * Time.deltaTime * mouseSensitivityX);
verticalLookRotation += Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSensitivityY;
And I tried taking out the Time.deltatime. Had to adjust mouseSEnsitivity to no avail and the camera goes nuts
Hello! My game is working perfectly fine in the editor NO errors NO bugs nothing but when i build the game some triggers are not working like they should be and an object is missing.
Gindipple🤭
Would you mind helping me with the map not rendering, if you have any idea as to why It's not rendering when I start my game.
can someone tell me how to randomize float?
Best if anyone available can help, sometimes others see things that someone else doesn't. But in general, show code and ask question. Sebastion's code is all on github, did you start with that or type it in as you watched the videos?
"name of float" = Random.Range("Min value","Max Value");
ok
Inb4 they copy that directly
Just replace the min and max with what you want and put the name of your float in the first part
https://docs.unity3d.com/ScriptReference/Random.Range.html
You can look at the docs for an example
I'm currently watching one, and I tried replacing the code with his from GitHub but It still doesn't seem to work. I'm also not too sure what script needs to change, and I have a few
He has 2 different things going on at once, one is the plane at editor time the other is the mesh at runtime. So which one isn't working for you?
The mesh isn't working, Like in the video it's just black, even in the editor, until I click on generate, change the DrawMode, or Turn a bool off and on again.
So the plane he uses is intended to just be for the development process to see the noise adjustments, that's why he wanted it editable in the edit mode, for fast changes. The mesh you eventually can't go on adjusting at runtime, gets too complicated., but it should render when you hit play at least
It should, but it don't. What script fo you think might be causing this? The MapDisplay?
what is iterator in C#? idk what this word means
@cosmic quail google doesn't help
it just says something like
"iterator method"
but it doesn't say what's iterator
did you try googling "what is iterator in C#" and opening the first result?
site doesn't open and words are hard
description doesn't really say much what makes sense
is GameObject iterator?
maybe look at the other results then, this site seems to give explanations and examples https://www.alanzucconi.com/2017/01/22/iterators-c-yield-ienumerable-ienumerator/
is that a coroutine?
this
should have posted this in the first place rather than asking what iterators are
I'm trying to make GameObject spawnedObject; still keep the spawnedObject = Instantiate(itemToSpawn, Items.transform);
"coroutines" use the C# iterator feature yes. You cannot use in, out, or ref with them
why do you have a void inside a method
I was messing with it
using ref in coroutine isn't possible and I should just do it like that?
That will not work as intended, re-assigning the variable inside a method won't update the variable outside that method, unless ref is used, which isn't possible here
Why do you need the instantiated object outside the method?
void Update()
{
if (Input.GetKeyUp("h") && Time.time - lastSpawnTime > 4)
{
Debug.Log("Key was just pressed");
lastSpawnTime = Time.time;
GameObject spawnedObject;
IEnumerator SpawnItem()
{
GameObject sigma;
for (int i = 0; i < 3; i += 1)
{
sigma = Instantiate(itemToSpawn, Items.transform);
sigma.transform.position = spawner.transform.position;
spawnedObject = sigma;
yield return new WaitForSeconds(.5f);
}
}
if (itemToSpawn.name != "Shit")
{
spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
//Vector3 direction = spawner.transform.position - (spawner.transform.position - spawnedObject.transform.position) * 800f;
//Debug.Log(spawner.transform.position - direction);
float randomX = Random.Range(-10f, 10f) / 10f;
float randomZ = Random.Range(-10f, 10f) / 10f;
spawnedObject.GetComponent<Rigidbody>().AddForce(new Vector3(randomX, -4, randomZ), ForceMode.Impulse);
}
else if (itemToSpawn.name == "Shit")
{
IEnumerator SpawnItem()
{
for (int i = 0; i < 3; i += 1)
{
spawnedObject = Instantiate(itemToSpawn, Items.transform);
spawnedObject.transform.position = spawner.transform.position;
yield return new WaitForSeconds(.5f);
}
}
StartCoroutine(SpawnItem());
}
}
}
because there's also other part
oh
I read it wrong
because I don't want to have the spawnedObject.GetComponent<Rigidbody>().AddForce(new Vector3(randomX, -4, randomZ), ForceMode.Impulse); part inside the function
Why not?
I don't know but it just seems to be more customizable
Nope, you can take the the if statements inside the coroutine instead, that will do the same thing.
Just make it so the yield instruction is still the last one within the loop, or else it'll add force with a 0.5 second delay.
Alternatively the part that adds force could be another script attached directly onto the prefab you Instantiate
wdym Just make it so the yield instruction is still the last one within the loop, or else it'll add force with a 0.5 second delay?
Hello , how can i make it returns random numbers like 0.3 0.4124 0.921314 ? it only returns 1 or 0 although its float not int
You Instantiate, do some stuff then yield. Put the rigidbody stuff before the yield or it'll execute later on
make it 0f and 2f to turn them into floats
These numbers are ints. If you need floats add an f at the end of the number to instruct C# that they are to be interpreted as floats: (0f, 2f)
why it will execute later on?
Because you tell it to do so by using yield return new WaitForSeconds(0.5f)
Wait for 0.5 seconds at this point
ah yes
You need to understand the code you are writing/copying
@short hazel oh i see thank you !
didnt think to do that
I know how to instantiate a prefab when I reference it from GUI with a [SerializeField], but how do I reference a prefab from code if I dont wan't to do it from the GUI?
put the prefab in a Resources folder and use Resources.Load
Thanks a lot
im not even sure what happened because i dont remember changing anything but now my entire movement script is failing
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and it keeps giving me this message that scalar calculations are faster than vector calculations for 40 and 41. i thought i had a grasp on it but ig not
i noticed something was wrong when the character couldnt really move, and originally i thought the problem was specifically the WASD function of the script, but not even the gravity works now
so the entire script is the problem, but the script is active on the player object
it was working yesterday and now its just 
why have you made no attempt to debug?
it hasnt given me any errors
actually
sorry the script itself didnt give me any errors, but it kept saying that it was missing a reference
Debugging is not about fixing errors, it's about seeing what your code actually does
then it cant find your CharacterController
that was an error on a button thing but im not sure its related
maybe its not the movement script thats the problem?
if you debugged it like I said, you would know
i mean i dont see anything that feels unusual
I see one problem straight away, your usage of deltaTime
You should definitely add debug.logs all over. See what executes and what doesn't. See if the values are what you expect at the moment of execution
Oh, you're so experienced you can debug code by 'feel' ?
nothing particularly stands out, i mean
i will try the debug.logs to see whats not turning on
oh i think i kind of have an idea
its not being used
sprint is giving a return but i must have removed the lines actually applying gravity and allowing movement
might just start the project over i think its just falling apart at this point
oh im fucking dense
the solution to the problem was right below the problem and i deleted the 
okay got it up and running again 👍
Anyone have a tutorial or general concept about an inventory system, where i can find items with attributes (ie "handgun", storyitem") and get their prefab?
there's only like 4-5 pages on google for the topic
how can i lock the Z pos on an image ?
how is it being modified currently?
chatgpt 🤷
(i was kidding)
Store it in a list or dictionary of enum to prefab
is this a question for me or for the guy above?
I currently store them in a list, but am not really sure how to handle the search for the correct item type. Got any ideas?
no was for you
from the context, this is a response for you . . .
okay uh let me go check real quick
its being modified via transform and being set to the input.mouseposition
well the simple answer is mask off the z component so you don't move it in that dir
okay what is masking
subtracting it from the vextor3, hidng it from the next calc
as it implies, to mask is to hide
do i do this in the transform.position = input.mouseposition?
you could on the fly creat a new vector3 and for hte x and y parts pass them along, for the z part just put in 0
this wouldn't work on world objects
difficult to know for sure without your code
thats kinda all the code
mousePosition is a screen coordinate / pixel position
oh if its UI its fine . and input mouse position doesn't have a z pos
so yea just force z part to 0 always
then why does the Z value get sent to mars?
idle, if i try to drag it the z value gets sent to mars and when i let go everythings okay again
The z component of the Vector3 is always 0.
the only thing here that when removed lets me drag it
BUT it doesnt make it snap back into place
is the
=> mars is at z=0
transform.Setparent(transform.root)
setting parent is what's messing up the z prob
maybe you want to pass true to KeepsWorldPos argument
see thats the thing
in the tutorial im following all of this works right?
and im supposed to add
transform.SetAsLastChild();
it probably wouldnt be a published tutorial if it doesnt work
ohh could you link tutorial
9 times out of 10 you missed some minor detail in hte turtorial
i really dont think so this time
i like the guy cause he explains what the code does
and form that i can see that i really do have everything, not 1:1 but its correct enough to work
tbh I dont even know whats going on in this image
is this what ur trying to do or
where in your code do you do the line transform.SetLastSibling??
no dude the issue is the item DISSAPEARS 😭
even if i put it in same issue
when you drag or when you end drag?
while dragging
in the idle position
when not dragged and after dragged
it snaps back to where it should be right
but while dragging it just
dissapears?
look at these 2
its.... there? but its not showing up
looks like its outside the canvas maybe ?
yeah uh for some reason
show a screenshot of the inspector while you dragging it with hierarchy visible
^ this plz
wait lemme debug something
okay so yes it does leave canvas right
and i know now what code makes it do that
parentAfterDrag = transform.parent;
transform.SetParent(parentAfterDrag);
i dont know why
what happens
where it suspposed to be
it goes and becomes a part of the player?, which is at the top of the hierarchy ig
even his does that
yet it simply dissapears
if i remove all the code except transform.pos = input.mousepos then i can drag it fine but it wont snap into place when i let go
the code that controlls that is also the code that breaks everything...
the point of transform.SetAsLastChild is to counteract this, and make it visible but it doesnt do the job right
Can someone help pls, I want that for int value I delete 1 Tkey
that's a strange group by predicate there
what=?
that code is mostly nonsense, please post it correctly for help
how should I post it correctly i dont get 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.
instead of using Transform.root why not assign the proper transform so you know for sure its using the canvas..
root is going to go to the top most object
What the hell is this even trying to do
my thoughts exactly
is that comparing a variable to itself?
idk how groups work
apparently
What are you trying to use groups for at all
What is this supposed to accomplish
im trying to find out how many of a specific TKey are in the Dictionary
transform.parent instead of root?
idk how to do it otherwise
there can be only one
The answer is 1
no make a proper field you can assign
A dictionary can only have one of each key
so the answer of "how many of this TKey are in the dictionary" is either 0 or 1
Then i mean list
what are you trying to do? what is the mechanic? what is this for ? etc..
So is it a list, or is it a dictionary?
it has multiple values of the same so its a list?
How about instead of guessing, you just look at the code and check
What's TKey?
the type for Dict
it says dictionary
but doesnt doesnt look like a dictionary
TKey is the generic name for the type a key of a dictionary
okay, well ill try that next but i changed it to transform.parent and magically, it wont snap into place
This is a more advanced way of writing ItemCount += intentoryList.Length;. #archived-code-advanced
Dictionary of what to what and which are you looking for
bro what
A dictionary of what, to what, and which of the two are you looking for?
hes asking you to explain the dictionary
if its a dictionary why did you screenshot inspector of an array/list
its a dictionary for what, goes to where and which one of the 2 elements are you looking for?
Dictionary<Foo, Bar> is referred to as a "Dictionary of Foo to Bar"
ItemType Gameobject
Okay, so, Dictionary<ItemType, GameObject>. So, it maps an ItemType to a specific GameObject. What are you trying to actually do with this information right now?
idk what that means, so is it still broken or
point is, if i change it the snap-to function wont work, ie snapping to where it supposed to be after i let go
like a inventory yk
Im just trying to see how many of a given Itemtype are in this dictionary and then removing it for (value) times
youu mean the parent after or before drag?
first, to get rid of confusion its not an ACTUAL function in the code
Dictionary<ItemType, GameObject> can have exactly 0 or 1 of a given ItemType
on drag start, if i change from transform.root to anything else it wont snap to where its supposed to after i let go
whats putting it where its supposed to go is a grid component
which is where? havent shown the hirerchy while dragging
then Im just trying to see how many of a given Gameobject are in this dictionary and then removing it for (value) timess
i have
which one is the canvas? there is no label
canvases areee let me check
Getting the count is easy, but if you find them, which ones do you want to remove? If the same object is in there under let's say five keys, and you want to remove four copies of that game object, how do you intend to know which key-value pair to keep?
uh i got an error but this time i actually didnt do anything
the gameobject named iteminventory is the canvas
its not an error in VS but in unity's console
and what is a canvas named iteminventory is beyond me..
Hi all, I'm hoping someone can help with a little bit of code I'm having trouble with.
newRecipeItemAvailable.text =
GameManager.gameManagerInstance.stationResourcesManager.availableComponentList
[newBuildableItemRecipe.dataContainer.stationModuleRecipeList[i].componentAvailableIndex].componentAmount.ToString();
Full Code here
https://hastebin.com/share/gebafinuti.csharp
It's a little bit messy/simple at the moment.
Basically I have two lists of Classes (AvailableComponentList which keeps track of how many components the player has 'in Stock' (First Image) The Entries in this list are of the Class 'AvailableComponents'. This lives on my StationResourceManager script which is 'attached' to my GameManager.
public class AvailableComponents
{
public string componentName;
public int componentAmount;
}
and a 'StationModuleRecipeList' in which the entries are of the 'StationConstructionRecipe' Class which lives on the Scriptable Object for the specific module the player wants to build.
public class StationConstructionRecipe
{
public string componentName;
public int componentAmount;
public int componentAvailableIndex;
}
I'm using the 'componentAvailableIndex' int to reference the specific Resource Manager list entry to then run a check to see if the player has enough of that resource to build the Module.
The problem I'm having lies in the line of code I've posted inline above. Everything up until that point works great, but it's seemingly not finding the 'componentAmount' list entry. So, would anyone be able to see any errors/issues in terms of finding said value in the way that I've written it above? Been staring at it for a while and just can't see an issue.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you aint really helping here thanks
huh?
im naming it for organising
"InventoryCanvas" would make more sense to me..
I am literally answering exactly the questions you are asking
If these don't help, ask better questions
lets not get stuck on naming semantics
you are literally asking me question, I came here to get normal answers
so it said "hey you dont have tmp pro stuff so we're going to import it" and it did
and its working, but now at line 525 its giving an error in the unity console that the object reference not set to an instance of the object
naming is important to identify whats what... Anyway looks like when you do root it goes to Player
i just wanted to show the full page cuz its not my script
it just appeared with an error?
Because you seem to have absolutely no idea what you even want to do. Your question of "how do I know how many of a key are in a dictionary" was answered. It's 1. If the key is in the dictionary at all, it's 1.
yeah, and the player is uh, not a canvas lol
should i just make it a canvas?
there are 3 things on that line that could be null, find out which
uh nvm
i delete the error and it doesnt seem to come back up
or disconnect the whole Inventorycanvas thing from the player?
Then u just lack knowledge and cant seem to understand my questions right
cause i put it in thinking i need it to be a child of the player or it wont work right but since its just ui over the full screen then i dont think it needs to be a child
if you can't explain your problem clearly , you wont be able to solve it
i hope it doesnt come back to bite me
Digi really doesn't lack, and tbh that attitude ain't going to get you any help.
noo , instead of using things that depend too much ion hierarchy order. Dont use things like transform.root or tranform.parent unless you're absolutely know for sure who the parent is etc
I have literally been answering questions here for half a decade and you don't know whether you are using a dictionary or a list
okay i fixed it
i just removed it and made the whole inventory its own parent
So maybe get your shit together and figure out what you even want to happen. If you literally do not even know what you want how can you expect me to tell you how to do it
I mean..you could've just made a field for Transform..but whatever floats your boat lol
is there a way to have a button have an outline
the boat is floaty
trying to link up this button to
yes but this isn't a coding question now is it..
and im a capitan thatll sail till i crash
true
this guy was giving me attitude first fr, attacking a newbie over very nice
"I am the captain now"
sorry but the jack sparrow doesnt negotiate
with somali pirates
its kaptaejn but he pronounces it kapitan
asking you to clarify your question isn't an attitude.
you should know better than that
oh shit you right let me delete that. forgot where i was for a second 😛
I am literally the only person who was attempting to make sense of your nonsense scribblings of garbage code enough to help you while everyone else just assumed you were too far gone to help. I guess they were right on that front.
Have fun never making your game and generally continuing to fail at everything you attempt to do. I'm done.
oh nice very nice thanks for your very kind words!
hes right tho
as a newbie we uh, we suck at coding lol so listen to what he says
but i do agree that he can come off as agressive in the way he talks
I was still waiting for him to post his code correctly, which, apparently, was too much to ask
idk man am new around here, and I think i have both a list and a dictionary thats what caused confusion
what caused confusion is that you didnt really explain exactly what you want
not with the code, but in general
what is the idea you are trying to execute yk
Nah, apparently asking for clarification is an "attack"
nono you just have a agressive way of speaking i kinda agree with him on that
if you are not sure, then post the full code so someone who knows how to read the code can determine which you are using
That being SAID, still he didnt give correct clarity
so lets start here
tbh, I don't think Digi is aggressive at all, just right to the point without any dicking about. lol.
what is your idea @bleak sleet ?
tbh the time i been here its pretty rare see digi being a bit more stern , its usually the other person being furstrating tbh>
Can sympathize, helping someone who wont try to help themselves gets frustrating..
yeah and some people understand directness as agressive
i say that as someone who is extremely direct, so its better to dilute the directness because otherwise it can come off as agressive
even though it might not really be, people can understand it in that way
Clear explanations go a loooong way to getting useful help. That's why my questions tend to be on the long side, as much detail as possible about what you want to do and what the issue is. lol.
The most common 'useless' request for help is "why is this broken?" lol.
I get called the "aggressive" or "with attitude" 90% of the time here
Sorry got busy at work. Dont know if anyone else replied
You either store them in lists specific to each item, which could be done by a dictionary, or loop through the list and just check. I'd store them in a dictionary of enum to list of prefab
apparently being direct is aggression on these new Zboyz
yea, but as a newbie, from my perspective im a dumb dumb and youre the masterclass superteacher who knows everything so i dont have to explain it
Zboyz lol
Im trying to do crafting table and want to do it variable so that in future I can easily make something take 2 of specific Items but I have no idea how to check if theres those items inside and how to remove them properly. I keep getting error messages
perhaps you should learn the tools you are attempting to use before you use them..
better
yes maybe... learning by doing...
It would help to share the errors?
seems easy.. create an Item.cs and hold a list/array of Items
yes but also searching things you dont know.
How do dictionaries work and such..
You can get frustrated when your question doesnt make sense..
its ok im gona try later by myself gtg w dog now
can you have a child object with a script tell its parent to no longer be active or can i only work downwards
I got it working with a list of scriptable objects with keywords and reference to the prefab. Thanks for the support, the message kind of got drowned in stupid replies like "google it"
i and i think we suggest to actually not do that and look up how a crafting grid system is best implemented
ya, once
haha yeah I havent had my matcha yet 🍵
Yeah, this is where a lot of people fall over. Never assume anything. Especially being newbies (I still am too, but learning slowly. lol.), the code could be so very very wrong it would have no chance of actually doing what you want it to do, so even the best coder in the world wouldn't be able to just look at it and figure it out.
doing it yourself will just get you furtstadt
its good to do it yourself if you plan on researching as you go
its not good if you expect to know it all out of gate.
thats the point, this is what we think as newbies, that youre allknowledgeale on the topic yk
we
literally think, that youre tech wizards
the thing i see most w/ newbies is "my code should be doing this.. but it does this instead"
... sir, it does the exact thing you told it to do
but that fixes itself w/ time
Yeah, that was my point in my previous comment. 🙂
idk if this is overcomplicating it but im going to try to attach separate scripts to specific buttons (one will turn off the parent object), and then have the player have a script that allows them to turn it on/off.
idk if it'll work but i'll find out ig
I wish..half the time they skip the "whats supposed to happen instead" bit
"my script no work"
as long as ur only turning it off (once it is disabled the script /child will not be able to turn on its parent (itself practically)
i had my own moment with this
we all do..
tried to put 2 contradicting if statements
Yep, the good old "Why is this broken?" question. lol.
why is the code that wont work unless a nuke ray from a supernova explosion touches the one bit and changes it to 1...... not working?
lol shows screenshot of random scene stuff "Why is it doing this?"
my first problem w/ that was
id' set something in the if statement. and then immediately check in teh else if it was not ..
then ur basically running a useless if statement
if makes thing false.. else runs regardless lol
LMAO. And then screenshot the code. When I first came on here, didn't bother me cause I didn't know enough to offer advice/answers, but now it really winds me up. lol.
oh i just realized im working out of order 
i was trying to set up the buttons to work but i cant even test if the buttons work because i havent set it up to allow the mouse to freely move
if (isActive)
{
isActive = false; // This sets 'isActive' to false
}
else if (!isActive)
{
Debug.Log("isActive is false now!"); // This will always run because 'isActive' was just set to false
}```
isnt that without the else if but just another if
or did i brain farted
i think an else would actually work?
idk im still drinking my first cup of coffee ☕ ¯_(ツ)_/¯
i think of else if like a switch case
if the first one was hit, the rest dont evaluate no?
- if statement: Checks the condition. If true, the code block executes, and then it skips the rest.
- else if statement: Only checked if the previous if (or else if) was false. If true, its block executes, and the rest are skipped.
- else statement: Executes only if none of the above conditions are true.
that code is nonsense, shame on you
is it bad practice to attach debug.log to a bunch of stuff to constantly keep seeing if its registering things
even if nothing is broken yet
No, it's very good practice.
noted
thank you 👍
Test your C# code online with .NET Fiddle code editor.
yo how do i store functions inside a list
wait nvm i asked chat gpt
cool.. i been looking for a good c# compiler just for fun
List<System.Action>
List<Func>
do both work
i us System.Action
yeah action is simpler though (method has no return)
alr
depends on your method signature
Code screenshot? tsk tsk. lol. (j/k :-P)
I was mainly showing the Console log but yea
Yeah I know, just couldn't resist. lol.
Func is for methods that return value, Action is fine if its a void
private void DrawCenteredButton(string buttonName, System.Action onClick)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
// Draw button with custom style
if (GUILayout.Button(buttonName, buttonStyle))
{
onClick?.Invoke();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}``` attribute button
I use also an Action as method param to a IEnumerator
a nice modular way to make many timers for diff methods/actions
i remember when i was very new.. i asked if i could pass a method into another method.. and someone called me stoopid..
said c# wasn't a macro language 😐
you'll be better off in life if you question everything that thing tells you
best useage for passing a method into a method is for async or coroutines to get a callback on completion
that'd be great for my loading system
very handy indeed
Yeah, it does crack me up that it really struggles with arrays. It has no idea how to count indeces. lol.
yeah, but for very basic stuff it helps
whats horrible is it gets totally stuck when u go deep enough
private IEnumerator CoolRepeatingTimer(float timeUntilSomething, Action method)
{
while (true)
{
var time = 0f;
while (time < timeUntilSomething)
{
yield return null;
time += Time.deltaTime;
}
method?.Invoke();
yield return null;
}
}```
ops
not saying it doesn't.. just never take what it says as concrete facts
i use it quite a bit to make tedious things abit less tedious
tbh I use it occasionally just to get it to type out code that I'm feeling too lazy at the time to type myself. lol.
for example.. giving it a list of enums and having it vomit out a switch statement for me
I know enough now that I can spot whether it's wrong or not.
or atleast get a feeling its going off the deep end 😅
lol.
yes if you can't spot whats wrong it can lead you into very dark places lol
That is horrible, should be an array of Action and use the enum as the index
I mean if it works it works amirite
I was studying the C++ code for GTA3 repo yesterday and their Enemy AI is basically one giant switch lol
It's 'knowledge' is very out of date too. I asked it once (gpt3.5) how up to date its Unity c# knowledge was and it was something like 2017.
IEnumerator BootEnvironments()
{
FindLightController();
yield return GetRandomWaitTime();
environmentProgress = 100f;
IncrementSector();
}
IEnumerator BootSystems()
{
FindGamePlayObjects();
SetupSettings();
yield return GetRandomWaitTime();
systemsProgress = 100f;
IncrementSector();
}
IEnumerator BootGameSetup()
{
SetupPlayer();
yield return GetRandomWaitTime();
gameSetupProgress = 100f;
IncrementSector();
}
IEnumerator BootVisualFX()
{
FindCanvasObjects();
yield return GetRandomWaitTime();
visualFXProgress = 100f;
IncrementSector();
}``` guess i could make this *functional* now 😄
@languid spire 👆 horrible v2
tbh its due for a refactor.. this codebase is going on 2 years old..
soo past me thought it was legit 🤣
I always evaluate
Time spent refactoring vs time spent rewriting it from scratch
This is a typical example of making code up as you go along instead of actually designing it first and then writing it
umm wtf?
Sorry, not sorry for bumping this. lol. I know it's a lot to look at, but any ideas? lol.
70% of my code 😢
design first is not realistic, so you're good 😛
Im horrible at designs and graphs
ya, i wasn't skilled enough to design it first.. and then build it..
my workflow consisted of.. building up a little at a time..
then having a guide I could actually conceptualize..
then rebuilding it basically from scratch
luckily I'm more of a generalist than a "coder" so to me as long a it works and its clear intent is there, I dont bother unless there is a performance issue
design first is 100% requiered if you want to produce good code
steve had c# grow up along side him.. its easier for him 😈
design first, but to some degree, sure... I've seen so many people (and I've done that too) spend week on design, and all that fails a little after you actually start writing code and using it
this is not a C# thing, it's a professional programmer thing
either that or you somehow did not foresee something unexpected while developing it
I tend to reach good code much quicker if I have only a high-level design plan and then write code that mostly does it and iterate
I have a bad habit of coming up with new ideas for the thing while I'm writing/building it. lol.
yeah I dont mind constantly iterating over it as long as I have a general idea/concept in mind already
same.. i keep scratch pad/paper next to my desk.. when that happens i just jot it down.. and try to move forward.. w/o dwelling on it too much
nothing is carved in stone but it's a damn sight easier and quicker to tweak a design than it is to refactor a complete code base
sure, but the design misses various details, also if it takes a long time to produce the design, you could be weeks in without doing any of the... practical work
whereas if you do high-level design, write some code that does some of it, then iterate, you kinda balance these... gives you an option to finish early, if some priorities changed
haha fresh out of college CS students
and saves yourself many more weeks documenting the spaghetti you produced
too much yap less practice/exp
hey guys.
is there a way for me to get a list of all types derived from a base type (in this case, Action_Node)
and then use them as a list of type Action_Node, instead of a list of type Type?
i cant simply convert them with the as keyword. so are there any other ways to do this?
I don't produce spaghetti 🤷♂️
if you dont design, believe me, you produce spaghetti
c#sharpghetti 🍜
What is the specific error you're getting on this
I do design, just do it as an iterative process of refinement, and of coruse even the initial one is not 🤢 unless I need to potentially finish a new feature in a day
some people get carried away with 20 days of design and only then code... that's what I'm against
Can you show the code for CreateNode?
It looks like this function takes an Action_Node, not a type
void CreateNode(Node node) {
var n = graph.CreateNode(node);
node.name = n.GetType().Name.Replace('_', ' ');
CreateNodeView(node);
}```
oh youre right
trying to make an AI enemy controller but i get a weird error like this
Try moving your 'agent' gameobject up a little (above the navmesh surface)
i need to place him extremely high then... and then i get error failed to create agent because there is no valid navmesh
Not really sure what you mean tbh. Basically your enemy (with the agent component) essentially raycasts down from the bottom of the collider to 'find' the navmesh, so if it's too low it can't see the navmesh, hence the first error. (that's a simplistic explanation and the best I understand it)
Also, might be better in https://discordapp.com/channels/489222168727519232/763502536354168882
what is 'weird' about the error? What dont you understand about it?
wait, what should the navmesh be? the ground?
Whatever the enemy walks/moves on.
Why is "just above the navmesh" mean "exteremly high"?
It should just be up enough to know for sure its collider isn't intersecting the floor
Yeah that confused me tbh.
is this a good way of creating a new instance of a type, that will always be derived from typeof(Node), and then converting it to a Node?
this is how im using the method :
Well, if the thing you're creating is a child class of Node, all instances will be of type Node. I have no idea what the point of all this reflection is, but it looks like Node might be a ScriptableObject. Wouldn't it be easier to just manually create a few instances and load them from Resources or something?
its not a scriptable object.
node itself derives from nothing
its as base as you can get
Okay, so, you can create one via new just fine. I'm guessing there's a lot of sub-classes that extend Node?
i need to get all types deriving from Node, then create a new instance of those types, no matter what they are, then use them as a Node.
thats why im doing all of the convertions.
how can i just use new?
well its weird, i'v put the navmesh (the ground) into the navmesh variable of the enemy and i still get the error look..
and the code
For example, new Action_Node()
Your NavMeshAgent is disabled
its not garuenteed to be a actin node. it might be any type that derives from it.
im using this as a replacement graph.CreateNode((t)Activator.CreateInstance(type) as Node)
Okay, so, you just need one blank instance of each deriving type of Node then?
yes
indeed, but it stays the same if i enable it, i just disabled it to look what happens and forgot to turn it on again
So from the types, you want to get the constructor and invoke that method. It even lets you pass parameters to it if you have constructors that take them
https://stackoverflow.com/questions/3255697/using-c-sharp-reflection-to-call-a-constructor
Although that does seem to be what you're doing with CreateInstance as well, which I thought was ScriptableObjects (they also use CreateInstance to be instantiated)
is this any better then the code i sent? it seems a bit longer.
So I think your code here could work, but I think the casting could be made simpler:
graph.CreateNode((t)Activator.CreateInstance(type)) should be enough
Yeah, I think I circled back to the same thing you were already doing after talking myself out of my own alternative
i need the as Node at the end:
alright, ty 👍
Actually, I think what you might need is to constrain the type parameter. You might need a where t : Node on the function declaration
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
okay ill add that too!
how do i change where unity stores builds?
which builds?
when you do
"build and run"
where it stores the build
that it runs
the file explorer?
Wherever you designated it to be when you first made the build
can i change that?
i know where it is i wanna change where its saved
If you just do a normal build (not build and run), it should ask you where
and then when i do build and run itll save it there right=?
why not try it
I almost never do Build and Run , i simply save to folder I want and the folder automatically opens when its done. I just run the exe..
This is too ez
What is
idk I did it somehow
2 errors i had
and it works as i wanted it to
what's the name of the boolean function that goes like this: var = bool ? a : b
trying to google if it works with enums
ternary operator
Wdym by "works with enums"?
It works with any expression that returns a bool
do you mean
enumyouchoose==wantedenum kind of thing
== expression returns a bool
it would work with anything that returns a bool
Yall im watching a video and I'm following the script the first line he put worked but the second one doesent and when i type the popups dont come up this is the script https://gdl.space/hokiquwazo.http
And what does the tutorial's code for that line look like?
You need to configure your IDE
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Then the "pop-ups" will appear
And you will make fewer typing mistakes like this one
I can send A pic of it
It was working before tho
Your code has errors. So configuring your IDE will point it out.
Sure, go ahead
But why did it randomly stop working,m
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 175
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-08-13
Because you typed it wrong
Code doesn't "randomly" change itself.
called it
What did i type wrong then?
this isn't the code you sent in the link
You added a semicolon, also pls don't share code with just a picture from your phone
hey walleliu
I think this is still the tutorial picture
Cannot modify the return value of 'Transform.position' because it is not a variable (CS1612)
This is mine
No, this was yours
#💻┃code-beginner message
He also put a semicolon but i wasnt able to sc it in time
Transform.position = Transform.position.yz + xvalue * Vector3.right
then why didn't you send the whole thing properly
I thought i did?
Sorry I'm just very confused 😅
you sent 4 lines
3 of them whitespaces
you were meant to send the Entire script as you had it
Then why did your pastebin say otherwise
Does anyone have an idea why this:
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.zero, Mathf.Infinity, LayerMask.GetMask("UI"));
if (hit.collider != null) hit.collider.transform.gameObject.GetComponent<Food_1>().GiveToppings(order);
ReturnToHolder();
}```
always trigger twice? its not an issue so far, but any debugs write twice, so it could be a problem when i add scores
Wait sorry Vector3 doesn't have those vector operations, tform.position = new Vector3(xvalue, tform.y, tform.z)
which code did you think we were referring to then ? Anyway send the actual script as you have it written
What calls Dropped
Idk whats a pastebin😭😭
Ok
letme try
I thought ylal were tlaking about the one line of code
well its imprtant to see exactly how you wrote it, hence those paste your code and send link type of websites
also, is your script placed on a gameobject ?
when there is no mouse input, but still has the item reference:
// if input detected
else if (item != null)
{
Drop();
return;
}
void Drop()
{
active = false;
item.Dropped();
item = null;
}```
So, Drop is likely getting called twice. What calls that
Okay, and what's the actual error
I would just post your full code so we dont have to chase the scripts.
so im making a 2d game and i want it that if the character hits a wall its momentum is flipped i wanted to make empty gameobjects on both sides and if collided put a negative sign on the velocity is there a more efficient way of doing this?
drop is called by the else if, and that is simply on Update()
it doesent work in unity it says "Assets\Pipemovescript.cs(19,60): error CS0117: 'Vector3' does not contain a definition for 'Left'"
So check the tutorial
They didn't write Left
if its not underlining that red inside your code editor, you need to configure your IDE was it was suggested
it wont fix the issue but will help you avoid these simple mistakes
Anyone that knows TextMeshPro can help me? I'm getting different results when calling a TypeWriter coroutine before and after a Canvas.ForceUpdateCanvases() and it's driving me crazy, idk what is wrong.
hmmm i change it then
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how do i do that
`` uiText.text = sb.ToString();
if (autoScrollRect)
{
Canvas.ForceUpdateCanvases ();
autoScrollRect.verticalNormalizedPosition = 0f;
}
StartCoroutine(TypeWriter(uiText.textInfo.characterCount));
}
IEnumerator TypeWriter(int charCount){
while (uiText.maxVisibleCharacters < charCount)
{
uiText.maxVisibleCharacters++;
yield return new WaitForSeconds(0.05f);
}
}
#endregion``
am I doing something wrong os is TMP being finicky?
anyone knows why i cant drag the TMP text into the variable?
now it says "The referenced script (Unknown) on this Behaviour is missing!"
because its textmesh and you seem to have the UI one
Probably because you are trying to drag a TextMeshProUGUI into a TextMeshPro field or vice-versa. Your variable should be of the type TMP_Text to cover both cases
could you show your code? are you referencing a TMPro.TextMeshProUGUI element?
Do you have any other errors
use links for large code
dont think so thats all it says in unity
you saved during playmode ?
where does it say that Console or on the object ?
paste bin is banned in my country is there any other website?
📃 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.
so i have a list of voids using list<system.action> called "rollMejoras" , and i wanna add one of those to a button onclick i thought this would work but it wont :(
no idea havent pressd play sense i first asked the question
console
clear console and press play see if it comes up again
the error says "The non-invokable member 'LogicManagerScript.rollMejoras' cannot be used as a method." (its translated from spanish so it might not be accurate)
TMP_Text doesnt work either
what is the error saying ?
it will
I would do as one answer suggested and use TMP_Text instead of TextMeshPro
@rich adder here!
AddListener requires a function as a parameter. By calling rollMejoras with a parameter of 0, you are instead calling rollMejoras and passing the return value to AddListener
how do i make it so it doesent delete stuff in hierachy when i press play
yes because thats not how you access element of array, use []brackets
this doesnt change anything
It doesn't delete anything you don't specifically tell it to
mate lol () is for methods [] is for array/list
Cannot convert from 'System.Action' to 'UnityEngine.Events.UnityAction'
how do i know if i told it delete sum
If you want the button to call rollMejoras(0), then you'll need to make a parameterless function that calls it. Either:
public void DoRollMejorasZero(){ rollMejoras(0) }
and then AddListener(DoRollMejorasZero)
Or you could one-line it:
AddListener(() => rollMejoras(0));
it doesnt lol, look
Did you call Destroy
Are you trying to reference a scene object on a prefab?
i dont recall doing that
https://hastebin.com/share/ixofomulab.csharp
I wanna make it like subway surfers like when you on the right you need twice input to go to left but in this code it takes one input to go to the left from the right
I want "right -> middle -> left"
it goes "right -> left"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
show the Text object