#💻┃code-beginner
1 messages · Page 424 of 1
What about this
this is a bunch of variables on a different object, what does this have to do with the question
Do you have another canvas in front of this one?
And does this canvas have a GraphicRaycaster component?
well first yes, but if i delete it the button is still not clickable?
ill check
yes
should i change anything in it ?
and even if, the button that doesnt work, its not under or over any button in the other canvas
Well im trying to use the MovementController to get the WASD input into a direction
that i then multiply
by the current speed
Okay, but what method do you intend to use to actually move something
and then move that way
Show the inspectors of the button and the canvas that the button is on
Lemme see in the tutorial cause im kind off using it to translate my code from godot into unity
the canvas that the button is a child of right?
yes
its a lil difficult cause they have alot of stuff
should i send each individually or is there something specific you need?
like as much info into one pic cause i cant get the full inspector in one
Idk he just used public CharacterController Controller; then proceeded to use Controller.Move(move * Current_Speed * DeltaTime)
I am just going to look for anything amiss. Send multiple pictures if you want
Okay, and did you do that?
Yes
Then why didn't you show that
You can see it here except that its before adding current speed and delta time
cause it didnt work without them
first pic is parent, next 3 are button
"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: 171
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-07-14
Did they name their script CharacterController in the tutorial
I now see the problem
Your button component is disabled
w h a t
h o w
i havent touched it???
Misclick maybe?
Unitypackage file not opening sumthing error
fixed that problem
thanks
Did they name their script CharacterController in the tutorial
Bro i literally changed it and its still the same
omd
one sec
Now it works
thank you man
im blind
I'm just glad that it wasn't something else because I was out of debugging options
one last question, if i was to make a main menu, would that be a whole nother scene?
and while that scene is running, the other one with the actual game wont right?
It could be. There are many doors, Ed-Boy
Simplest is probably just a canvas you toggle
ehh, rather not
but an additive scene is probably better for organizational purposes
yes
and while that scene is running the actual game scene wont right?
the scene that has the game
If you change scenes, the scene that gets unloaded ceases to exist and every object in it is destroyed
You could use additive scene loading to have multiple scenes at once
You would be loading that scene from disk as it was defined in the inspector
question, if i was to make a game with multiple indivually explorable areas that are big on their own
this would require mulitple scenes right?
Probably
or atlesat it would be better with them
im just asking if itll work on build
like will it work if the base scene is the main menu and you load into the GAME scene ig
it changes to it ig
it was because charactercontroller, your script was a class inherited from monobehavior and charactercontroller, the component is also a class so they were causing conflict and i'm guessing your script is like a higher priority class
I'm having this UI overlapping issue and can't find a reliable fix
What do I do about this?
Since this is a code channel, post the code related to the issue
If you're using a custom property drawer, then you probably didn't override GetPropertyHeight or made a mistake
{
[System.Serializable]
public class Wave
{
public string Name;
public Transform Enemy;
public int Count;
public float SpawnRate;
}
public Wave[] Waves;
}```
(I'm on 2021.3.4f1 as well)
hello , i have a list of Components i want to make foreach loop and then disable every component in the list in the foreach loop like this :
foreach(Component componentcomp in NonNetComps)
componentcomp.enabled = false;
but i get an error on enabled why i cant access it ?
Do you have a custom property drawer for the Wave class?
like an editor script?
@sleek marten you don't have to serialize the second class like that?
You can just serialize the fields themselves
See if that fixes your issue
The thing he does is perfectly valid
Oh no I see what your doing my fault
I've never used one these before
Try updating your unity editor version then
What version of unity are you using?
You're 36 versions behind the latest LTS version for 2021
That could be it
2021.3.4f1
are you saying to use something like 2022?
Is there a way to get the gizmo box to rotate with the game object? When I rotate the object that has the gizmo, the gizmo stays at the same orientation
Pretty much backup your project every time you update your editor
Are you using ALL 8 versions?
nope
Then uninstall them
but everytime I start a group project they always want to use a different version
And how many group project are you in at once
@desert plinth if you can use a sphere instead of cube, no need to rotate it
Then you can remove half of these versions
And politely ask others to use the latest LTS in the next projects
Yeah...could do that actually...thanks I guess
say you create a class in script a, is it possible to create an instance of that class through script b?
Yes
how?
ok yeah
Should I make my resources and my tools different ScriptableObject scripts?
or is it better to make an "item" scriptable object?
this is because I want my tools to have atributes like strength, durability
You can make an abstract scriptable object, if your items have common properties (like a name, a rarity, etc.)
Then derive from it, for each different item type that has specific properties (a gun would have an initial magazine capacity, and armor would have strength)
That fixed it! thank you!
is there a way to run a script without play mode? i wanna change the text size of a button when the screen resolution changes. (in this case when i drag the editor window from my 1080p monitor to my 720p tv) i finally figured out how the anchors work.
You may not need to, you can check the "Auto font size" in the button's underlying TextMeshPro Text component
oh
That way it will adapt to the container (the button) size
thank you
why does it make the text bigger when i switch screens
thats literally the opposite of what i want to happen
-_-
Can I rename all the appeareances of a CLASS name?
I know you can with variables but what about classes?
use the refactoring tools to do so
Same way as renaming variables. The keybind depends on which code editor you're using
With the caret (blinking text edition cursor) over the name, hit Ctrl + R twice to begin the rename operation
I get an error
It says I can´t rename this
still not working
are you doing it from the class or from some other file?
Show a screenshot of what you're doing
other file
yeah so that's likely the problem
oh okay, it is
Atom is a class and atoms is a List<Atom>, when i run foreach(class Atom in atoms) it gives me a ton of errors, and when i run foreach(Atom in List<Atom> atoms) it doesn't change anything
First, configure VS Code so it highlights errors for you
!vscode
how should i add a momentum system while using character controller
momentum?
like the player walks for a while and takes time to stop?
you can access characterController's velocity, such that when input keys are released you can keep moving the player based on velocity
thanks
How can i get the correct x,y of the rotated triangle?
I’m pretty new to Unity/c# and every time I try to make a simple game, I get stuck for hours trying to figure out why my code doesn’t work, often to no avail. Is it better to just abandon my work and start over, or try to stick it out even when feeling totally lost and helpless?
Stick it out and ask for help. Software development is largely a process of breaking and fixing things - the time you invest in figuring out a problem and solving it will pay dividends later. You'll start to avoid creating the same bugs, and you'll get better at hunting and killing them.
stick to it. debugging is a very important part of programming
dumb way is to transform.rotatearound
As an afterthought, when you're feeling totally lost or overwhelmed, sometimes it can help to switch scopes for a while. Instead of dropping the project, pivot to focusing on a different aspect of it for a bit. Maybe even a totally new scene to explore some other feature
Okay thanks. I guess I’ll post one of my questions here in case someone knows: For some reason when I run my game and click the mouse button, my objects’ gravity scale changes. I used to have a code that did that so I disabled the code, removed the script component, and then even deleted the code, none of which worked. This wasn’t a problem until I changed my GameObject into a prefab, does that have anything to do with it?
If you are having trouble figuring out what your code is doing I would suggest learning to use the debugger then you can step through your code line by line and see what it does exactly
these replay files are massive man is there any way i can compress them at all?
Apply compression :P
how can i do that?
I'm not entirely sure - I'm looking into it now, out of curiousity. But it would seem reasonable to me to zip/gzip/7zip them
28mb per replay is wild
thats with like 4 people for a 6 minute match
just a bunch of input data
Anotber reson saving binary data is better suited. filesize should be a lot smaller
this code gives me my speed at which my rigidbody is moving, is there any way to split this in 2 to check what speed my forward/backward, left/right speeds are?
var vel = rb.velocity; //to get a Vector3 representation of the velocity
speed = vel.magnitude;
Just get the Z and X no?
each axis is already the speed it is moving along that axis
that works but i need it to not go in the negatives
then get its absolute value
any ideas for how can I make my ragdoll take steps manually and make walking a little bit a skill issue in my game?
Lookup active ragdoll
I already have an active ragdoll
I am trying to do something like the game steppy pants
I'm sure there are videos/ instructions on getting motion
I'll take a look
!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 there a way to make something happen when you release getkey? because getkeyup only works when you press and instantly release.
how else would you want ?
GetKeyUp works usually
if you mean you want some actions to happen across time after release, then enable a bool, put it update if statement
sorry it works
it stopped working normally thats why I asked but then I saw a line made that
in this loop, i am running through a list of instances of the Atom class. i want to add the electrons and protons variables of all the instances of the Atom class within this list to the totalElectrons and totalProtons variables. im doing this through a foreach loop, but am getting this error
nvm
ok
wym?
yes, but how to i count up all the electrons/protons from all the instances in my list?
using "the instance"?
you keep reassinigng new value each iteration
if you want to add them up you use +=
oh nvm I see your doing var + var
share !code properly cause its hard to paste line of code to show you
📃 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.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Molecule {
public string moleculeID;
public Molecule(string MoleculeID) {
this.moleculeID = MoleculeID;
}
public List<Atom> atoms = null;
public float totalAtoms = 0;
public float totalElectrons = 0;
public float totalProtons = 0;
void Start() {
}
public void AddAtom() {
}
public void GetStats() {
totalAtoms = 0;
totalElectrons = 0;
totalProtons = 0;
foreach (Atom atom in atoms) {
totalAtoms = totalAtoms + 1;
totalElectrons = totalElectrons + Atom.electrons;
totalProtons = totalProtons + Atom.protons;
}
}
}
public class Atom {
public float protons;
public float electrons;
public string atomID;
public Atom(float Protons, float Electrons, string AtomID) {
this.protons = Protons;
this.electrons = Electrons;
this.atomID = AtomID;
}
}```
!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.
no need to spam the command again..
i didnt
you can just tel them that they used the wrong one
I already sent it
oh i see mb
alright i fixed the formatting
foreach (Atom atom in atoms) {
totalElectrons += atom.electrons;
totalProtons += atom.protons;
}
technically you dont need totalAtoms in the loop..
just count the totalatoms = atoms.Count
OHHH im stupid
my bad
It sounds like you would generally need to include the relevant dlls for a compression library to your project (possibly multiple libraries to support multiple target platforms), after which you could utilize whatever functionality they offer.
I see Unity also provides a com.unity.sharp-zip-lib package wrapping SharpZipLib - it looks like to compress you'd use a StreamWriter to write your JSON string to a MemoryStream, run that through one of the library's compression interfaces, and write the output stream to disk... And for decompression, I would think the same in reverse, but starting with a FileStream and the corresponding decompression method instead.
Depending on how large a replay can become, it might also be necessary to perform this work in a separate thread to avoid hanging the application 😬
It looks like there are also a number of assets available on the store which could tackle the problem.
This is all somewhat out of my wheelhouse and I reckon that I'm overlooking important things and alternatives. I lean towards navarone's suggestion of using binary serialization first. And then maybe applying compression on top of that, if necessary.
Interesting! thanks for your analysis. yeah, hanging is an issue, because my game freezes for like 3 seconds whenever it ends trying to save the file
The built-in classes in System.IO.Compression should also work in Unity
And for the game freezing, offload the task to another thread or use the async methods
Hello I am trying to get a button to change to a bool to true then to false alternating on each click is there a way to do that
Sure thing, in the button's click handler method: val = !val; where val is your bool variable you want to toggle
"val is now equals to the opposite value of val", which effectively toggles the value each time this line is executed
this is suppose to clamp the vector right? my character accelerates fast so im limiting speed but it doesnt clamp it
xvel = Mathf.Clamp(xvel, -maxairspeed, maxairspeed);
rb.velocity = new Vector3(xvel, rb.velocity.y, rb.velocity.z);
am i doing something wrong?
Okay thank you will this change each time or only once?
Each time this line is executed
this only clamps the x value
Okay so it will swap each time
If that line is put in the button's click function, yes
might have to show more of the script. hard to say from this alone
Yep it is thank you very much
here are the xvel values
var xvel = rb.velocity.x;
var zvel = rb.velocity.z;
speedX = Mathf.Abs(xvel);
speedZ = Mathf.Abs(zvel);
i dont know if its because my character accelerates to fast but that shouldnt be a problem for clamping
i dont think
public void onClickPanelShowDispear()
{
isPanelShown = !false;
}
When this method is ran will isPanelShown = true
Well yes, NOT false is true
why not just write = true
Scroll back up at my example
The clamp will clamp. Have you verified that rb.velocity.x is definitively exceeding maxairspeed? In order to do so consistently, something else would have to be affecting rb.velocity after the code you shared above
bcs I want it to swap when the method is ran
if you want a toggle you have to assign the opposite of the current state
like SRP2 said above so it would be isPanelShown = !isPanelShown
i have a public float telling me what my x and z movement is in an absolute value, so yes i can verify its going over limit. It could be my acceleration
I think that is waht i did wrong let me try
Hello Together!
For the past year, I have been learning C# because I was curious about how real programming is, and I really like it. So, I thought about learning Unity so I could maybe live my dream of becoming a small indie developer. I started watching tutorials and noticed that the guy in the tutorial had a list with the methods he was typing. I didn’t have such a list, so I would love to know if someone knows if this is a setting or a plugin. To understand what I mean, I will send a picture with the list.
Thanks!
yep that was it now it disapears on click and comes back thank you!
It sounds like you may need to configure your !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
Thanks for responding so fast! I will try it.
ah it seems to be clamping it just looks funky because of my rigidbody acceleration.
📃 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.
https://paste.ofcode.org/BTjyZaBDhRQBaNBQuy98Hw for some reason my camera and player starts shaking a bunch after making this script
ill send a video
I've got an object I want to look at a target, but it will not work, so I'm trying to see what the matter is. Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lookAtPlayerBlank : MonoBehaviour
{
//Variable for our look at target
public GameObject player;
// Update is called once per frame
private void OnTriggerStay(Collider other)
{
// Tell gameobject to look at the target.
if (other.gameObject.CompareTag("Player"))
{
transform.LookAt(player.transform);
}
}
}```
Hello, can you send me a code to open and close the door in my Unity game by pressing the E key?
its easy as f mate
Just make a public bool on the door then raycast on the door , use E to toggle bool
use the bool to open/close door with update rotation, or just use animation.
also don't crosspost in #archived-code-general stick to #💻┃code-beginner you already posted here
put debug.log before if statement, make sure its even called
btw if other is player you don't need the player since its already inside other if tag is found
transform.LookAt(other.transform)
https://paste.ofcode.org/t2p2TwhT54VW8gEBVt22r6
Iam trying to check whether the fillings in the cocktailglass are what they should be in the recipe
I printed out the fillings that are currently in the glass with: "Key-Filling: " ...
Then it goes over every ingredient in the recipe and checks if the ingredient is even existing in the glass fillings
if yes it goes over to the else statement and checks if the filling is in a 0.1 range
But in the console output It instantly returns false it prints(no such ingredient in recipe) but it definitely is as printed with key-filling and key-recipe
I hope smb can help me, I would be really grateful
It's probably due to the fact that ingredients in one dictionary aren't the "same" as ingredients in the other dictionary. See, when you create objects with new, a new space in memory is made to contain it. You might have two ingredients with name "WATER", but they're not at the same place in memory so they're deemed different, that's most likely why it's not found in the dictionaries.
Can you post the definition of the IngredientTags class here?
To make sure my theory actually holds
how can i draw custom shapes with debug?
like a custom concave shape or somethong using coordinates
1min please
could someone help me?
not if you don't say whats wrong
im having trouble with this
ive tried freezing rotations but it doesnt work
In the editor? Gizmos/Debug/Handles.DrawLine, Handles.DrawBezier etc.
Multiple Handles.DrawAAConvexPolygon for a convex shape
But how do I fix it then? I have no idea
I figured out what the problem was, but thank you.
Make that class implement the IEquatable<IngredientTags> interface. That will force you to implement a custom Equals and GetHashCode method, in which you can provide your own logic to determine whether two IngredientTags are considered the same (maybe by comparing their Ingredient property?). Once you do that, the Dictionary will recognize that you implemented this interface, and should start using it.
If you mean the Debug class then theres nothing but DrawLine.
But Gizmos/Handles could help and you can draw Handles in OnDrawGizmos
so like for each coordinate in a list i'd draw lines between them?
Sure, if you want outlines/a path then use DrawLine
Handles.DrawAAPolyLine/DrawPolyLine lets you draw multiple lines at once
i see
i was just trying to draw a 2d shape for a custom fixed point number collider im making
Bunch of lines would be easiest then
OK thank you, but sorry for asking ehm how do i implement sth? like this?:
public class IngredientTags : IEquatable<IngredientTags>
because that throws an error
bunch of drawlines then?
Sure, or just DrawPolyLine like I said
Yes that is expected, because you need to actually implement the interface now. Scroll back up and read my full message again
awesome, thanks
Ok thank you I will try it tomorrow because I need sleep now but I thank you very much I will write in here if I get any more errors or if it works tomorrow but thanks for now again
On a subjective note, I find myself substantially less inclined to assist someone who presents themselves as "dick rider." You might find that more people are willing to help if you choose a less vulgar nickname for this space.
It's not clear how the objects in your video relate to the code you posted. It's also not clear what the "grapple state" of the player is within the video. Capturing the video directly on your computer instead of with a phone is also nice - not only is it easier to watch, but we could see additional context such as your hierarchy, and console messages which might have been logged.
sorry I changed my name, I’m figuring out how to record a video right now
Alright, had to makie an edit, but I'm trying to make it so my script ensures that a projectile is shot out of the given gameObject at the right trigger, which is a player entering. Anything I need to do or add?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaunchProjectile : MonoBehaviour
{
public GameObject projectile;
public GameObject player;
public float launchVelocity = 700f;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
GameObject ball = Instantiate(projectile, transform.position, transform.rotation);
ball.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0, launchVelocity, 0));
}
}
}
I only think it’s related because when I started writing it that’s when everything got glitchy
Is it glitchy even when you're not grappled to something?
That seems fine at a glance - give it a run 👍
yes, I just got a recording I’ll send it
I did, Which is why I'm very confused as to why it isn't working.
Your collider isn't flagged as "Is Trigger", so OnTriggerEnter() will never be called
That is some nutty shaking... I don't think that this script is responsible however, as it happens without the grapple joint, and the script really doesn't perform any work outside of creating/destroying the joint
oh okay
i think ill try changing the movement script to something more advanced and see if that fixes it
how do i make a variable increase slowly
like not instantly
Like a float?
do it in update += (someMultiplier) *Time.deltaTime
easily googleable btw
mb
Hey, can someone explain to me why I am getting this error?
public Room GetRoomScriptAt(Vector2Int index)
{
GameObject roomObject = roomObjects.Find(r => r.GetComponent<Room>().RoomIndex==index);
if(roomObject !=null)
return roomObject.GetComponent<Room>();
return null;
}
I need some help breaking down the Find function here.
I'm looking at the webpage that describes how Find() works but I'm not sure what the "r => r" portion means. A "Lambda expression...?"
Find seems like some search function that returns a match but I'm not sure how to interpret the function's input here
Your class is implementing an interface, but it doesn't implement the members which the interface requires. Your class needs to contain all of the things it's whining about
ok, and how do I contain all of the things it wants? I barley have anything in my interface. Here look:
public interface ISate {
void Input(bool KeysPressed, bool IsGrounded);
void Update();
}```
look at the spelling
I set it on isTrigger, but it didn't make anything happen.
also the using Unity.VisualScripting; - are you intending to use stuff from the visual scripting namespace?
look at how this is spelt, compared to what you have in the screenshot above. Also in the screenshot, look at this section here
oh hahaha. I did not even notice that. But I am still getting errors here even after changing everything. Is it because I has to actually add them in the class or is there something else going on here?
From your screenshot, it looks like your collider is on the tip of that red thing. If that's correct, it seems like maybe it's kind of high - does the player really hit it clear up there?
You might want to throw a Debug.Log("Hit!"); at the top of your OnTriggerEnter() method, just to help narrow down the space in which the problem might be.
That's correct - yeah, you need to add those methods. VS should provide the option to automatically add the basic definitions, or you can write them by hand 👍
ah ok thank you for your help
The box is a cube with the mesh collider pulled off. However, I think the problem is that the script is attached to that, so it won't proc without the player touching that cube. So what I need to do is make it bigger, I think?
That was exactly the problem.
can you serialise a property?
unity cannot serialize properties, but it can serialize the backing field. if you are using an auto property you can target its backing field for an attribute using field: otherwise. a full property has an explicit backing field so you'd just serialize that
note that the auto property cannot be readonly otherwise the generated backing field will be readonly as well which cannot be serialized
so this is some code to calulate speed on the x axis but can i change that to be local right/left or forward/backward?
IEnumerator CalcVelocity()
{
while (Application.isPlaying)
{
// Position at frame start
Vector3 prevPos = new Vector3(transform.position.x, 0, 0);
// Wait till it the end of the frame
yield return new WaitForEndOfFrame();
// Calculate velocity: Velocity = DeltaPosition / DeltaTime
Vector3 currVel = (new Vector3(transform.position.x, 0, 0) - prevPos) / Time.deltaTime;
Newspeed = currVel.magnitude;
}
}
How do I make a variable that contains an object component?
Wdym with object component?
Maybe you want the Component type. But that is kind of unusua - what are you actually trying to do?
public GameObject Obj;?
Im trying to refer to transform.Position and store it inside a variable.
transform.position is a Vector3, which is a value type, so accessing it will create a copy instead of referring to the original
If you want a copy of it then do a Vector3 field
If you want it to stay updated then reference a Transform instead, and access its position when you want
Ok, thanks.
Not sure if this is the place, but I've been getting a ton of trouble with WebGL in Unity 2021.3.8f1. All the way until this recent project webGL was able to export flawlessly. Now it can't. Not sure why.
Tried uninstalling and reinstalling the package. Leaving compression methods to disable, deformation fallback and minimalized stripping Here is the usual errors when I try :
Also can't export an empty project. Not just the project I'm working on.
How can I check if a SO that heritates from an abstract class has that component (the own, not the abstract)?
if(mySO is Something theTempVar)
but I can only access the mother class
the theTempVar is the inherited SO
thTempVar?
sorry, Im just very confused
if mySO (original abstact) is Something (the childclass SO)
can you put me an example?
you mean you have this setup (example) ?
public abstract class Animal : ScriptableObject{
}
public class Human : Animal{
}```
yeah, that´s it
and you want to know if the SO is Human?
yes
public class SomeContainerClass : MonoBehaviour{
public void SomeMethod(Animal animal)
{
if(animal is Human human)
{
// do something with human var
}
}
}```
how would i get a local position?
literally first result
does that make sense ?
can someone help me install unity
its stuck on validating and Its driving me crazy
direct me to the proper channel then please
new Vector3(transform.localPosition.x, 0, 0) doesnt give me local x position?
How do you know?
how do i know? what
how do you know its not the localPosition's x
then its not a child of something?
It should be, try debug logging it
Newbie question here:
Should you update a time based boolean that affect physics in update or fixed update?
For example, say you have a timer, and when timer > 0.5f, timerCondition = true. If timerCondition = true, say the physics would change, like the player's speed doubling or a force being applied. Should the timer > 0.5f condition be in Update() or FixedUpdate()? Im inclined to say FixedUpdate as that would seemingly make it deterministic?
update
do the forces in fixedupdate, unless its Impulse that is fine in Update or 1 frame event
That somewhat confuses me, because despite never applying forces in Update(), my game still seems to frame dependent on very extreme frame rates, for example 5 fps. And Im led to believe that playing at low frames like this breaks any deterministic physics due to the Update() time variable checks? Unless Unity just isn't deterministic to begin with
what does deterministic have to do with a bool
What I mean is like, the physics in my game aren't determistic. Unless that's Unity normally, Im led to believe the reason it's not deterministic is because of frame dependencies, and playing at 5fps compared to 60fps would have the boolean set to true at different intervals in between fixed update?
I think it has more to do with how floats behave and across different machines, don't quote me on it . Originally from your question if you're only increasing the speed for example, I usually just do it in update, never had issues aross diff fps. the only main issue at low fps is "skipping" almost like teleport
I doubt there are any deterministic physics engines out there
Those are fair points
I do have a final question tho, would I be in correct in saying the following:
timer += Time.deltaTime
At 1 fps, it takes the timer 1 second to pass 0.5
At 2 fps, it takes the timer 0.5 seconds to pass 0.5
If I conduct a check if it has passed 0.5, wouldnt the check return true a frame earlier, impacting FixedUpdate?
you kinda don't want them to be either, imagine dropping a ball on another and it always falling hte same way
https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/design.html
its for specific instance/usecases says here
Well, I'm mostly interested in deterministic physics as they cater for TAS' or just frame perfect stuff
multiplayer it certainly would help
How does one reference variables from other scripts without making those variables changeable? Do I have to make them public?
If by changeable you meaning them being in the inspector, you can do it still
use public get and private set property
You need them to be public to access them from elsewhere
but if you put [HideInInspector] before the public or private bit it wont show up in the inspector
I don't mean changeable in the inspector, I meant changeable in the code itself
set readonly
thats not what they're asking
My bad then
Still useful, was wondering this as well earlier
making them public and hide in inspector is such cringe when i see it
well technically not, there is actually a max delta time in order to combat extreme scenarios like this.
In a scenario with smaller values, yea this could happen but very doubtful itd ever matter
"props?"
At that fps your game is probably gonna be unplayable anyway. The fixed update would try to update at it's determined rate, which would cause the frame time to snowball to a halt.
properties
hmm, I still need to learn about what those are then
they are just fancy methods , look into them they're extremely useful
That's intersting, didn't know it had a cap
So, with that in mind, I probably shouldn't worry about catering for say, someone playing in 5fps?
Yes. You should build your game such that it would run at the expected frame rate on the target devices.
its best not to worry about cases like these. If your concern is multiplayer, your server wouldnt care if the player was lagging. If this is p2p then yea people can lag switch but 🤷♂️ thats not possible to fix really
And if its single player, you simply wont have players if its running at 5fps
Fair enough, thanks for tips yall
thanks sm.
Despite doing a lot of programming in C++ throughout all of my undergrad and then learning a large portion of Python and Perl, C# is hecka unique and confusing to me so far with a lot of its syntax and jargon
Every language has it's own unique terminology. Think about vectors in c++.
I found C++ a confusing mess in the beginning so our roles are reversed 
you'll pick it up quick if you already learned those
just gotta get used it
c# and c++ are written pretty similarly. if anything python is the unique one
lol, I can't remember if I even ever learned about them tbh lol
yeah not a fan of python due to its syntax
fr I get lost without brackets kinda joking but not
you have to be sadistic to enjoy memory management lol
well in most cases you dont use c/c++ because you want to
C# the C++ relax mode 
That's very weird. They're like one of the basic things that almost any codebase has.
Basically the C++ lists.
Just my personal opinion, but if you haven't heard about c++ vectors, you probably didn't learn enough of it to extrapolate to other languages.
could just be my memory sucking. It was like 8 years ago
doesnt C++ have getter and setter?
I agree, though its simpler syntax has helped a few of my friends learn programming, so Im kinda glad for it
python has properties iirc
wait a vector is just a one-dimensional array? That's it?
no
It's a type. And it's closer to C# lists, than arrays.
https://cplusplus.com/reference/vector/vector/
oh c++ vector
#💻┃unity-talk pls help
c++ doesn't even have lists, it's in the STL added in
Dang. Well a list and a one-dimensional array are like....synonomous to me rn so I think I need to do a big refesher
dont crosspost, or ping others into your conversation
Oh. Maybe that's why I think of lists as one-dimentional arrays
since c++ is my coding foundation
isnt that basically how vector database work?
idk, they're all still synonomous to me atm lol
list, vector, one-dimensional array...
No. C++ vector from std library is basically the same thing as a List in C#.
ahh ok
This conversation is making me feel like I need to go back to college
college what that?
You don't need college to learn properly. The documentation is publicly open and free
just need 🍕 🧠 ⌛
i had to learn(some) C++ to mod source ended up stumbling on unity to have more flexibility and c# seemed easier
childs play in comparison
we should probably steer back to unity c# coding qs 😛
Agreed, just am impatient and want to learn what I need like, now. Unfortunately I'm at a stage where answers to questions use lots of jargon that I don't understand so I need to ask questions about the answers etc etc and then those use jargon I don't understand as wel.....I'm going to go do the C# CodeAcademy course rq
The terminology is explain very well in the documentation. That's what it is for after all.
can we see some code? and the line its at?
this might not be a code problem
okay. Maybe I just need to learn how to read it. I often struggle with understanding the documentation somehow
Library cache is usually somehing else going wrong
oh
thats the thing i dont have any scirpts
Yeah, that's a very important skill to get early on.
Try doing a Reimport all
wheres that located?
Assets menu
why does this not @
cause its hashtags
ok
oh
yeah
#💻┃unity-talk im not to keen in discord
so i tried the local position but it didnt work out due to it being the parent, can i convert the position to local position?
IEnumerator CalcVelocity()
{
while (Application.isPlaying)
{
// Position at frame start
Vector3 prevPos = new Vector3(transform.position.x, 0, 0);
// Wait till it the end of the frame
yield return new WaitForEndOfFrame();
// Calculate velocity: Velocity = DeltaPosition / DeltaTime
Vector3 currVel = (new Vector3(transform.position.x, 0, 0) - prevPos) / Time.deltaTime;
Newspeed = currVel.magnitude;
}
}
all of this is so vague, what "didnt work"
scroll up
and what does the local position have to do with any of this
ask your question in a complete message or at least link the context, im not scrolling through a ton of messages to find it
why do you need local position if its not parented ?
that makes not much sense
if you need the difference get the two world? still same distance no?
so its basically i need to get the X and Z speeds but if i use global positon and rotate my character to the left instead of reading 8 meters a second, it will read 0.11522 etc
then it will say the Z axis is 8 meters a second
instead of X
cant you just get the velocity then count a second and compare the two ?
still none of what you're saying makes sense, itd probably be a lot easier if you just got the velocity from whatever script is actually moving the object
velocity is in m/per second anyway no?
it is in the same script
then why do you need to read its position, you have a script which moves the object so the script knows how far its moving the object
i didnt know the unit of speed for unity so i just said meters, sorry.
i can use rb.velocity but the same problem persists
well in unity 3D its always in meters per second
1 unity unit = 1 meter
alr ty
they tried matching real life, thats how vel is calculated
🤷♂️ you still really havent clearly said what the problem even is. "didnt work" and the stuff above is all without actual context. Rotating your character has nothing to do with its position unless you're rotating some parent object with a child object that isnt centered
the rb velocity gives exactly what its velocity is. If you think its wrong, then you're likely doing something wrong elsewhere
yes rb velocity is doing what ur doing (currentPos - prevPos )
im not saying the rb.velocity is wrong i just need the velocity in a local space. if i do not use local space it wont give me correct horizontal/vertical velocities.
Hello.
Trying to create a mouse mov, but don't understand what is wrong!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
[SefializeField] Transform PlayerCamera = null;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update() {
void UpdateMouseLook();
}
void UpdateMouseLook(){
Vector2 mouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
}
And the field don't appear
the names are different?
What names?
The name in the image doesnt match the name in this script here. Also this definitely has compile errors
configure your !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
you are showing a Player Controller script but the name in the script you posted is NewBehaviourScript
I think new unity doesn't care now does it?
i think this is the issue
void Update() {
void UpdateMouseLook();
}
declaring a method without a body
Configure your IDE
unity screams at me if my names are not correct
which unity version? Thought that was a thing of the past
although I still keep them consistent
i have zero clue what unity version im using 😂
Whats the best free unity C# course ya'll know of?
seriali zad?
if you want more general c#
https://learn.microsoft.com/en-us/collections/yz26f8y64n7k07
cool
this should convert global to local will it not?
Vector3 currVel = (new Vector3(transform.localPosition.x, 0, 0) - prevPos) / Time.deltaTime;
Vector3 locVel = transform.InverseTransformDirection(currVel);
Newspeed = locVel.z;
mb
i dont understand why not just grab it from rb then transform direction that? what reason ur manually checking vel
#💻┃code-beginner message
i linked you the exact method
TransformDirection converts a local space direction to a world space direction
Also it's unclear what prevPos is or why you're taking localPosition.x
trust
It doesn't make much sense
IEnumerator CalcVelocity()
{
while (Application.isPlaying)
{
// Position at frame start
Vector3 prevPos = new Vector3(transform.position.x, 0, 0);
// Wait till it the end of the frame
yield return new WaitForEndOfFrame();
// Calculate velocity: Velocity = DeltaPosition / DeltaTime
Vector3 currVel = (new Vector3(transform.position.x, 0, 0) - prevPos) / Time.deltaTime;
Vector3 locVel = transform.InverseTransformDirection(currVel);
Newspeed = locVel.x;
}
}
transform.localPosition is a position in the parent's local space.
InverseTransformDirection converts a direction in world space into the local space of the object itself.
In short, no this doesn't make sense
the script is on the parent obj so it converts it back to global position, lemmie fix it
i tried that, its still global
Vector3 locVel = transform.InverseTransformDirection(rb.velocity);
Newspeed = locVel.x;
You should debug what the vectors are, the velocity and locVel. It most definitely isnt still global
you probably just think it should be something else, but again everything you've written is too vague and you arent describing the actual issue. Nothing more can really be said
i'm using np++ to edit. It's good?
i have them as a float as a debug to see exactly whats happening, I have explained in detail whats wrong, i stated i need a localposition but i couldnt use it due to the fact im using global possition because the script is using the parents position, so you gave me the Transform.InverseTransformDirection which is giving bad results.
There is no place to install VS using Unity Hub!
Where?
Click the gear, add modules, install Visual studio.
it isnt giving bad results. again, debug the vectors. I really am not gonna entertain this more if you wont go through the absolute basics of troubleshooting. You're claiming the method is giving you a vector back in global space yet you wont print out the vector before and after to see it
Does that say Visual Studio?
bro im debugging as we speak, im still getting the same results, unity is telling me the rb.velocity and the LocVel and they are exactly the same from what the float is saying.
ah.. ok.. this thing just download the installer, but don't install it
i know how to debug
have them as a float as a debug
Show the actual debug lines then
can i send a video?
or only pictures
if i can send video i need to reinstall the recorder app i had
When I try to install, it return an error, but don't specify that is wrong! Sad.. need to know what I need to do to install VS!
🙄 so you arent gonna show the debug lines?
Im just gonna point out that the #854851968446365696 says
Don't
Directly give answers to users who will not troubleshoot.
and im truly not gonna beg you to answer what ive been asking. Someone else can help you
i never said i wasnt gonna show debug lines, all i asked if i can either send a video or picture to send the debug lines
Unity has logs you can see for the install that can give hints, otherwise there's no guessing the issue.
they constantly update so a picture wont give a lot
Weird. . .
But you can always look on Google and find people's solutions: https://forum.unity.com/threads/install-failed-validation-failed.1147151/
the title is the error (
Install failed: Validation Failed)
how do i fix this?
oh yes.. i'm looking for it right now. . rsrs
the lines of code is what i meant. the last thing ill say about this is if your global and local direction are the same then that implies your object is at the default rotation.
You can show a video, but still it wont really answer what ive been asking the whole time. What the actual issue is. Because youve said lately is the vector is still global, which is what you assume and not even true to begin with
Problem Solved!
This isn't visual studio, this is visual studio code which is not what is installed from Unity Hub.
So not sure how you got here, but either way, it counts as one of the programs you can use for Unity. Just make sure you configure it !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 close the Hub and open it with admin. After that the Hub installs the VS.
I feel that in my soul. It happens. The fact that there are two threw me off at first.
Don't know what I did wrong if the Unity Download it.
What's the issue? The local velocity would be the same as a global velocity if your object is not rotated.
i need it to be local and not global. the code i have now should convert it to local but it doesnt
i showed it in the video and a a little above the video
Did you read my message?
Local and global would be the same if the object is not rotated
local should be local to where to object is facing, it should not be global. thats why i did inversedirection on it
I'm on the right place?
so the local velocity isnt local, its global velocity
yeah you seem good now
Again, if the object is not rotated, then local direction == global direction
ah good!
the point of local direction is to not do that
thats what global is for
The point of local direction is that it's relative to the object's orientation
If it's orientation matches the world orientation, then global is the same as local
makes sense?
Thanks @frosty hound!
You gimme the right means to solve this! +1
yeah that makes sense, i fixed it, thank you😅
So if I were making reference to the current player state as the CurrentPlayerState in the main player script, would that suffice for having said state data from said state be sent the main one? That's worded poorly. But basically.
Info from this.
Is sent here.
And I make reference to say the acceleration in current state as the value to use for my player's speed calc in the main script?
Trying to avoid using a bunch of bools and losing track of everything in the process.
You could always access like baseAcceleration in the "main script" from a reference to your state machine like playerStateMachine.CurrentPlayerState.baseAcceleration, sure.
But if you're saying you want to store a reference to the state machine's CurrentPlayerState in like a field and just always try and get the current value from that, that might not, as when CurrentPlayerState changes in the state machine, the field in the "main script" would still be referencing the whatever state the field was initialized with.
Ok. I'll stick with the former to avoid any issues then.
Thank you. Felt like I was overthinking it and potentially adding a middle man that would cause problems. I'll just reference it with the playerStateMachine.CurrentPlayerState.baseAcceleration.
Can someone explain a specific case where singletons can mess things up? I’ve looked at articles, but they give very general and hypothetical examples
You could use a property to express that more succinctly though:
private PlayerState state {
get { return playerStateMachine.CurrentPlayerState }
}
Or have the player script subscribe to events invoked by the state machine when it changes states, and update a reference or values accordingly - but that sounds somewhat messy to me.
I get a little lost in all the possibilities as well 😅
I don't think any pattern by itself can really mess things up on it's own - it's usually a matter of a developer misunderstanding or misapplying a pattern
Ohhh ok, so it’s the development proccess
all the examples will be hypothetical, until you make one and then realize its messed things up. "mess things up" is also kinda vague, like if we're talking about actual logic issues then that could be "i made my player a singleton so enemies could find him. now i want the player to have an ally that can be targetted!" Basically i had one now I want 2.
Other issues people bring up is more with like industry code where you are testing. I found it mostly doesnt really apply in indie game dev
One annoying thing also is having singletons that u have to create in every scene, but this part is somewhat tedious to have an alternative. Like if a script creates a bunch of stuff at the start of loading a scene, and you need to call a function for it to run, then you have to find the script somehow. Or take the script out of the scene and associate a scene to this function elsewhere
Ah i see
I’m fine since i never use more than one scene 😂 (I probably should but i never felt the need to so far)
it doesnt work i tried making a new project and it says it insalled all pakages but now the error is happening tto all of them wont let me boot it up without going into safe mode
it told me to run unity with tempmemoryleakvalidation so i did but i dont know what to do next
What version are you on?
First of all, you can get rid of the test related errors, by removing the tests package.
Unless you're using unit tests in your project
2023.2.1f1
Do you need to use 2023? Or LTS is fine?
Your patch version is suspicious too
should i upgrade to a different version? i was using this one because a friend was using it
lts is fine
I recommend LTS, 2022.3.37f1
But it is downgrade so you might encounter some issue when converting
Otherwise at lease use the most recent fix version 2023.2.20f1
ok ill try this
Do you use version control? Make some backup before converting
yes im using version control, how do i back it up?
If you are using one then just having a commit you can go back is enough
is there a way i can check if 2 shapes on a 3d grid are touching eachother without iterating over each cell in each direction?
alr ok
depends on what these shapes are and what information you have about them.
you could always use the bounds to see if they overlap but if the shape itself is completely unique then the bounds might not be entirely accurate
the shapes wont be convex, i want to implement branches and pools in my cellbased fluidsystem, but need a way to check if they are overlapping or touching. i can make custom classes for them, might be easier to give them a hitbox and see if they touch?
only info i have for them now is the collection of positions they occupy
are you checking between 2 specific shapes, which is what i thought from the initial question, or if anything at all overlaps?
ideally i want to know if they are touching, but if i cant find a good way to do that i think ill have to resort to checking for overlaps
also could be checking between multiple shapes
if you're checking if anything at all overlaps, it might just be better to check through the grid.
how do you mean check through the grid?
Well with a grid, I assumed you're storing which places are occupied. I meant using the collection of positions and seeing if any of those are occupied
Which is pretty similar to your initial question, of iterating over every cell but im not fully sure what you're trying to do with iterating in each direction if you just need to know what's touching
by touching i meant that they could be occupying neighbouring positions. with overlap that would be both occupying the same position
its nearly done downloading but now shows this should i just download it manually?
Hi guys, I'm not quite sure how I'm meant to hash a Vector2Int into unique values, how are you supposed to combine the x and y axis into a number that isn't recurring accross the map in any way?
x+y would mean that diagonal lines would have the same output...
x+y*... will only modify the way it repeats by squashing it down?
x+y%... will just make it trunciate across y...?
Why Visual studio?
Unity Hub should have it
Oh you checked to install VS
Do you know the size of the map?
Oh it’s just hashing then it doesn’t need to be unique
Hashes can’t be unique
I see, then yea manually checking this is probably the best way to go.
With checking every adjacent cell
Wdym, there's no way to not have a lot of repeats across the map? 0.o
you should explain what you're actually using this for. this x+y x+y* etc stuff is an XY problem
of course theres no way. how do you fit 2 numbers into one, where the original 2 can be any number. You cant
So on the map, some floors have decorators, however I don't want to save all that extra data to make it show the same decorator each time you load that position
i dont really know what a decorator is in this case, but could you not just store this by some ID? What would hashing a Vector2Int even do for you here?
Uhm... Maybe I can fit one on top of the other? Like x + y/mapSize?
Yeah that sounds like downgrading issue, you probably want to modify some package.json :/
If you know the map size x + (y * width) is how you convert 2D to 1D
Storing 1000000 integers is kinda absurd '^^
I intend to generate a rng instead as in that case I don't need to save anything
whats 1 + 0, and whats 0 + 1
If you had a defined max size, then it could be possible but i think theres a better solution out there. Like specifically what are you hashing a Vector2Int for
Seriously I think that not even terraria saves the rng for each tile
"hash" is meant to be non-unique
Why? That's just around 4 MB. If you really need to store that, then why not?
It's such a waste...
4mb is a waste? dear lord
Depends on what you need it for
I think you are using term "hash" wrong
should i try to find the package or just go to 2023.2.20f1? i dont know what package im looking for
I think that tbh, if you hash that probably the result should be good enough
i dont think you know what hashing is
Hash is not compression
Hashing is to turn a number into a psuedo random number, ain't it?
With same output from the same input each time?
So what I want is a random number for each tile, but to be able to get that same number whenever I load the tile
In Packages/manifest.json I think you should just delete the line contains the said accessibility package
and also, this seemingly came out of nowhere. Either way you're gonna need to save the same amount of data. Again, what is this Vector2Int and why are you hashing it? What is a decorator, can you not just give it a specific ID and save that ID?
You're confusing it with random seeds
So, imagine a map in the form of a grid, the map can be of any size, but at minimum I expect 100 by 100, although 1000 by 1000 is my target standard. Each tile of the map has a floor type, it could be dirt, mud, or like, grass.
Grass tiles have decorators, they might spawn a random grass object on top when loaded
What I want is to get the same random grass on top whenever I load that tile
Hashing is making your variable, of any size, to fit in certain size
It does not guarantee uniqueness, you cannot recover original value from it
You could save the seed that you use for the Random function for deciding whether to put an object on top of it or not.
But you can't get that seed after the generation
Or have manual control over it
Yes but, the seed of the generator isn't the only thing deciding, it's also the position of the tile...
I seriously thought that it's called hash functions tho?
i see nothing stopping you from using ID's for the grass object, or what dlich said about storing the seed then just generating everything in the same way
Well, if the generation algorithm is determenistic, then the seed should be enough. You probably have access to the tile position anyways.
Eh... Fine, Imma jsut ask it directly, how to generate a psuedo random number from a seed, a x position, and a y position
A hash is a way to compress data in such a way that there are values that would overlap for sure. They're just usually outside of the range that you're interested in.
All three values are meant to generate a rng that doesn't show some visibly repetitive/incrementing patterns
theres no way you need a random number here if you're trying to store information about what was generated
Ultimately you need to compress these 3 values into 1 seed. How you do it is up to you.
Storing a random number for each chunk seems bad... I want to avoid storing extra variables in each chunk as much as possible
For example, you could use the first 2 bytes of the int for the random number and the 3d and 4th for the x and y positions
you havent even accurately said why you cant just store a single ID. You were also told that hashes cannot give you the original number back. How do you expect to use this data if you're storing a number generated with a one way function? What do you think you're actually gonna do with this number
Thought, that would limit the range of tile positions that you could use
Well, you either store the data or pay with precision and control. Take minecraft for example. It saves a lot of the state of the world and thus the save size is huge
I can, but like I said, it just increases the memory cost of each dimension quite a lot
if you're building to anything better than a samsung toaster, really just cut the crap and make what works simply. All of this is "i think its bad" with 0 experience in it
And like i said, your solution right now doesnt even seem like a solution. You're trying to store a hash of a number, for what purpose? How do you expect to get the original values back to read the thing
Whats the point of even storing this
I'm not trying to store it 🤦♂️
Ultimately, the amount of data you can encode in a unit of memory is limited. So if you want to save more data, you need to use more memory. Deterministic procedural generation is one way to compress that data, but it's not without flaws.
Told you that I want the same number for the same seed, x and y, without needing to store it and without them showing an obvious relation to eachother
I don't really get the issue with hashes... Okay, uh... There're basically formulas that shuffles a number non-sensically
Usually utilizing bit shifts, modulos and multiplications
everytime ive asked you something of it, storing numbers was brought up so I thought this was in relation to storing.
You could just use a single instance of random then and generate it from 1 seed at the start. I still dont see what you need this other seed (of seed, x, and y) for
I kept saying I want to avoid storing numbers tho...
Because you load the chunks in runtime
The issue is that hashes are not unique. And also that you would probably need to implement your own hashing algorithm for your specific need.
And reload them in runtime too, just like in minecraft
1000 x 1000 can easily all just be generated at once
Count all the dimensions in, and each world
You'd be adding at least 16mb per world, even if this is a small addition, it'd add up significantly when saving things unnecessariliy too often
Well, then you'd need to use a random seed and a determenistic generation algorithm. That's how minecraft and other similar games do it.
🤷♂️ what other unknown aspects am i supposed to account for? Im going purely off information you've said
I have an int and I'm trying to lerp it into a usable index in a list I have but something here seems to be rounding weird,
float lerpResult = Mathf.Lerp(0f, (float)(gizmosColors.Count - 1), (float)intValue);
The List is 6 in length and i'm giving it 1-8 and this always results in 6, What am I goofing up here
It still saves a lot of data normally as well
I know I gotta turn it back into a clean int after this but this is where my issue is
Yes, but I kept asking how to take a position into it lol
And I answered it
Probably intValue
@tiny rain Here: #💻┃code-beginner message
is there a better way to tell that stupid number to be a float
this doesnt make sense, the 3rd param of lerp takes in a value of 0 to 1. Giving it (what was initially an int) will either be its lowest value, or highest value
Ah, right... Um... I guess, that's why I said that maybe I could just compress them together before hashing by x + y / worldSize, or x+y*worldSize if I'm making it an integer
In which case you wouldn't need a hash anyways. You can use the resulting value as is. I don't understand that obsession with hashes? Considering you don't seem to understand them.
Why hashes? Cus if you, say, use it for whether grass spawns, the value would still show a very recognisable pattern, no?
Cus y++ might give a very linear change to the value, thus making the grass pattern visibly repetitive
It depends on the algorithm you use to generate the grass.
And that being said, I'm not sure that hashes would help you with that anyways
Like, what exactly do you want to use them for?
To break an obviosuly repetitive pattern? https://stackoverflow.com/questions/44593626/how-to-create-a-hash-function-for-use-in-noise-generation
Hashes are not random numbers. They're very much deterministic and preserve patterns. In addition they are not unique and could correspond to several of the same values.
Well, I do need it to be deterministic as I don't want to save the output in the map, so that's what I actually need, I just need it to not have an obvious pattern to the player
Like in minecraft where the same seed always gives the same map, that's what I'm seeking
This is diving into Perlin(or any other) noise algorithm itself. I'd avoid messing with that. And it's probably not really what you need anyways.
Then use Random numbers.
Perlinnoise is only built on top of random numbers like this
You can't retrieve the same Rng with UnityEngine.Random with the same seed... Still don't get the problem here?
And you've been answered many times regarding that. Nowhere here hashes are relevant
unless you're trying to write your own noise library
But you can with dotnet Random
It sounds like you might using "hash" interchangeably with like "procgen algorithm" or maybe just "pure function"
Idk what pure function means
Same output for same input without side-effects
Pretty much, except that when you, for example calculate it for each pixel on a texture, the texture wouldn't look repetitive
Also, you can do it with unity random as well
https://docs.unity3d.com/ScriptReference/Random.InitState.html
PerlinNoise is an extension on it, a hash function isn't a perlin noise itself, as it's specially programmed to make the wave effects
I'd still use the dotnet one, as you don't need to reset the state every time.
I'm pretty sure that setting the seed for each position in that UnityEngine.Random's case would do something like what happened in this video... Can't tell for sure
https://www.youtube.com/watch?v=ZZY9YE7rZJw&t=1688s
In this video I look at how we can manipulate randomness to generate coherent and well formed structures on demand, which allows truly vast and complex resources to be created with no effort from a designer
Patreon:...
At 10:35
They set the seed but the result is visibly not random, as it relies on jumping states to make it seem random
Why would you set it for each position?
But yeah, you'll need to maintain the random state between different seeds and steps of generation, which is why I suggest using the dotnet one.
Told ya... I don't intend to save it, so basically I should be able to get the same random number at a certain position without dependency on extra values like it being the 100th rng generated from the seed
You seem to be confusing many pieces of information technology. Keep it simpler. Start simpler. Learn how random seed work and how you can have multiple random generators with different seeds.
Wat? Again, I feel like you're confused. At this point I really don't understand what you have in mind.
You do realise that you would need to save at least something, right??
at least the initial seed
These kinda functions
Otherwise you would never get the same map ever again(in realistic time range)
They are deterministic, yet they don't rely on hopping states x times starting from x seed to seem random
And they look random
Well, that's exactly what a random function does
It just has a different algorithm under the hood
in your case nLehmer is the seed
- the hexadecimal at the function start
Yeah... But some numbers if you set a number with a visible pattern as a seed, the output keeps the visible pattern
Your algorithm would also have a visible pattern depending on what values you feed it
The Lehmer function instead doesn't have such an obvious repetition despite feeding it a visible pattern
Yes, if you feed it stuff like x+y
Random wouldn't have a visible pattern either. It's white noise
Which makes it obviously repeat in diagonal strokes
Please watch that video at 10:35, they were setting the seed for Rand(), and it didn't look like a white noise at all
That's the problem I was talking about
Rand relies on the previous state to generate a decent looking rng
Which, if you set the seed for each position, destroys the purpose of it
Again, you're confusing concepts. They get a repetitive pattern because of how they use the random. You would get a repetitive pattern with your function as well if you feed certain values into it.
Anyways, it seems like you already have all the answers yourself, so I don't see any point in continuing this conversation.
No... It's really proven in the video that some look random, some look repetitive, despite all being fed as seed (y << 16 | x)
Rand() when fed that as seed gives diagonal strokes, while Lehmer gives a white noise
Great. Then I guess you've got your answer.
I'd also point that srand/rand is C++, and there's absolutely no guarantee it has the same implementation as the C# Random
I can't believe I spent that much time on that meaningless conversation with arguments relying on a different function from a different language in a very specific scenario...
C'est la vie
así es la vida
viva la fromage
theres an off chance that the rand() is implemented differently between platforms too
Almost definitely is
CHEESE
if its that important you might as well make a backend server that handles all this for you
precisely why i stepped out early. when it was clear the exact issue wasnt gonna be brought up, instead bringing up more details only when it counteracted a solution presented
The source of entropy on Unix is different than the source of entropy on Windows, and that's not even considering the hardware
So I have certain prefabs that I spawn every several seconds and I want them to be destroyed when they're out of bounds. The problem is that when I try using a separate gameobject to destroy everything it touches it simply doesn't work. I have also tried destroying that prefab after 5 seconds but it still doesn't work. Any suggestions ?
are you using OnTriggerEnter by coincidence?
yes, 2D
you need to specify more about what "didnt work". this is very vague, look at the #854851968446365696 on what to include when asking so people dont need to play 20 questions
because i am making a 2d game
could you add a Rigidbody2D, with Kinematic on?
to the trigger
one of the objects on this needs rigidbody
well it doesn't provide an error, nor it destroys that object
Idk why you kept misunderstanding my question tbh
In my point of view y'all seemed confused, I think that it was a communication issue instead
i didnt say anything about an error, but to look at the #854851968446365696. you need to include code
sure
If several people are misunderstanding your question, maybe the other people aren't the problem as a note.
an object with a collider but no rigidbody is not expected to move. thus the physics engine will not take that into account
Ye, that's why I suggest communication issue, not sure what I was saying that was so confusing in the first place
the message you replied to literally states why. You kept bringing up something new when a solution presented didnt match your hidden use case.
that is all the code for the gameobject that is supposed to destroy the prefabs
i have also set the isTrigger
on
To me, I was talking about the same thing pretty much all the time 😂
that worked bruh
Only going off track to explain what I needed it for
@pliant sleet
look into how physics engines work too
making one is fun
unity uses nvidia physx, a physics engine that uses your GPU
you also might wanna consider having the rb's on the moving objects rather than the destruction area
unless you want it to destroy truly everything that comes into contact, and not just those select objects
nah, truly everything, because only the prefabs that are moving can touch that trigger
Thank you for the advice
on 3D games it doesn't work like that
oh it works the same way in 3d actually
one object needs a rigidbody for the trigger to work
then it's just on me because I didn't take that into account
For some reason every time my code throws an error, it sets the Scale of the items the next time I start the game to 0
When I set the scale back to 1 in play mode and exit without error, the items load properly the next time
But every time I have an error, it will set all items that were in the hierarchy the previous play to 0 scale the next time it runs
Even though all items are Instantiated in code from a prefab, the prefab scale is set to 1 and my code does not touch scale
So none of these items are in my Hierarchy while in edit mode, they are created while in play mode
Some values driven by VerticalLayoutGroup
Whelp, guys, after testing, yep, there're you go, exactly what I meant
- UnityEngine.Random will show a very consistent pattern when seeded with (x << 16 | y)
- System.Random is repetitive too, except in another pattern
However, to prove the other part of what I was saying, this is what Lehmer does, with the exact same input:
I'm just telling this only as a final statement to prove my points correct honestly, else I wouldn't've even bothered
I was only hoping to find a built-in, which I suspected to be hash128, else I'd be using Lehmer
would you also know how to fix this? can't really figure it out
ok ill spoonfeed a little but your parent object has a verticallayoutgroup
you'll need to play around with the values a bit
also see the Layout Element component which gives you control over what happens in a layout group
This only proves the point in the constraints of your specific scenario. And you're probably not even using the function correctly.
It totally works how it does, you could look at the tutorial and you'd get what I mean with it
They're using it the exact same way
And this is exactly what I was asking for- Converting a position into a psuedo random number, without them showing an obvious pattern
Both Dotnet and Unity's random doesn't cut it, likely made to be faster but with this weakness
I'm not saying that it doesn't work. I'm saying that dotnet or unity random would work as good if used correctly
They rely on the previous "state" or "seed", they cache the previous value to generate the next one
If you used that to try get the rng it'd give at a position, you'd either need to generate till the xth rng from the same starting seed
Or set the seed to a number made with the position, but that fails to look random
Yes. That's how it's done usually. A deterministic algorithm always generates in the same order, which is why the seed based random generator works.
However, perlin noise is different, if you gave it the same x and y input, the output will always be the same, no matter what you do
However, the wavy look comes at a cost, which isn't worth it for this purpose
That's why, there need to be another algorithm to generate a rng from an x and y value, one that doesn't perform such redundant operations
That's where Lehmer comes in, I knew that I could use it, but I wanted to see if I could get away not writing custom noise functions
Sorry that it's a waste of time after all, I guess, thanks for trying 😂
It isn't a weakness of c# or unity if you're using it wrong.
Anyways isnt noise just a hash function?
It's the weakness of the function, it was meant to be random, but it wasn't made for this.
I was suggested to use Unity or Dotnet's random by you guys, while I knew that it's extremely unlikely to work for this case
you should show your actual implementation to ensure there were no flaws in it
That's why I was talking about hash functions all this time 🤦♂️
Also, no, not all noises are just a simple hash function
Perlin noise have some sort of lerping between points, those hills
Voronoi noises, despite being able to use hash to determine the position of the points, still need extra checks to know the value in between
Bad code is bad code. You can 1000000% have it work for your use case, but simply didnt write it in a way to do so
I dont know what you are face palming for, you're the one who asked how to generate prngs multiple times above
Partly cus you were the one saying that I wanted to store stuff, and said that I kept saying storing, while being the one who suggested storing in the first place, and repeated on it many times over
While I said that I wanted the same rng for the same x y, without storing the value
Please, I don't know why y'all keep thinking that there was another way or whatever stuff I was saying, can't we just stop talking gibberish over stuff that's already done?
Storing it or not is irrelevant, you literally just said you wanted to generate a random number.
Anyways doesnt matter as long as you found something that fits your desires
If you didnt want a discussion on it, then maybe dont post above about how c# and unity random has this "weakness"...
This kind of talk genuinely has beginners think it has flaws and they try to go find other methods when it's perfectly fine to use
Well, maybe weakness was "wrong", great, it was just simply not the tool for generating an rng from an x and y value at all
And I didn't start about those two tools in the first place, okay?
Sure, here you go
int seed = position.x << 16 | position.y;
UnityEngine.Random.InitState(seed);
int unity = UnityEngine.Random.Range(0, 5);
System.Random sysRand = new System.Random(seed);
int system = sysRand.Next(5);
int lehmer = (int)Lehmer((UInt32)seed);
so for every position you initialize the random instances with a new seed? that is literally the definition of using them wrong
I was asking for something that generates something with an x and y value
And I didn't even think of using them before, it was on dlich's suggestion
that doesn't mean you should be re-seeding for every position
To me it was already unlikely a good idea
They rely on a previous state to seem random, seriously, I said that so many times by now, you can't get a reasonably random looking something with them if you want it to use x and y
you can't reasonably expect actually random numbers if you just feed it similar numbers as the seed every single time you get a new number
Try writing me a function that takes in x and y, and gives the same output consistently for the same x and y values, while looking random
Lehmer is one of those that does look random, there're plenty of hash functions that does it
Just one question. With your current implementation, there's no way you can generate different worlds with separate seeds. You do realize that?
"guys, i'm going to misuse these random number generators then complain when they don't look as random because i am consistently misusing them"
Yep, but I'm pretty sure I know how to stack a seed into it, too
Jokes on you, it was more like:
"Guys can I have the screwdriver please?"
"Why don't you try it with a wrench?"
*Proves with tests that a wrench don't work
"Insert your joke here"
I can imagine it causing visible patterns on different scales, but you do you.
Probable... However it's said to be pretty good for it's speed
So I imagine it to be quite reliable
There're better hash functions... But they are usually slower
can you stop with the ego? your first question wasnt "can I have the screwdriver" it was something that was literally impossible #💻┃code-beginner message and then people played 100 questions to even guess what you want.
This is truely war without reason, it wasn't ego, it was a counter attack to someone else tryna roast me
can't we just stop talking gibberish over stuff that's already done
you can also stop responding, but we all know this was written as a "im the bigger person" message
C'mon, y'all say the exact same type of stuff