#archived-code-general
1 messages · Page 221 of 1
tbh i would just store the order in some array then use arr[i] to get the rotation you want. At least this lets you change it in the future.
its potentially infinite
I would do this:
float degreesPerShot = 5f;
float rotation = playerRotation;
for (int i = 0; i < bulletCount; i++) {
rotation += i * degreesPerShot * (i % 2 == 0 ? 1 : -1);
var bulletEntity = _contexts.game.CreateEntity();
var rotation = Quaternion.Euler(0, rotation, 0);
}```
Okay, so it's that pattern, expanding forever
I think this would work
then yea you'll just need to check if i is an odd number, increase the rotation if so
it would be (+0, -5, +10, -15)... wait maybe it's a bit off 😉
In that case, I would do this
Im looking for +0, -5, +5, -10, +10, -15, +15
Yeah I mean the number to add
int bulletIndex = 1; // not 0
...
void Fire() {
float error = 5 * (bulletIndex / 2 - 1);
float direction = bulletIndex % 1 == 0 ? -1 : 1;
}
there we go
the first shot has 0 error; the next two shots have 5 error; etc.
i need some help with this snippet. I keep getting an error returned on lines 29 and 41, and yet when I edit and save it, it works the first time, then doesnt work again until I edit and save it again. They never occur at the same time, its always one or the other
public void OnGUI()
{
GUILayout.Label("Finger Bones");
root = (Transform)EditorGUILayout.ObjectField("Root", root, typeof(Transform), true);
if(GUILayout.Button("Pose Hand"))
{
foreach(Transform t in root.GetComponentsInChildren<Transform>())
{
fingerBones.Add(t.gameObject.transform);
}
HandPose handPose = CreateInstance<HandPose>();
AssetDatabase.CreateAsset(handPose, "Assets/HandPose.asset");
AssetDatabase.SaveAssets();
Selection.activeObject = handPose;
foreach (Transform t in fingerBones)
{
Debug.Log(t.name);
handPose.bones.Add(t.gameObject.transform);
handPose.bonePos.Add(t.gameObject.transform.position);
handPose.boneRot.Add(t.gameObject.transform.rotation);
}
}
}
so you end up with:
delta 0 5 -10 15 -20
total 0 5 -5 10 -10``` with my code
should work fine
A runtime error, you mean?
Oh yeah makes sense, that could work
i know gameobject.transform isnt needed, its just an edit i made to fix the issue state
Rather than a compile error.
could you not just do
if i is odd, increase some stored rotation by 5.
Use the negative rotation
else
use the positive rotation?
NullReferenceException: Object reference not set to an instance of an object
mb,
fingerBones.Add(t.gameObject.transform); is 29
handPose.bones.Add(t.gameObject.transform); is 41
https://img.sidia.net/ZEyI5/ZanEDufI35.mp4/raw perfect, thanks
if it errors on those two lines its either the lists are null or they both have t that is null
the thing is, the Debug.Log always returns a name
the lists are probably not initialized ?
you didn't show the whole script so im just guessing lol
in HandPose prob
yeah that worked. i had to set them as new List
thanks its been bothering me for so long i dont know why I didnt initialize them smh
Hey, I need to convert a string (given by the player) to a seed for a map. Anyone know a simple hash algorithm that outputs an integer?
Even the smallest size value for the HashAlgorithm class outputs a gigantic number.
if you just want something quick and easy that just outputs an int you can just use GetHashCode
Saddly that does not guarantee unique seeds
nothing that uses an integer does
For example, with InputFields, it gives the same hashcode for different strings
nothing will guarantee unique seeds, collisions are a part of hashing
9 different strings, gave the same hashcode
you could use md5 hash
would MurmurHash work?
this is what I use, seems to work well
public static int GetHash(string value)
{
int hash = 0;
for (int i = 0; i < value.Length; i++)
hash = hash * 31 + value[i];
return hash;
}
I can try
That worked
ty
How does that work, tho? You can just add chars with ints??
never knew that
just to add one thing, with hashing the size of your input should have no correlation to the size of your output. This would be pretty bad for a real security purpose (although ik yours is just for a map seed). Hashing algorithms will mostly have their own fixed output size. Like md5 is 128 bit
chars are just ints that display as a character
What is the best practice for cycling through menu buttons in the UI?
Do you write a custom navigation system?
UI navigation is built into Unity's UI system unless you need something custom
hey guys does anyone know course or code source of a game like this and the 2d motorcycle physiques
pretty sure brackys has one
the line rider thing
yea I've seen the video the physiques not like this there is a big difference.
you want too specific
you have to buld it
"physics like this" idk what that even means
What specifically is the big difference? Generally you get someone somewhat similar and modify it
I want to be able to wheelie the wheel with the motor and hold it.
He uses in this game rb.AddTorque it won't work in my case
Why would addtoque not allow a wheelie?
oh, you mean like do a wheelie "state" where it rigidly stays in a wheelie position?
You need rotate the body of the rigidbody /moto, not the wheels
It doesn't allow for cycling through the buttons though. What i mean is: once I reach the lowest button and press 'down' I want the highest button to be selected again.
(also i'm using InControl which comes with it's own Input Module)
UI navigation seems to simply rely on the position of the selectables. so 'down' selects the button with the next lower y value it seems
simple just set the navigation on the first and last element to explicit and point them at each other
no need to build your own system
you're just talking about the auto navigation setup
all of this can be set programatically as well, if needed
aah under Button -> Navigation -> Explicit. thanks!
good that i asked. i would have written some really roundabout code otherwise 😄
is there a way to write an int property that allows public get, and public ++, and public -- only?
yes
Is this the right way? I'm not sure if there is a smarter way than just having the setter assert it
perfect only I would have thrown an exception
I assume it will simplify in final build, because I thought Build removes UnityEngine.Debug. lines
As long as you test completely, ok
I feel like just writing Increment and Decrement functions would be cleaner, no?
is there a way of baking that into a property, instead of makng it a method for the whole class?
Hey there - I’m modding a game (Which supports mods) and I’m trying to add a new animation to an existing Animator. Whats my best method of doing this?
Modding is not supported here
if you want mod support please ask in the discord of that game
if it has modding then the community of that game will be able to tell you
I think modding and his question are kind of separate
then there is nothing special of adding animation to animator and can be easily googled
As far as I could tell this can’t be done at runtime? Unless I’m missing it
you would just need to edit the animator to have an additional animation, connect the new animations like normal, and then modify code so the animator state machine can access the new animations
no, it cannot be done at runtime
you can with scripts 🤷♂️
really?
an animator is basically a Finite state machine.
You want to modify this finite state machine
well you could only override actually iirc not add new ones
Yeah I found that with runtimeanimatorcontroller although it didn’t seem to allow me to play the animation.
Could possibly be because the state is defaulting elsewhere
What is the cleanest way to patch a reference type between two variables without making a new hard copy?
you would use
https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.html
but idk about mods
thats why we dont discuss modded games
its specific to that mod
specifically, I have ContactState next; ContactState old;
I want to rewire the variables so I can make old hold a referenece to what is currently held in new, and new = a new instance
Yeah, I used that and it worked well to replace an existing unused animation in the controller, although I was unable to play the animation
it all depends how the parameters are setup 🤷♂️
you could use animator.Play i suppose with specific clip names
how do I do this without accidentally overwriting my instance as I make the new state?
Couldn’t get that to work either - I also setup a standalone Unity project to test it and couldn’t get it working there either.
I’ll give a couple other things a try
Is ContactState a class?
yes
Yup
great. I always remember the whole reference frame aliasing thing being a watch out
You're just changing where in memory the variable points to, the underlying value does not change
Only valid for reference types.
For value types, = creates a copy
yeah. I wanted to make sure.
I still remember my first computer science professor chatting about this, but that lecture was... a long long time ago
don't remember what he said, but I still kept the knee-jerk reaction to watch out for accidentally messing with references
hello, i have a sword that i want to swing using animator tab. i want to change the transform.rotation property in the animator, but the problem is that i want to swing it starting from the mouse's direction that is, it starts off being rotated towards the mouse, and then rotates up/down using the animator. how can i achieve this?
when i tried to do it, the animator asked for specific rotation values. i want it to start off with whatever value it already has.
Animator rotation values are local
You can parent the animated sword to another object
Then rotate that object towards the mouse
aight my turn
Implementation question, I'm making a game where the player draws spell patterns to cast them, the spell gets recognised out of a group of spells with their own preset patterns. I was thinking of doing a similar implementation to Hogwarts Legacy, where it distance checks the mouse to a hinted pattern. The problem is I don't want to have a hinted pattern, so therefore the player might draw it bigger or smaller than the preset pattern, but still have the right shape, which means a distance check won't work. Any ideas to do this?
I was thinking of doing a system where it would check the position of a point relative to the last point, which would be size independent
The problem is if you draw it smaller you'll have more points in a direction than the real thing
Yeah you could normalize the positions into a 0..1 range for instance
And have your presets in that 0..1 range
So scale the one the player drew up/down then distance check?
Yeah fit it to the same size as the preset spells.
Can try that.
You would have to calculate its min and max positions and go on from there
Basically a rect
You can also search for symbol/scribble/object detection algorithms
Can do that, find leftmost and rightmost, find the difference to 0 and 1 then get a scale factor
also, is there a way to change the speed of the animation using a variable in code?
"animator change speed of animation in script unity" google
Animator.speed
ty
I am using a character controller for movement and I want the player to rotate around the object's base (the center of the bottom circle in the capsule). I have attempted using Quaternion function to rotate around that, but it's a bit cumbersome. I also tried having a parent object positioned at the pivot point, so now the character controller is a child object, so I used this bit of code to reposition the parent properly after using CharacterController.Move(), but it's giving neat errors where if I look along the negative z axis while moving, my character shoots off along the negative x and z axes at an incredible rate, so clearly that's not working.
private void Move(Vector3 movement)
{
controller.Move(movement);
transform.position += controller.transform.localPosition;
controller.transform.localPosition = Vector3.zero;
}```
At this point I'm kind of stuck, so I'm wondering what would be the best way to do this?
does anyone know what might cause this bit of code that checks for the shortest distance of an object from the elements of an array to always return the same value?
{
Vector3 moveTowardsInput;
float lowestDistance = Mathf.Infinity;
for (int i = 0; i < nextMachine.inputs.Length; i++)
{
Debug.Log(nextMachine.inputs[i]);
float dist = Vector3.Distance(nextMachine.inputs[i].transform.position, beltItem.transform.position);
if (dist < lowestDistance)
{
moveTowardsInput = nextMachine.inputs[i].transform.position;
lowestDistance = dist;
return moveTowardsInput;
}
}
return Vector3.zero;
}
The log gives different values, right?
Try putting a log inside showing dist after it's set
Also you could use the debugger if you know how (or just look it up, it's worth it), and step through the code
One tip for debugging with logs: add more info to your logs. At the moment you don't even know how many elements you have and what their values are, or how many times you loop. Outputting an index might be very helpful.
Your lowest distance is Mathf.Infinity
And you are returning the first one that is closer than infinity
= the first one always
It should be fixed if you move return moveTowardsInput after the for loop, not inside it @delicate garden
man, idk how to encapsulate better, now that I learned internal actually works
VSCode often gives me internal when refactoring
I just want to make one classes' methods accessible only to a specific other class, but apparently I need to make and manage several DLLs just to use internal
I get that, but I've been working with just one assembly for my whole project
Is that what c++ friend keyword does or am I mistaken?
yes
Me wants
that is exactly the friend keyword
Yeah, that's why I'm saying that there's no point in using it.
yes, but I can't use private, because that blocks access
Not really.
Friend gives you access to private fields of another class afaik
Internal doesn't do that.
I just want to be able to mark specific things as accessible to another class
Oh yeah I meant the behaviour that loup wants, not internal itself
but only a specific other class to not expose more than needed
Define the other class within your access class🤷♂️
how
Just define it in the scope of the class
explain
public class A
{
public class B
{
}
}
and how do I define a method in B accessible only to A and B
Just define it normally in B
with a private access modifier?
You can't access class A from outside unless you do A.B
No. Public.
but then I could do:
A a = new A();
a.b.MethodInB();
I think you can also make the B class private
No. You can't do that.
ok, well that's exactly not what 'm looking for
Unless b is a public field.
You're looking to do this?
everyone needs access to fields marked as public in A and B, but also B needs to expose something only to A
and A has no business inheritting from B
Create a separate class/struct for whatever you want to only expose to A and only expose it🤷♂️
Great
except that method I only want to expose specifically modifies private fields in B
In theory, you can use internal and assembly.
However, I do no think it is really appropriate.
I don't think it's right either
but how do I just encapsulate it better? We don't even have the file keyword
Don't do that then. Also inheritance is an option.
A has no business inheritting from B
idk it's worth asking
but I think the language just doesn't support more advanced encapsulation outside of the options we already discussed here
how is it not encapsulation to restrict access to methods
Handy things are usually bad practice
You can achieve that with nested class and private access
it's not a GOTO flag. we'll live
The same argument could be made for the goto instruction
The issue is that it creates bad architectural design
The one usecase I keep finding for goto is breaking out of nested loops. But I still avoid it because it's non-standard
Ahh that's probably it, thank you!
And thank you everyone else for the tips!
Same. At least we have the break; instruction that covers must of the use case.
Yeah, usually just need break + a bool or something to break out of the outer loop
You can also use two condition in the loop.
That's true, I think I overlook that often
You can restrict access to A via nesting how I showed before and restrict access to A members via making it's instance private to B.
Then if you need to expose anything from A, you can just make a getter in B.
I don't know the context, but the whole idea sounds over convoluted in the first place, so maybe explain what you're trying to do a bit better.
Sorry, I ended up having to leave sooner than expected.
For the code above, that's what I'm using where I have this script on the parent object positioned at the pivot point, and a child object with the CharacterController. Rotation is then just handled by spinning the parent object in any way, and it should rotate around the pivot, but for movement, CharacterController.Move() will only move the child object, so the above code is what I was trying to use to correct that, but it gave the issue mentioned above.
The other system I tried involved not having a parent object, where the CC is on the highest object in the player's hiearchy. Then to rotate it I was using Transform.RotateAround(pivot, axis, angle) where the axis and angle are calculated elsewhere, and the pivot is the position in world coordinates of the CC's desired pivot point.
This system sort of works, but it is a bit frustrating as I can't simply set a rotation since the object's position also has to get altered.
Sorry for the essay, if anything needs to be clarified or simplified, please let me know.
@hard viper @cosmic rain Yo can u guys do a summary of what u guys were talking about? 
Is it possible to attach Visual Studio Tools' Unity Debugger programmatically? I have Visual studio running, I have a Unity game running, i want to run my own custom exe that'll tell visual studio to attach to the unity instance
we wanted a C# equivalent of the C++ friend keyword. there isn’t one
B can access anything from A, even private. But A can't access private members from B.
You can make a static partial class A then make classes B1, B2, B3 etc under it. And all B classes can access anything in A, including other B classes since it's an actual member of A. (But each B classes still won't be able to access protected or private members from other B classes.)
But i find this rather strange to do so i tend to avoid it since this brings up "Why not use static classes instead of namespaces?". 
So, to answer this, you make B a private class and declare a public method inside of B. That will make method in B accessible to both A and any B classes.
That's the only way i can think of tho. 
You can't make method in B private or protected because that will make A unable to access it.

it would just be nice to have an attribute to specifically expose to a given class
So, I got this script working as intended and it works great on its own. However, there is an issue that is happening when there are more than 2 objects with this same script (duped or prefab). The part of the script that controls the cam.orthographicSize. Its starting at 6.1 which is the number that is set on the camera so this part is correct but when I am zooming it should be going to 6.25. When there is only one object with this script in the scene it does that no problem. But when there is more than one object with that script then that part of the script never gets about 6.12. There is only one camera in the scene and it is tagged correctly and is being referenced correctly from my understanding. Any ideas or direction on how I can solve this greatly appreciated, thank you.
For context… this script is attached to a ball object. in the script I am trying to reference (this ball) "ball" the (main camera)"cam" and another script on the ball (ballInteract.cs) "ballInteract". There is a bool on ballinteract called "isDragging" when its true I am interacting this this particular ball and this script should be activated (and only this script and this ball). As I drag my mouse further away from the ball the startingVelocity another value in Ball interact which determines the velocity the ball with be shot with is pulled. the higher the velocity the more of a zoom I am supposed to get. Up to 6.25 from 6.1. I assume that this code is telling the camera to do what I mentioned ( of course I could be wrong I'm still new at this ). And when I am not dragging everything should go back as it was. And for the most part this works perfect when only one object is in the scene this script but as soon as I dup the object or prefab it, the zooming gets jacked up. Oddly as you can see in the attached gif. both balls are getting the correct reference. and there is only one camera and it is tagged correctly. It’s just the zoom wants to not play nice for some reason.
I mean it seems fairly obvious that since you have two scripts the else part of Update is always running for at least one of them
so it's fighting against the other
what you need is one centralized place to control the camera zoom
@leaden ice You know I never thought of that... good point.
Yeah that sounds really handy.
I think there's an InterallyAvailable attribute or smth specifically for allowing internal members or classes to other assemblies. But that's the only attribute i know of that modifies security. Even then, that aforementioned attribute don't make a lot of sense imo. 
Considering you can just make assembly references.
Anyone know why this is happening to my car?
https://i.gyazo.com/4f3e3dcfe207e09ca9b1ce8c75113bbb.gif
private void HandleSteering()
{
currentSteeringAngle = maxSteeringAngle * horizontalInput;
frontLeftWheelCollider.steerAngle = currentSteeringAngle;
frontRightWheelCollider.steerAngle = currentSteeringAngle;
}
private void UpdateWheels()
{
UpdateSingleWheel(frontRightWheelCollider, frontRightWheelTransform);
UpdateSingleWheel(frontLeftWheelCollider, frontLeftWheelTransform);
UpdateSingleWheel(rearWheelsCollider, rearWheelsTransform);
}
private void UpdateSingleWheel(WheelCollider wheelCollider, Transform wheelTransform)
{
Vector3 pos;
Quaternion rot;
wheelCollider.GetWorldPose(out pos, out rot);
wheelTransform.rotation = rot;
wheelTransform.position = pos;
}
It's possessed
There's probably something wrong with your setup
Not sure what it'd be
Like wheel colliders being parented to the visual wheels
Or having some weird offset on some of the children

Might want to record that video again, but with all the gizmos enabled and visible. Especially the wheel colliders ones
how do I enable those in game again?
On the top right of the game view there's the gizmos tab.
found it ;3
the rear wheels might be an issue
since the two rear wheels are one single mesh
so I can't add two wheel cplliders
Why is it one mesh?
I couldn't tell you
Is it also 1 wheel collider?
yes
Well, that's not gonna work.
Take a screenshot of your wheel meshes transform and wheel colliders transform.
I like those wheels.
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
You can tryparse to the type you want
What is this input though? Tmp input field should have an option to only allow numbers
I meant the number keys on your keyboard
checking if any of them are being pressed
Absolute easiest way would be looping through the numbers and checking get key with the number as a string. Although this wouldnt be fun to adjust in the future like if you wanted key remapping
ah I see
so what's the normal way of handling logic for, let's say, number bound inventory slots?
It can't be checking every individual key, that sounds really inefficient
loop from alpha1 to alpha9, and check alpha0 (it may be mapped to 10)
Hey y'all! So I have a MeshRenderer component that's being disabled every frame, but I genuinely have no idea which script or what code is disabling it. What would be the most efficient way to debug this to figure out where it's being disabled from?
(I know it's being disabled every frame because I can't enable it in editor while it's running. I can enable it when it's paused, but then it's disabled again as soon as I resume)
find the reference to that component in editor and find any GetComponent<MeshRenderer>()
By find reference in editor, do you mean this?
Because that doesn't seem to find any references in scene
I'm assuming the issue is that the meshrenderer is either for some reason disabling itself, or there's a GetComponentsInChildren somewhere. The prefab is completely new, so I know I have no direct and intentional references to this component in any old code.
Use your IDE FInd function to find all references to MeshRenderer.
You could also find all referencces to .enabled
Hey, does anyone know why this bit of code is causing the grid selection indicator to be offset, instead of directly in the cell where the mouse pointer is?
Vector3 mousePosition = inputManager.GetSelectedMapPosition();
Vector3Int gridPosition = grid.WorldToCell(mousePosition);
mouseIndicator.transform.position = mousePosition;
cellIndicator.transform.position = grid.CellToWorld(gridPosition);
this is the code for getting the mouse position
public Vector3 GetSelectedMapPosition()
{
Vector3 mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
lastPosition = mousePosition;
return lastPosition;
}
If I have 100 agents who behave differently and execute different tasks, do I have to create a script for each or can i manage all in one?
consistently getting this error - this was working on my pc but not working on my pc at university - I've tried reimporting assets, etc. IDE reports no errors within the scripts however - any solutions / things to try to get it working?
Are you using the same version of Unity on both machines?
Yeah, unless the PC I've logged into today happens to have a differing version lol
using 2022.3.0
definitely not a good version to be using
well that's reassuring
if it was me I'd be using either LTS or a newer version
Always the latest LTS unless there is a really, really good reason not to
I am so confused on as to why this error as appearing now; the class never had an extension attribute in the first place but it seems like unity is expecting there to be one?
its just simply defined like ```cs
public static class CameraSwitcher
yes, and something else is checking for an attribute it does not have
Could that be due to me referencing it in another script, outside of the namespace? I have put the whole using Camera (the namespace) at the top of the script so I'd have assumed it'd be able to access it
because the thing is that it was a) working last night and b) Rider is not reporting any issues
probably not you but something internal to Unity. Have you checked all of the Package Versions you are using? It could be something as simple as an old package
only updates available are for VCS and timeline, don't think they'd be relevant to the issue 
yes, but it could be that the updates are not available because this is an old Unity version
Is it a MonoBehaviour?
no, there's no class inheritence on the defined class that's reporting the issue - however the same script does contain a mono behaviour for another class (same name of file etc) but that's not the error
yeahhh its a pain in the ass this lol
Is there a stack trace to that error?
CameraSwitcher is your own class?
yeah
why is it in the Camera namespace?
its just the folder name
it wouldn't be directly being the UnityEngine.Camera
its just standalone
change the namespace, I think by using Camera you've confused Unity
how would I view that
I'm not sure about it. But worth a try.
I'd like to see the error details though.
Select the error. Is there anything in the bottom?
just tried that to no avail unfortunately
Hmm... Are you using it with GetComponent or something like that anywhere?
Can you change CameraSwitcher to something else?
the only reference I truly have to it is in my base class for my finite state machine
public virtual void PhysicsUpdate()
{
CameraSwitcher.GetActiveCams(out ThirdPersonCam, out FirstPersonCam);
switch (MainCamera.ActiveCameraMode)
{
case CameraSwitcher.CameraModes.FirstPerson:
if (MouseInput is {x: 0, y: 0}) return;
if (TargetRotation == Vector3.zero) return;
if (XRotation == 0) return;
Character.playerMesh.transform.Rotate(Vector3.up, MouseX * Time.deltaTime);
XRotation -= MouseY;
XRotation = Mathf.Clamp(XRotation, -Character.XClamp, Character.XClamp);
TargetRotation = Character.playerMesh.transform.eulerAngles;
TargetRotation.x = XRotation;
FirstPersonCam.transform.eulerAngles = TargetRotation;
break;
case CameraSwitcher.CameraModes.ThirdPerson:
var cameraPos = ThirdPersonCam.transform.position;
var playerPos = Character.PlayerTransform.position;
var viewDir = playerPos - new Vector3(cameraPos.x, playerPos.y, cameraPos.z);
Character.PlayerTransform.forward = viewDir.normalized;
var inputDir =
Character.PlayerTransform.forward * MouseInput.x +
Character.PlayerTransform.right * MouseInput.y;
if (inputDir != Vector3.zero)
Character.playerMesh.transform.forward = Vector3.Slerp(Character.playerMesh.transform.forward,
inputDir.normalized, Time.deltaTime * Character.RotationSpeed);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
like just rename the class?
yes
give me two secs I'll give it a go
what the fuck
how does it work now 
wait a min
premature celebration
there was obviously a name conflict
so not. hmm
this is so goofy
but no stack trace?
no stack trace whatsoever
I can try finding one via rider in debug mode but idk if that'll get anywhere
I doubt coz I dont think it's in your code
why did you switch the namespace back to Camera
because the change to another namespace didn't fix it
it's a combination of changes. Change it again
Try finding all the references of the class. Maybe there's somewhere you're using it you don't know about.
Also share the whole file code
I'm aware of all of these already
of the mainCamera.cs script:
ohhh
Did you rename it?
Camera.CameraChanger
that's within mainCamera
📃 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.
two secs
bear in mind too that this has been working 100% successfully up until today
what happens if you just add the attribute to the class?
what attribute
the one it says is missing
Attribute not inheritance
[ExtensionOfNativeClass] above the class declaration
no 1 in the error message
I think the issue might be with your extension methods and using coroutines.🤔
Does the error disappear if you comment out the code?
shouldn't be, like I said - has worked on every pc up until now
Inside methods.
the code with coroutines?
with the coroutines commented out still no worky
same error message
you are thinking CineMachine conflict?
the coroutines however are under the class CinemachineExtras which does not exist previously from within Cinemachine
so that shouldn't be what'd be giving the issue
Indeed. Didn't notice.
might just rewrite a lot more of my code than I originally anticipated to get around this issue

does anyone know why this might be happening?
It's a very odd bug and without a stack trace virtually impossible to track down
What if you remove the Debug.Log's from the static methods?
iam colliding with my player and vendor to open a shop, but i dont see the debug line being executed
{
Collider[] colliders = Physics.OverlapSphere(transform.position, interactionRadius, playerLayer);
foreach (Collider collider in colliders)
{
if (collider.CompareTag("Player"))
{
Debug.Log("you collided with vender");
return true;
}
}
return false;
}```
The tag and the log don't seem to match.
Anyway, more debug.Logs
Could someone help me?
I am working on an inventory system, for the premade FPS game that unity made. I have a script on the enemy which drops the item and an inventory script. I do not know how to get these to properly communicate.
same issue - but y'know I wouldn't have assumed it'd be the cause as it was working perfectly beforehand
i changed to the inbuilt function: private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { if (Input.GetKeyDown(KeyCode.B)) { Debug.Log("Player entered vendor's interaction zone."); PurchaseItem(); } else { Debug.Log("Player is not nearby a vendor."); } } }
Logically, if this code is working on your home machine, there can be only 2 culprits
- Unity version
- CineMachine version
I use github for vcs though so it should import the specific versions when I clone the project and set it up on another system
no, not if that version is not supported
I can check the package manifest at least and compare the versions
they're both identical
You really need to start putting logs OUTSIDE your if statements to see what's going on.
Also input handling in a physics callback will not be reliable
fixed the issue
thank god
thanks guys for your input
it seems splitting up the classes into their own files is what was needed
weird but it is what it is
var amount = Input.GetAxis("Mouse X");
transform.RotateAround(obj.position, transform.up, amount);
``` So, I currently have this code that rotate the camera around an object when mouse button 1 is being held, and I need it to smoothly snap to 90 degrees after I release the mouse button.
How can I achieve this?
lol, I was just about to suggest you do that
Any suggestion of best way to incorporate a point and click dialogue system for a game?
What do you mean with point and click dialogue? Like a conversation window? If so there are plenty assets in the asset store
As a good starting point
Hello, using XRInteractionToolkit I'm currently trying to figure out a way to check if an object has been placed in the XRSocketInteractor, what I am trying to achieve is a way to set the parent of the object that has been placed in the Socket to be the object that has the XRSocketInteractor as a child
Do not cross post
there's a solid spacing in time between each post
I'm trying to get a reply somewhere, sorry again
4 minutes is not 'solid spacing'
also two hours ago in #🥽┃virtual-reality
can anyone help me with this?
private IEnumerator SmoothSnap()
{
Vector3 startRotation = transform.eulerAngles;
Vector3 targetRotation = new Vector3(0, 0, 90);
for (float i = 0; i < 1; i += Time.deltaTime)
{
transform.eulerAngles = Vector3.Lerp(startRotation, targetRotation, i);
yield return null;
}
}
I'm using RotateAround, it changes both the position and rotation of the camera, so this wouldn't work as it just changes the rotation
Or would it? Correct me if I'm wrong
no it wouldn't
Yeah, so what do I do?
i wanna keep everything flexible because every vendor sales something different
{
Debug.Log("Item purchased!");
// Add the purchased item to the player (e.g., increase gold)
if (player.playerData.resourcesAmount.ContainsKey(currencyExchange))
{
player.playerData.sellingItem += itemAmount;
player.playerData.resourcesAmount[currencyExchange] -= itemCost;
}
} else {
Debug.Log("Not enough " + currencyExchange + " to buy gold.");
}```
but i get erorr where sellingItem cant be found
i have a string variable, public string sellingItem;
show full error
error CS1061: 'PlayerData' does not contain a definition for 'sellingItem' and no accessible extension method 'sellingItem' accepting a first argument of type 'PlayerData' could be found (are you missing a using directive or an assembly reference?)
{
public Dictionary<string, int> resourcesAmount = new Dictionary<string, int>();
}```
basically sellingitem is what de vendor sales
no sellingItem here
thats something you would create later in the inspector
you have not even declared a variable so how could it be filled?
Are you doing a challenge where you are only allowed to use native types? Why is your item a string and not a class?
my sellingitem is declared in the vendor class public string currencyExchange; // Resource type of the item public string sellingItem; public int itemAmount; // Amount of the item to give public int itemCost;
so why are you trying to access it with playerdata?
vendor will check if you have the right currency
and then give you the sellingitem
no playerdata will hold strings like wood, silver, wool etc..
player.playerData.sellingItem += itemAmount;
doesnt work
your error is saying you're trying to access it on playerdata
Uh, I was just trying to show that you do access sellingItem by PlayerData even though there is no field called sellingItem in PlayerData. That's why you're getting that error
public class Item
{
public string name;
public int cost;
}
public class Vendor : MonoBehaviour
{
public List<Item> stock = new List<Item>();
}```
You should do it like this or you are gonna have a to make a new dictionary for each field your item has.
I would class it for flexability but that depends on what functionallity you want on the item.
Can we get back to this if plausible? Thanks.
yup
Use a float variable for the target angle and the smoothed angle
Also just make the classes inherited.
For items you want to make...
I got nothing from that
Can you elaborate?
GetAxis is no where close to a degree angle
its range is -1 to 1
RotateAround is additive though
One degree per update cycle then?
I'm aware
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.
Documentation doesn't specify amount. So I guess just see what it outputs.
The amount depends on how much you moved your mouse, if that wasnt obvious
So when you release the mouse, you could start a coroutine that smoothly rotates the camera to the snapped angle.
You could get the angle with something like Vector3.SignedAngle(transform.forward, (obj.position - transform.position), transform.up)
Then snap it with Mathf.Round
Then use SmoothDampAngle, MoveTowardsAngle , Quaternion.Slerp or some other way to smoothly rotate towards that angle
you probably don’t want to set mouse to get axis input. that sounds like garbo
you will want to get mouse position, then work with that
It works just like Input.mousePosition tbh
really? that is not what I would expect
Oops I mean
Wait what's thet other way to even get mouse delta, I forget
Right, there is no other way (in old input system)
AFAIK checking the difference of Input.mousePosition produces the same result as GetAxis @hard viper
anybody know if these things exist in code as enums or something similar?
How do I know which angle I'm at right now though? Or do I not need to know that?
Did you read
You really don't since Rotate around is addative,
Briefly, sorry for that lol
The angle I'm talking about is the angle from camera to the object. The one calculated with Vector3.SignedAngle
I feel so stupid now
Hi guys i have asked a question on SO if anyone has some time to take a look : https://stackoverflow.com/questions/77474682/how-client-server-rpc-works-with-global-variables
How would I transfer the momentum of the animation to the rigidbodies on my ragdol?
If I activate the ragdol mid-flight it looks weird like it "snaps" it doesn't look smooth.. Any ideas how to make my ragdoll spawn with that momentum of animation flying back ?
as you can see it looks very ugly transition
I did that by having each bodypart record its position change (so "velocity") every frame when it is being animated
And then applying that "velocity" to the bodypart's rigidbody when activating ragdoll
All this in world space
😅 any tips on how to do this ? I'm kinda lost on this one. thought this as well
are you just keeping track of positions and not rotations ?
public class Bodypart : MonoBehaviour
{
Vector3 currentPos;
Vector3 lastPos;
// Cache the positions
void FixedUpdate()
{
lastPos = currentPos;
currentPos = transform.position;
}
}```
Ahh like that
Then when activating the ragdoll you could add a force that is currentPos - lastPos
thanks! I will try this out
As a bonus you can do it with rotations + torque too, but I didn't bother myself, position looked good enough
oh yeah thats a good idea i might try that too
does it matter that my RB start kinematic ?
Probably not, as long as you make them non-kinematic before adding the force
yea ofc ofc
thx
I just do ```cs
public void ActivateRagdoll()
{
foreach (var limb in limbsCol)
{
limb.isTrigger = false;
}
foreach (var rb in rbs)
{
rb.isKinematic = false;
rb.useGravity = true;
rb.gameObject.layer = LayerMask.NameToLayer("RagdollIgnore");
}
anim.enabled = false;
1 more thing, depending on your anim setup, the FixedUpdate position values might not be correct so you might have to use Update or LateUpdate
And then do some maths to convert it from 'deltaTime' velocity to 'fixedDeltaTime' velocity... But see if FixedUpdate works first
sounds good, will try both ty
its strange I thought animator would keep track of the whole avatar/limb positions or something
I don't think it has any idea what happened last frame
It doesn't really need to know about it
true
You might also need to add the forces in a second foreach loop, to make sure that every rb and its connected rb's are not kinematic
good idea Ill put that one after
is there a way to cast a shape with rotation?
like, if I have a box, and I want to cast it as it rotates, and query what is in the middle
Like having a different start and end rotation for the shape?
Nothing that I know of, though you could try doing it in steps
ty. I’ll think about it more
one more physics thing I’ve still been mulling over for days is getting contacts outside of physics update
specifically, getcontacts just grabs contacts from last physics update.
and my current challenge is that Collider2D.Cast only generates one hit per collider. But I have tilemap/composite colliders with advanced shapes, so it’s very possible to have multiple actual contacts with different normals to that one collider.
does my question make sense?
oof
for some reason this is the result
if I play frame by frame before turns into ragdoll the whole thing expliodes (see gif above)
red lines are result of ( currentPos - lastPos)
this code should actually add the new items to my list // Add the purchased item to the player (e.g., increase itemType) player.resourcesAmountList.Add(new ResourceData { resourceName = itemType, amount = itemAmount });
in this case the vendor sales gold
for 100 wool
What are the red lines? Is that the velocity?
oh wait you said .velocity not addforce
my new ragdoll
public void ActivateRagdoll()
{
foreach (var bodyPart in bodyParts)
{
bodyPart.Col.isTrigger = false;
bodyPart.RB.isKinematic = false;
bodyPart.RB.useGravity = true;
bodyPart.gameObject.layer = LayerMask.NameToLayer("RagdollIgnore");
bodyPart.RagdollActive = true;
}
foreach (var bodyPart in bodyParts)
{
bodyPart.RB.AddForce(bodyPart.Dir * 10, ForceMode.Impulse);
}```
nvm wait
was about to say it does that lol
my code works partly, only the part where the vendor has to return 1 gold for 100 wool doesn't work, what goes wrong: https://hatebin.com/kjwzcckagp
Start with drawing the rays also while ragdoll is not active
will do
bit of a mess 😅
Would be less messy if the ray wasnt 100 long lol
true lol
Anyway looks like it's jittering somehow, maybe because it is FixedUpdate and not perfectly synced with anims
@rigid island Try LateUpdate instead of fixed
Also don't add such a massive force... Why is it multiplied by 10
late update and shorter rays
direction seems ok
but i tried 10 because it wouldn't addforce or barely
it still doesnt it just flops down 😦
Set their angularVelocity to zero and also use velocity instead of addforce
I remember having issues with execution order or something so it took me a while to get this right
like this ?
cs foreach (var bodyPart in bodyParts) { bodyPart.RB.angularVelocity = Vector3.zero; bodyPart.RB.velocity = bodyPart.Dir; }
Yeah
There's also this..
still floppy fish
LateUpdates may happen way faster than FixedUpdate so the vel is smaller
But FixedUpdate is not in sync with animations so i dont think it works here
hmm should I add a multiplier maybe ?
nope it just stops midair again
oh wait I put * 300 and got closer
to soemthing
it moves correcrt dir but transition still weird
Actually yeah I think you gotta multiply with 1f / Time.deltaTime 🤔
Idk, step through it frame by frame and see whats wrong
is there a reason when I step frame by frame before transition the limbs explode?
Not sure, maybe Time.deltaTime goes crazy
lol
it only happens when you frame by frame before transition to ragdoll and not after
nvidia physics is weird af mann
I also suggest adding a slow-mo button/hotkey to your game that just sets timescale to like 0.1
Helps with debugging stuff
good idea!
yeah i did it right before .velocity part and it seem it just doesn't like to transition smooth lol
direction is correct at least
if I read correctly on internets this has to do with joints might not be able to keep up
reduced velocity multi a bit and it helps a little :\
It does seem to freeze for at least 1 frame
Did you use unity's own ragdoll thing?
The colliders usually do need a lot of tweaking
I did it by hand without unity's ragdoll tool, but you can probably work from there
Enabling this on the joints might help... https://docs.unity3d.com/ScriptReference/Joint-enablePreprocessing.html
And upping your iteration count in physics settings
A lot of trial & error goes into this stuff
yeah it seems so, I have to play around with some settings
thank you for link as well this looks promising
Tbh this gif looks correct apart from the little freeze, right?
yeah not as noticeable
The freezing moment, from what I understand is when the joints are glitching and can't solve a good position/rotation for a moment
I think enablePreprocessing might help with that but not sure
Also yep make sure colliders don't overlap.
Also I prefer capsulecolliders for ragdolls. No edges, just smooth surfaces
enabled it but still does the same, its just not as bell
ohh for my chest area you mean?
I might have confuesd enablePreprocessing with Enable Adaptive Force in physics settings
Try enabling that, and also the solver iterations (first two settings in this screenshot) are at really low settings by default
Make them like maybe 32 and 8 or something
trying now
yeah still weird hitch
its the arm chest area so maybe it is bad colliders?
the chest and hip boxes seem to be intersecting
Yeah fix the colliders first. Also try disabling collisions in each joint settings
@rigid island make a thread so we dont flood?
using unity editor version is directly tied to the version of the Unity API?
eg if a function is added in 2023.1, do you need to upgrade editor to 2023.1 to allow your code to call it?
yes
Also, I’m putting a lot of effort into my custom physics engine. How much do you think people would be interested in using it?
it’s similar to the KCC system, but it has the following pros/cons:
Pro:
-Reference frame handling (effective parenting of rigidbodies)
-Easy to write new effector logic
-Polite physics: force only ever transfered by truly kinematic RBs.
-Built in ground handling (slopes, floor, snapping), and get contacts/grounding state to use at the start of fixed update.
-Can specifically request one-way ignoring of forces (ie collider A ignores force from collider B, but not visa versa)
-You can read where kinematic RBs plan to move to (midframe)
Cons:
-No rotation
-Moving objects need CompositeCollider2D for PolygonCollider2D/CircleCollider2D/CapsuleCollider2D
-Only allows one thread for physics sim
-Only allows one main collider for a given rigidbody to drive its motion.
-Heavier than normal Physic2D
-No Joint2D
No rotation is probably a dealbreaker for most people
as is the lack of non-box shapes
I assume no rotation is the biggest issue imo
I could write this engine to be more ready for use with other peoples’ projects. Or just keep on with my own business. Is it worth publishing?
it very much has a “big restriction => unique big payoff” feel
ty for the input, praetor
tbh It feels like you are trying to bolt a wart onto a carbuncle, If I was to go so far I would make my own rigidbodies and colliders and ditch Unity physics completely
i’m basically there. but I use Unity Physics for collision callbacks. I could relatively easily replace it tho
unity physics lets you get collision callbacks from colliders not involved with custom simulation
multi threaded collision system is not hard to make and has the benefit of being much faster than Unitys when large numbers of colliders are involved
I would need to think more about multi threading. The most expensive operation right now is getting contacts, which can be multi-threaded easily.
multi threading is where a own built system will win hands down over Unitys pedestrian system every day
but i’ve never done multithreading before, and I don’t have enough complete control over my one thread to experiment with multithreading + physics at the same time
time to experiment and learn, its not that hard, honest
like, i don’t have it truly down yet, and I need to get my shit together before I can even consider splitting the task.
if that makes sense
when I am in control of the situation, I can revisit to multithread
yep, I understand, visualizing multi threading/multi tasking can be a royal pain in the arse and generate lots of headaches
in theory, I can identify many spots in code where I iterate over an IEnumerable, each iteration is relatively expensive, and I could split the tasks across multiple threads easily
that would be a good start and pay big bonuses
that’s probably as easy as it gets tbh
what is the best system to learn for multi threading? jobs?
nah, just microsoft learn, this is pure c# and Unity just unnecessarily complicate things with DOTS/ECS
which is the right system to learn then?
just standard C# Threads and Tasks
so let me get this straight. Lets say I want to: foreach (x in IEnumerable) ExpensiveFunction(x);
do I do something like:
foreach (x in Ienumerable) {
Task t = new Task(() => { ExpensiveFunc(x); busyTasks- -; });
busyTasks++;
t.Start();
}
while (busyTasks > 0) {}
not really, no
The concept is correct. There are prettier and safer ways to do what you're doing at the end there which is called "joining" the threads
you could do
foreach (x in IEnumerable) {
Thread th = new Thread(ExpensiveFunction);
th.Start(x);
}
(there's also Task.Run)
that makes sense to me too. but I also want to make sure everything is done before I continue main thread
lots of options, that's why I said experiment and learn
add them to a list as you start them and use Task.WhenAll
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=net-7.0 to join on a bunch of Tasks which you can get from Task.Run for example
may I suggest you just make some simple Console apps to learn the basics of this, then try to bring them back into Unity
i think I’ll dip my toes in it to give it a shot and learn
it will repay you 100 fold
Once you learn these concepts it will be much easier to dip into the Job system too
ty guys. I think I’ll start by making a simple static method to do something like: RunForEach<T>(IEnumerable<T>, Action<T>) that does what we described
course on OS should teach threading in general
yeah, I never properly learned threading in school
but that class was apparently suffering because it was writing code to implement threading in assembly. so maybe I didn’t miss out too much lol
No, this is advanced stuff, overuse of Threading and Tasks by the ill informed is worse than not knowing it
yeah, there is danger because many things are not thread-safe
and I don’t want to thread too much because that will open pandora’s box of not knowing wtf is going on
but as I make a simple physics engine, I think it would work to just identify key blocks of the physics loop to split across threads
as I said it can become very difficult to visualize, race conditions abound
my plan is to ride the bunny slopes and say I skiid at least once in my life, steve
Ive never had issues with unity hanging after playmode runs for awhile but it keeps happening on this project about flying agents, does anyone know what to make of this? I have no idea what is actually causing this to happen.
looks like infinite loop or something
RAM use will go up until you crash
End Task
I have removed every while loop and have made them just run in fixed update because I assumed this was the case but it still happens, also it runs for a random amount of time before hanging, Ive had it happen in 2 minutes and 40 minutes
easy test would just be to disable the script
you can share the script if you want
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'll see about posting the script I would appreciate it thanks. I have tried pinning it down by disabling scripts but its hard to tell when it can sometimes take 40 minutes to hang. Im doing one last test right now and then I'll upload code
Are you saying you moved the while loops into FixedUpdate?
no no no not literally, as in I rewrote the parts that were while(true) and moved them to fixed update in case that was the issue
the original was a while (true) that then sets a goal and checks (goal isnt reached) before returning to set another goal, so didnt really need to be a while loop to work
heres the script where I moved the coroutine to fixed update, sorry for all the commented out code Ive been trying everything to find whats causing it https://paste.ofcode.org/6d6QPYDLQ4iHAudYnj3LXT
and heres another script that could be responsible https://paste.ofcode.org/xWEJ336uG8zH8J7C8rgTfh
you can see at line 38 and 60 that I took what was originally generating a grid on awake and made it generate it every set amount of seconds, I dont think that this is whats causing the crash because I ran it with no agents activated and it never froze, but maybe it just needed to be ran for even longer to have actually hung, thats whats so annoying about this
How to make the Physics.OverlapBox exactly around the object, given that the object is not static, it can rotate around its axis. Do I have to use all 8 angles of the object to create this? Because I took Vector3 ((bounds.min.x, bounds.min.y, bounds.min.z) and Vector3 ((bounds.max.x, bounds.max.y, bounds.max.z)), but when the object rotates around its axis, it doesn't exactly do what I want.
In simple terms, the goal I want to achieve is to verify that the object on which the script hangs has an intersection with another object other than the ground and its daughter objects.
The OnCollisionEnter method doesn't work for me, so the method described above has to be called once at the time I need it.
There's a little sketch of my code.
https://hatebin.com/bwyoybswvv
Don't worry about all the unnecessary variables and the general crappiness of the code, I'm just experimenting.
Thanks in advance for any help.
So are you trying to say that the position you're casting OverlapBox on isn't centered on gameobject? Maybe clarify a bit more or maybe some screenshot of the scene hierarchy if needed.
It's because of the minimum and maximum points.
But can I use more than two dots, like 4, 8?
i dont understand why it never reaches the item to buy:
https://hatebin.com/rozowgqbge
!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.
Ah, right the box collider doesn't rotate with the gameobject transform values, so the collider is lower in the hierarchy? I think meshcollider does though which you could consider, otherwise what you're trying to do is probably the idea. Otherwise you could consider restructuring it all and make both the mesh and collider siblings (which is probably ideal)
my rule of thumb is: If I’m on mobile; and I need to swipe >2 screens to cross your code, you need to use a pastebin
how would one add velocity to a kinematic Rigidbody?
hey guys need help, my code can setup the rig weight to zero in start but when I call it again in LookAtPlayer() it does not change
https://hatebin.com/onkmnosymq
!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.
- if you spam var keyword, it’s hard to know wtf your variables are
- kinematic RBs don’t use velocity in 3D
you would need to call MovePosition every frame to advance
someone?
Can't say. The very first if statement does not pass the condition, and you haven't posted the code of the CanPlayerAffordItem() method.
Hi! I have a deserialization problem that I've found surprisingly hard to solve:
I have a type, Entity, which in turn amongst other things keeps a list of children, which are also of type Entity.
As soon as I have this in the code, I get a runtime warning that "Serialization depth limit 10 exceeded" and "There may be an object composition cycle in one or more of your serialized classes."
Yes, I know there's a cyclic reference, but it's not infinite since the list of children will be empty at some time (actually, I've only got two levels of nesting currently), so I can't see why that should be a problem.
I'm using JsonUtil.FromJson to deserialize. Any hints how I should setup my Entity class?
i would use a class in the middle
The entity class itself should be fine, I think you would benefit from using Newtonsoft instead.
i might refer you to this generic class
it is a generic data structure that effectively stores a hierarchy of TStored
not saying it will solve your problem, but I think it will be helpful to you
i can update the code for it later if you are interested
Thanks! @hard viper . Not sure what benefit I get from Newtonsoft? New to C# and Unity. But it seems to pull in another package just to parse JSON, when there's already support for that built-in, seems a bit overkill when this is the only problem I have.... 🤷♂️
But I will sure look into it if I don't find any other solution.
the class I sent you uses several IEnumerables. Are you comfortable with that?
the docstring at the very top should explain how to use it
For Unity, its Json tool is a much more lightweight version of what Newtonsoft have I believe. Really depends on what your problem is and if the difference between the lightweight and the other would help.
Newtonsoft is more flexible, you can define your own json converters and their website has a lot of examples
Mm, sounds like what you would expect. But I've moved that complexity to the JSON generator, which is outside of Unity, so I don't have much problem with that (currently). I just want to have entities with child entities. And it even works: it seems to only be a warning...
my whole class: https://hatebin.com/grqsrciczi
Take some basic debugging steps here. At least one of the conditions on lines 27-28 returns false, causing the whole && to return false. Log both the conditions before returning their values
Or use the debugger to step through the code line by line
Also the call on line 21 is completely unnecessary and can be removed entirely. It's eating out processing power for nothing
Also line 96 introduces a flaw in the code, when the player exits the trigger once, it won't be able to interact with the shop anymore
I'm making a multiplayer game with photon pun 2, what would be the best way to save account details for players like username, account level, coins, etc.? is it databases or can I somehow do that with photon? And if its databases, what would you recommend?
So I've got this code that I found online that deals with when a ball hits a wall it'll reflect off of it. It works fine until it hits a corner, then it either stops moving or slides against the wall until another corner.
{
lastFrameVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("wall"))
{
print(collision.contactCount);
Bounce(collision.GetContact(0).normal);
}
}
private void Bounce(Vector3 collisionNormal)
{
print(collisionNormal);
var speed = lastFrameVelocity.magnitude;
var direction = Vector3.Reflect(lastFrameVelocity.normalized, collisionNormal);
//Debug.Log("Out Direction: " + direction);
rb.velocity = direction * Mathf.Max(speed, minVelocity);
}
I got it from this:
For photon specifically I cant answer, there is a photon discord pinned in #archived-networking
For storing account details, regardless of what method you choose, you'll need to store them somewhere on the server. If its only stored locally, people will easily manipulate data. Any database you choose should be fine, since you arent gonna be doing complex work on these. Just read and write pretty much
thanks much :)
Can someone assist me with this issue?
https://i.gyazo.com/eaabdfd7c121f5131e73fd2e3d8d3456.gif
I'm getting error CS0201, here's the code: https://pastecode.io/s/6ac41iwo
Please format your code correctly, and try again
This is pretty much unreadable
How so?
does your tab key not work?
Visual Studio 2019/2022 : Hit Ctrl + K, Ctrl + D
VS Code : Hit Ctrl + Shift + P, and search for "Format Document"
If these do not do anything, your code editor is not configured to work with Unity, and you should do so before asking questions here
Seriously?
It's the same as before
Well I formatted it.
No
do you not even check what you post? Strike II
Wait I have 2 strikes?
For reference, this would be your Start method, formatted:
void Start()
{
if (transform.position.y == 5.5)
{
(set == set + 1);
(preSet == preSet + 1);
}
}
What did I do to get the first strike?
Lots of errors in it, but at least it looks good
Strike III, Block
Block?
Steve is not a moderator, dont mind him
Steve's power trips, you can ignore
Only moderators can inflict strikes
Anyway, format your code correctly and post it again
Looks like your wheel mesh/visual object is a child and its local position is not zero? Also don't cross post please
I hope it's right this time: https://pastecode.io/s/df0psv5j
lol you barely changed anything
Mate just use the tools your code editor gives you
but lines 12 and 13 are not valid
your IDE will auto format this for you, is your IDE even configured though?
You mean extensions?
What code editor are you using?
VS
Instructions here #archived-code-general message
For me it is just Alt+Shift+F for VSCode
Yeah that works, I didn't remember the exact keybind
But yeah almost nothing is valid in there. Comparing floats with doubles, assignments with ==, parentheses that will break things, etc.
Show inspectors of the wheel and its children, what object has what component etc.
Okay looks better now. Lines 13 and 14 are not valid
The wheel transforms have an odd rotation of -89
How do I fix them?
You're trying to compare two values, but you do nothing with the result. This produces the first two errors
Perhaps you meant to use = instead of ==, so you put a new value into those variables?
== compares, = assigns
Okay, change it? 🤔
Also this
I would but the pivot point is incorrect
you might have to fix it in whatever tool it was created in then
Yeah probably imported from blender, there's a ~90 degree difference on X axis
Now it's giving me an error called "Only assignment, call, increment, decrement, await and new object expressions can be used as a statement".
Yes, I changed the == to =
Now get rid of the parentheses because they're not supposed to be there
It causes the line to be interpreted differently, which causes the error
The error is gone
How to make a coroutine WaitForEarlyFixedUpdate?
WaitForFixedUpdate seems to wait for after collision callbacks etc are all done
I have singletons to work with if I need delegates
Will collider.isTouching always return true for at least one frame if 2 objects touch? Or is there a chance that if they aren't touching on one frame and then have bounced off each other by the next, that it will never be true since there was never a frame where they actually touched?
Sry if that's confusing lol
It is performed against the LAST physics frame, and yes it will be true even if it is only one frame
I was following brackeys rpg tutorial and in stats episode I had a problem about modifiers not adding.
PlayerStat :https://hatebin.com/brveegyegz
CharacterStats :https://hatebin.com/oemqfhfurh
Stat :https://hatebin.com/vzwnqrwubm
EquipmentManager:https://hatebin.com/cucdffbbcb
Debug.Log("Equipment Changed"); this line works but rest doesnt.(it's in playerstat)
Well, the only place I see where the onEquipmentChanged event is invoked, you pass in null and oldItem
oldItem is initialized as null, then only set inside a condition.
Then you invoke the event in a SEPARATE condition
So both parameters are clearly null
Try this simple change?
https://hatebin.com/jpoopzlzsz
Tried it but nothing changed as I can see
now it does not say Equipment Changed
currentEquipment[slotIndex] is null
Which is why only the debug ran before.
Now it won't call the event unless it's not null, because why call the event if both parameters are null?
So yes it should not say Equipment Changed
Now you have to figure out the real issue of currentEquipment[slotIndex] being null
Am I able to make a list of a constructor?
For example, if I have a constructor Person(string name, int age), could I make a list of those?
Or is there something similar I can do?
How would I create the list?
List<Person> myList = new();
But don't I have to make the list before I can create constructors?
? No. The constructor is compiled. Adding the instances would be runtime. What do you mean?
myList.Add(new Person("John", 18));
So should I make a new if statement that has the currentEquipment[slotIndex] = null condition?
I didn't think it would work because I thought I had to create all of my variables (like lists) before I could use them in classes, where I would create the constructor
What would you do in that?
Well the list obviously couldn't be in the Person class....
But yeah, initialize before usage..
What are you even talking about?
If you are talking about physics frames, then yeah. If you are using Update/LateUpdate loop, then you are doing physics wrong
Unity can run multiple physics steps before it renders a frame
Idk where you got "Well the list obviously couldn't be in the Person class...."
What I'm trying to say is that for me to be able to make the list of constructors, the constructor would have already have to have been created - but I can't do that, right?
As I asked before, what is a list of constructors. I said you can make a list of INSTANCES
Wtf does list of constructors mean?
doesn't if (currentEquipment[slotIndex] != null) mean if there is already an equipment in the slot,I thought nothing would happen if there isnt anything in the slot before
Exactly. Nothing happens, and the event is not invoked, which is why you don't see the log
Maybe I'm using the wrong terms, sorry. But imma leave if you're gonna talk like that :/
?? Talk like what? But Ok. Suit yourself. I'll keep that in mind in the future.
Explain yourself next time
thats why I asked about adding something like if(currentEquipment[slotIndex] = null)
Ok yeah, and my question was: "what would you put in that?"
Is it supposed to be =
Or perhaps ==
oh yes
https://i.gyazo.com/3ba37266795c4bf2b04a06f3ca1a9bdc.gif
My car is now doing this, code: https://gdl.space/uqubuwefip.cs
Anyone know why it isn't moving or anything?
What I think you asking about is constructor overloads? In that case, no, you can't make a list of them
I don't know the whole story(since it wouldn't load in my discord for some reason), but I think you have a common misunderstanding about how code works. Unless you are dealing with delegates, you can't add an executable code to a list. Instead, the constructor(as any method) is executed, returns an instance(or a reference to it depending on the type) of the type and then the instance is added to the list.
Maybe explain better what's going on, as all I see is a car falling down from the sky.
Show the inspector for that script. Maybe motorPower is 0 or something
It's 1000
I had to take the model out for changing mesh origins so it rotated properly
now it's not moving
Looking at the script, you only apply torque to the front wheels, and they're also rotated in a weird angle.
Apply torque to the rear wheels as well
Aside from that, if it's still not moving, I'd guess it's something about your setup in the inspector/hierarchy and not the code.
I think the tilting of the wheels is the 'steering angle' but I could be wrong
you didn't set up your vehicle correctly. use a template and observe it carefully there.
Unity has a decent tutorial on this too
https://docs.unity3d.com/Manual/WheelColliderTutorial.html
it's best to start with a pre-existing correctly rigged vehicle
there's nothing wrong in the inspector. your hierarchy is wrong
{
oldItem = currentEquipment[slotIndex];
onEquipmentChanged?.Invoke(null, oldItem);
}```
I added this now I get the debug message but still no modifiers
there are lots of little details. use the free edy vehicle physics asset for this
the transforms of the wheels and/or wheel colliders are wrong
start with a pre-existing prefab
CurrentEquipment is null to be able to get into that code, so setting oldItem to it makes no sense
how so?
trying to rig a vehicle with the unity standard assets will involve reinventing all the stuff that's in the free EVP package
figuring that out is longer and harder than starting with a correctly rigged vehicle and observing carefully what the transforms are
it's arbitrary
it's like asking why do animals have five fingers
and not four or six. it's just arbitrary.
Are you sure that the car's collider is not touching the ground?
Maybe suspension is adjusted wrong
like i don't know off the top of my head. i don't remember if wheel colliders rotate about x, y or z. i think it's x. then your wheel transforms will be wrong relative to that.
the suspension is tricky too. you need the exactly correct resting position
study a pre-existing prefab
you're assuming that the car's hiearchy is correct for rigging. it's not
anyway you will figure this out
Also what is the mass of the rigidbody
So what should I exactly do if you know, my brain stopped working at this hour of night
1500
The wheels are not colliding with the ground
I adjusted the collider and moved it up and it goes straight there
Huh
the mass is 1500
Go to sleep and come back tomorrow 🤷♂️
You need to add things to CurrentEquipment and use an index with a non-null value
Find where you add equipment and make sure it's happening properly
Okay yeah that's what the unity page suggests, nevermind
Have you looked at the car while playing? Can you screenshot it after it has fallen on the ground?
In your GIF it really looks like the suspension is not stiff enough
You can enter scene view while the game is playing and inspect it there
I have found the exact while loop that can hang unity after this function is called many many times, https://paste.ofcode.org/gCHfztBHcdyrRPkEPfDdfX
can anyone tell why this would cause unity to hang? Or a way to abort it if it causes a hang?
Seems like openSet.Add gets called more than openSet.Remove 🤷♂️
Hanging means you're either in an infinite loop or an extremely long loop. quite probably your code has a logical error in it
Enable Gizmos and/or expand the wheel collider's inspector
They were on but they just disappeared
Hello guys do any of you know what would be the best way to get realistic movement and some help on how to do it I'm still pretty bad at coding and haven't got my roots down quite yet
For an realistic FPS
get your roots down first
Making your own FPS movement controller is very complex
Maybe use some asset meanwhile
For example the character controller for Apex legends probably took several professional game developers a few months to perfect. It's not something you just do before you really even know how to write code yet.
Yeah the people at Respawn are genius. Titanfall is so smooth
I know things like functions transform RigidBody I just don't really know how to use them to a good degree quite yet, But yeah I will
I know Ive been trying to fix it. I didnt write this function so Im not sure exactly what breaks it but whatever it is is really small because I have to run the function thousands of times before it has the chance to cause a hang
It wouldn't be about how many times you run it. It would be some characteristic of the graph you are feeding it that causes it
for example maybe there's a cycle in the graph and your code doesn't know how to handle that.
Problem with that tho I don't have any money
it would help if you understood the A* algorithm, which is essentially a modified DFS
why do you need money?
Learning programming is free
Ohhhh I thought Asset store
what do you mean by cycle? it seems like it just goes through a grid of inherently different points 1 by 1, do you mean it has the chance to loop through several points that it isnt supposed to?
a cycle is a series of connected nodes in the graph that form.. a cycle. For example A -> C -> A
if you keep following that path, you'll go forever unless you detect the cycle somehow
I've been looking for a good way to make a 3d mesh heightmap object from a csv file of heights, could anyone point me in the right direction? I havent been able to find much information that doesn't use terrains, which is not what I am looking for. Any help would be great thanks!
There are free assets on the store (like the great Kinematic Character Controller), but those still require the understanding and ability to implement them.
I'm sure there are plug and play ones, but I don't know them
I put in the total amount of accessible points the graph has detected and do that count-- for each pass in the loop so shouldnt that prevent that? it isnt stopping it somehow
The use of terrains and generating a mesh are extremely similar. You'll have to be familiar with how meshes are structured and creating procedural meshes to create a mesh though
I'm not sure what that means. The typical approach is to maintain a set of "visited" nodes, and never process a node that has already been visited.
Nothing specific to CSV here but I like these text tutorials
https://catlikecoding.com/unity/tutorials/procedural-meshes/
thanks both of you :)
@uncut mantle Praetor is right, I think you are missing a 'closedSet' to check if a node was already visited
Im adding it now, let me see if it works
You can use a HashSet for faster Contains than with List
I dont think it even works, I added visitedPoints and made it so points cant get added if theyve ever been checked on before but it still hangs.
Should probably check also if openSet contains the value before adding it
(Second screenshot)
huh thats interesting let me see, would have never thought of that
unfortunately its still hanging :/
You could make it into a coroutine or async and visualize it, see where it goes wrong
good idea let me write that
Or if you end up rewriting the A*, this is a decent video tutorial series
https://www.youtube.com/watch?v=-L-WgKMFuhE
What are Heapify and HeapifyDeletion? 🤔
Im not sure the video I got it from went over all of his code extremely briefly unfortunately, I swore that he explained it in the video but I cant find it, heres the video if youre curious https://youtu.be/p3WcsO6pAmU?si=3xXtcKWwPu9SfEXt&t=179
heres the heapify functions, I remember him explaining that it was a way to streamline checking through the coordinates to make it more efficient
An custom pathfinding experiment tried.
Support me on Patreon: https://www.patreon.com/abitofgamedev
Follow me on Twitter: https://twitter.com/steffonne
Follow me on Instagram: https://www.instagram.com/abitofgamedev/
Download the project: https://github.com/abitofgamedev/pathfinding
#unity #programming #algorithm #tutorial #projectile #coding...
Heapify is recursive... That could be the reason it hangs
Both are recursive*
oh earlier I ran it without the heapify function and it still hung, I must have missed that heapify deletion also called itself, let me try running it without both of them
it still hung wow
I suggest going through the tutorial again. I took a quick peek and in the tutorial he also had this check
Which you didn't have -> makes me think you missed something else too.
grabbed his code from github I didnt write it
And if you want an actual A* explanation + implementation then check this out ^
a lot of his code changed from the video to the github updates, he removed it himself for some reason
My game involves a character climbing a tower by going around it in a spiral staircase. The camera is in a fixed isometric position, but I want to make it rotate around the tower to follow the player while staying at the angle it is. This is the code I used, but it's not working as I want it to (it restricts the character from straying too far from the tower). What would be a better option? (The script is on the camera btw)
2 ways you can do that
- Use a "camera boom", basically position the parent object of the camera in the middle of the tower, then offset the camera and just rotate the parent
- Use the LookAt function
I'll try those, thank you!
in the current script neighbor is a point variable and neighbordata is a pointdata variable so he changed how he iterates through openset
can somebody tell me why this results in the SelectCharacter function always being called with i = the number of items in the characters list? When printing i, it iterates from 0 to characters.Count - 1 as it should.
void Start() {
List<Character> characters;
GameObject charGO;
CharacterItem charItem;
Button charItemButton;
for (int i = 0; i < characters.Count; i++)
{
charGO = Instantiate(characterItemPrefab, charactersPanel);
charItem = charGO.GetComponent<CharacterItem>();
charItemButton = charGO.GetComponent<Button>();
charItem.Setup(characters[i]);
charItemButton.onClick.AddListener(() =>
{
SelectCharacter(i);
});
}
}
Also when I add/remove an item to the characters list and start the game, i get the error
NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
Is this during play mode? Remember that wheel colliders belong to the rb and would move with it. Can you select the rb/vehicle collider and see if it's in place?
yep, typical lambda variable capture
what does that mean? sorry :')
thanks much, that helps a lot :D
Everytime I restart Unity it turns Player Projects off which makes Visual Studio Work Properly anyone know how to set it to be automatically on?
I don't think that checkbox affects anything aside from when regenerating the project files
Huh, I've only EVER had the top two checked, and my vs is fine
That's a lot of project files
Visual Studio will work but the colors or the reccomendations wont work
Yes they will normally.
Does it really not for you? That is not normal
My vs has correct colors, autocomplete, error underlining, all of it
You can see the !ide guide, which doesn't have all of it checked
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
These are what it looks like on and off
Did you regerate it with it off? I would uncheck all but the top two and click regenerate, then restart your computer, then see what happens
Tried that and it didnt work
What other options do you have in the external script editor drop-down?
Does that reset when reopening the project?
no
Okay, so it means that your project files get regenerated on opening the project.
Try deleting the .csproj and .sln files in the project and reopening it again .
Hey guys, this is an issue with 2020.3.19f1, I'm stuck on that version because it's a mod I'm building.
I have a bit of JSON data I'm trying to send with UnityWebRequest
using (UnityWebRequest www = UnityWebRequest.Post("http://localhost:5000/playerRanks", form))```
but no data is received by the server at all
it receives the request and responds to it correctly, but there is no data in the body
there is no data in the body
Why do you say it responds correctly then?
there is no data in the body of the response? Or the request?
there's no data in the body of the request, Unity receives the json response just fine
also why is your data called "form" if it's json?
I would guess you likely haven't encoded your data properly
You probably haven't set the mime type/content type
For example: https://forum.unity.com/threads/posting-raw-json-into-unitywebrequest.397871/#post-2888237
is JsonConvert preferred over JsonUtility?
doesn't matter/isn't relevant to the problem at hand
if you are getting the correct json string with whatever you're using it's fine
ok, I'm going to sub in
string playerDataJson = JsonUtility.ToJson(playerData);
to what package does "GetBytes" belong?
I presume they mean Encoding.UTF8.GetBytes
No, I just remembered, JsonUtility doesn't want to convert my particular list to a string
that's a completely separate issue
sounds like either:
- you're trying to serialize a naked list (unsupported by JsonUtility)
- your list is not public or [SerializeField]
- The type in the list is not serializable
Let me just say that I do have the correct JSON representation of the list, generated dynamically on run, so might as well use that
[{"name":"CPU 1","rank":0,"side":"","fleet":"","cost":""},{"name":"AirmanEpic","rank":3750,"side":"","fleet":"","cost":""}]
foreach(playerData player in playerData){
basicJSON += JsonUtility.ToJson(player)+",";
}
//delete the last comma
basicJSON = basicJSON.Remove(basicJSON.Length - 1);
basicJSON += "]";```
Yeah JsonUtility won't be able to create that because it doesn't support naked lists/arrays
great.