#archived-code-general

1 messages · Page 221 of 1

heady iris
#

the first bullet behaves differently than the rest

#

tbh if it's a fixed pattern, just make an array of 5 floats

lean sail
#

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.

heady iris
#

it'll be more obvious what it does than a weird morass of % and other operators

#

jinx

dusky lake
leaden ice
#

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);
}```
heady iris
#

Okay, so it's that pattern, expanding forever

leaden ice
#

I think this would work

lean sail
#

then yea you'll just need to check if i is an odd number, increase the rotation if so

leaden ice
#

it would be (+0, -5, +10, -15)... wait maybe it's a bit off 😉

heady iris
#

In that case, I would do this

dusky lake
leaden ice
heady iris
#
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.

visual cove
#

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);
        }
    }
}
leaden ice
#

should work fine

dusky lake
visual cove
heady iris
#

Rather than a compile error.

lean sail
visual cove
#

nope, occurs in-editor after button press

#

its an EditorWindow type

heady iris
#

and what is the error?

#

we also have no idea what lines 29 and 41 are

visual cove
#

NullReferenceException: Object reference not set to an instance of an object

visual cove
rigid island
visual cove
rigid island
#

the lists are probably not initialized ?

#

you didn't show the whole script so im just guessing lol

#

in HandPose prob

visual cove
#

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

celest iron
#

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.

somber nacelle
#

if you just want something quick and easy that just outputs an int you can just use GetHashCode

celest iron
#

Saddly that does not guarantee unique seeds

somber nacelle
#

nothing that uses an integer does

celest iron
#

For example, with InputFields, it gives the same hashcode for different strings

lean sail
#

nothing will guarantee unique seeds, collisions are a part of hashing

celest iron
#

9 different strings, gave the same hashcode

lean sail
#

you could use md5 hash

rigid island
#

would MurmurHash work?

knotty sun
celest iron
#

I can try

celest iron
#

ty

#

How does that work, tho? You can just add chars with ints??

#

never knew that

lean sail
somber nacelle
celest iron
#

I knew they had the ASCII code, but never thought about adding them with ints

#

Cool

atomic sinew
#

What is the best practice for cycling through menu buttons in the UI?
Do you write a custom navigation system?

leaden ice
austere cape
#

hey guys does anyone know course or code source of a game like this and the 2d motorcycle physiques

rigid island
#

the line rider thing

austere cape
rigid island
#

you want too specific

#

you have to buld it

#

"physics like this" idk what that even means

spring creek
austere cape
#

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

spring creek
#

oh, you mean like do a wheelie "state" where it rigidly stays in a wheelie position?

rigid island
atomic sinew
#

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

leaden ice
#

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

atomic sinew
hard viper
#

is there a way to write an int property that allows public get, and public ++, and public -- only?

knotty sun
#

yes

hard viper
#

Is this the right way? I'm not sure if there is a smarter way than just having the setter assert it

knotty sun
#

perfect only I would have thrown an exception

hard viper
#

I assume it will simplify in final build, because I thought Build removes UnityEngine.Debug. lines

knotty sun
#

As long as you test completely, ok

leaden ice
hard viper
#

is there a way of baking that into a property, instead of makng it a method for the whole class?

leaden ice
#

make a class and use it as a property

#

or struct but you have to be careful with that

hard viper
#

I feel like that might add more parts, while being safer

#

ty for the input, guys

lapis nexus
#

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?

dusky lake
#

Modding is not supported here

#

if you want mod support please ask in the discord of that game

rigid island
hard viper
#

I think modding and his question are kind of separate

rigid island
#

then there is nothing special of adding animation to animator and can be easily googled

lapis nexus
hard viper
#

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

rigid island
hard viper
#

really?

#

an animator is basically a Finite state machine.

#

You want to modify this finite state machine

rigid island
#

well you could only override actually iirc not add new ones

lapis nexus
hard viper
#

What is the cleanest way to patch a reference type between two variables without making a new hard copy?

rigid island
#

thats why we dont discuss modded games

#

its specific to that mod

hard viper
#

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

lapis nexus
rigid island
#

it all depends how the parameters are setup 🤷‍♂️

#

you could use animator.Play i suppose with specific clip names

hard viper
lapis nexus
hard viper
#

yes. ref type

#

can I just do: B = A; A = new ContactState();?

somber nacelle
#

yes

simple egret
#

Yup

hard viper
#

great. I always remember the whole reference frame aliasing thing being a watch out

simple egret
#

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

hard viper
#

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

valid trench
#

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.

hidden parrot
#

Animator rotation values are local

#

You can parent the animated sword to another object

#

Then rotate that object towards the mouse

valid trench
#

oh that is a good idea

#

thank you

hidden parrot
#

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

hexed pecan
#

Yeah you could normalize the positions into a 0..1 range for instance

#

And have your presets in that 0..1 range

hidden parrot
#

So scale the one the player drew up/down then distance check?

hexed pecan
#

Yeah fit it to the same size as the preset spells.

hidden parrot
#

Can try that.

hexed pecan
#

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

hidden parrot
valid trench
hidden parrot
#

Animator.speed

valid trench
#

ty

inner yarrow
#

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?
hexed pecan
#

I'm not seeing any rotation code, do you mean position?

#

Like orbit around a point?

delicate garden
#

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;
    }
spring creek
#

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

cosmic rain
hexed pecan
#

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

hard viper
#

man, idk how to encapsulate better, now that I learned internal actually works

hexed pecan
#

VSCode often gives me internal when refactoring

hard viper
#

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

cosmic rain
#

Internal is like private between assemblies

#

Just use private.

hard viper
#

I get that, but I've been working with just one assembly for my whole project

hexed pecan
hard viper
#

yes

hexed pecan
#

Me wants

hard viper
#

that is exactly the friend keyword

cosmic rain
hard viper
#

yes, but I can't use private, because that blocks access

cosmic rain
#

Friend gives you access to private fields of another class afaik

#

Internal doesn't do that.

hard viper
#

I just want to be able to mark specific things as accessible to another class

hexed pecan
#

Oh yeah I meant the behaviour that loup wants, not internal itself

hard viper
#

but only a specific other class to not expose more than needed

cosmic rain
hard viper
#

how

cosmic rain
#

Just define it in the scope of the class

hard viper
#

explain

cosmic rain
#
public class A
{
    public class B
    {
    }
}
hard viper
#

and how do I define a method in B accessible only to A and B

cosmic rain
#

Just define it normally in B

hard viper
#

with a private access modifier?

cosmic rain
#

You can't access class A from outside unless you do A.B

cosmic rain
hard viper
#

but then I could do:
A a = new A();
a.b.MethodInB();

cosmic rain
#

I think you can also make the B class private

cosmic rain
hard viper
#

ok, well that's exactly not what 'm looking for

cosmic rain
#

Unless b is a public field.

cosmic rain
hard viper
#

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

cosmic rain
#

Create a separate class/struct for whatever you want to only expose to A and only expose it🤷‍♂️

hard viper
#

Great

#

except that method I only want to expose specifically modifies private fields in B

steady moat
#

In theory, you can use internal and assembly.

#

However, I do no think it is really appropriate.

hard viper
#

I don't think it's right either

#

but how do I just encapsulate it better? We don't even have the file keyword

cosmic rain
hard viper
#

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

cosmic rain
#

It's not really encapsulation

#

It's kind of an inconsistent thing you want

hard viper
#

how is it not encapsulation to restrict access to methods

steady moat
#

Also, the friend keyword is an antipattern.

#

It is usually bad practice

hexed pecan
#

Handy things are usually bad practice

cosmic rain
#

You can achieve that with nested class and private access

hard viper
#

it's not a GOTO flag. we'll live

steady moat
#

The same argument could be made for the goto instruction

#

The issue is that it creates bad architectural design

hexed pecan
#

The one usecase I keep finding for goto is breaking out of nested loops. But I still avoid it because it's non-standard

delicate garden
steady moat
hexed pecan
#

Yeah, usually just need break + a bool or something to break out of the outer loop

steady moat
#

You can also use two condition in the loop.

hexed pecan
#

That's true, I think I overlook that often

steady moat
#

for(int i =0; i < count && isRunning; ++i)

#

(In some scenario)

cosmic rain
#

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.

inner yarrow
# hexed pecan I'm not seeing any rotation code, do you mean position?

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.

loud wharf
#

@hard viper @cosmic rain Yo can u guys do a summary of what u guys were talking about? UnityChanSleepy

silver iris
#

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

hard viper
loud wharf
#

Hmmm, internal is the closest equivalent? UnityChanThink

#

But u guys alr talked about that.

loud wharf
# hard viper and how do I define a method in B accessible only to A and B

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?". UnityChanThink

loud wharf
#

That's the only way i can think of tho. UnityChanThink

#

You can't make method in B private or protected because that will make A unable to access it.

hard viper
#

it would just be nice to have an attribute to specifically expose to a given class

sharp skiff
#

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.

leaden ice
#

so it's fighting against the other

#

what you need is one centralized place to control the camera zoom

sharp skiff
#

@leaden ice You know I never thought of that... good point.

loud wharf
#

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. UnityChanThink

#

Considering you can just make assembly references.

indigo pasture
#

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;
    }
cosmic rain
#

There's probably something wrong with your setup

indigo pasture
#

Not sure what it'd be

cosmic rain
#

Like wheel colliders being parented to the visual wheels

indigo pasture
cosmic rain
#

Or having some weird offset on some of the children

loud wharf
indigo pasture
cosmic rain
#

Might want to record that video again, but with all the gizmos enabled and visible. Especially the wheel colliders ones

indigo pasture
#

how do I enable those in game again?

cosmic rain
#

On the top right of the game view there's the gizmos tab.

indigo pasture
#

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

cosmic rain
#

Lol wtf

#

Is it a three-wheeler?😅

indigo pasture
#

it's one mesh

cosmic rain
#

Why is it one mesh?

indigo pasture
#

I couldn't tell you

cosmic rain
#

Is it also 1 wheel collider?

indigo pasture
#

yes

cosmic rain
#

Well, that's not gonna work.

indigo pasture
#

even as I add that, it doesn't fix the issue

cosmic rain
#

Take a screenshot of your wheel meshes transform and wheel colliders transform.

loud wharf
#

I like those wheels.

jade valve
#

!cs

tawny elkBOT
delicate garden
#

hey, what would be the easiest way to check for any numbered input?

#

(1-9)

lean sail
#

What is this input though? Tmp input field should have an option to only allow numbers

delicate garden
#

checking if any of them are being pressed

lean sail
delicate garden
#

It can't be checking every individual key, that sounds really inefficient

fervent furnace
#

loop from alpha1 to alpha9, and check alpha0 (it may be mapped to 10)

paper mirage
#

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)

fervent furnace
#

find the reference to that component in editor and find any GetComponent<MeshRenderer>()

paper mirage
#

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.

knotty sun
delicate garden
#

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;
    }
bronze crystal
#

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?

untold siren
#

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?

knotty sun
untold siren
#

using 2022.3.0

knotty sun
#

definitely not a good version to be using

untold siren
#

well that's reassuring OMEGALUL if it was me I'd be using either LTS or a newer version

knotty sun
#

Always the latest LTS unless there is a really, really good reason not to

untold siren
#

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

knotty sun
#

yes, and something else is checking for an attribute it does not have

untold siren
#

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

knotty sun
#

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

untold siren
#

only updates available are for VCS and timeline, don't think they'd be relevant to the issue peepoDetective

knotty sun
#

yes, but it could be that the updates are not available because this is an old Unity version

untold siren
# cosmic rain 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

untold siren
cosmic rain
knotty sun
#

CameraSwitcher is your own class?

untold siren
knotty sun
#

why is it in the Camera namespace?

untold siren
#

its just the folder name

#

it wouldn't be directly being the UnityEngine.Camera

#

its just standalone

knotty sun
#

change the namespace, I think by using Camera you've confused Unity

untold siren
cosmic rain
#

I'm not sure about it. But worth a try.
I'd like to see the error details though.

cosmic rain
untold siren
untold siren
cosmic rain
# untold siren

Hmm... Are you using it with GetComponent or something like that anywhere?

knotty sun
#

Can you change CameraSwitcher to something else?

untold siren
# cosmic rain Hmm... Are you using it with GetComponent or something like that anywhere?

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();
            }
}
untold siren
knotty sun
#

yes

untold siren
#

give me two secs I'll give it a go

#

what the fuck

#

how does it work now OMEGALUL

#

wait a min

#

premature celebration

knotty sun
#

there was obviously a name conflict

untold siren
#

unity didn't compile the changes so I thought it was fine

#

but nah

knotty sun
#

so not. hmm

untold siren
#

this is so goofy

knotty sun
#

but no stack trace?

untold siren
#

no stack trace whatsoever

#

I can try finding one via rider in debug mode but idk if that'll get anywhere

knotty sun
#

I doubt coz I dont think it's in your code

#

why did you switch the namespace back to Camera

untold siren
#

because the change to another namespace didn't fix it

knotty sun
#

it's a combination of changes. Change it again

cosmic rain
cosmic rain
#

Also share the whole file code

untold siren
untold siren
cosmic rain
#

Wait, it had a different name

untold siren
#

ohhh

cosmic rain
#

Did you rename it?

untold siren
#

what part

#

nah the class is defined within mainCamera.cs

cosmic rain
#

Camera.CameraChanger

untold siren
#

that's within mainCamera

cosmic rain
#

Share the mainCamera.cs

#

!code

tawny elkBOT
untold siren
#

two secs

#

bear in mind too that this has been working 100% successfully up until today

knotty sun
#

what happens if you just add the attribute to the class?

untold siren
#

what attribute

knotty sun
#

the one it says is missing

untold siren
#

doesn't exist

knotty sun
#

Attribute not inheritance

untold siren
#

oh mb

#

how would I do that

knotty sun
#

[ExtensionOfNativeClass] above the class declaration

untold siren
#

with a 1 it reports an error

knotty sun
#

no 1 in the error message

untold siren
#

this is such a goofy error

cosmic rain
#

I think the issue might be with your extension methods and using coroutines.🤔

#

Does the error disappear if you comment out the code?

untold siren
#

shouldn't be, like I said - has worked on every pc up until now

cosmic rain
#

Inside methods.

untold siren
#

with the coroutines commented out still no worky

#

same error message

knotty sun
untold siren
#

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

cosmic rain
#

Indeed. Didn't notice.

untold siren
#

might just rewrite a lot more of my code than I originally anticipated to get around this issue

delicate garden
knotty sun
cosmic rain
bronze crystal
#

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;
    }```
leaden ice
outer flicker
#

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.

untold siren
bronze crystal
knotty sun
untold siren
#

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

knotty sun
#

no, not if that version is not supported

untold siren
#

I can check the package manifest at least and compare the versions

#

they're both identical

leaden ice
untold siren
#

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

swift falcon
#
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?

knotty sun
wide mural
#

Any suggestion of best way to incorporate a point and click dialogue system for a game?

dusky lake
#

As a good starting point

short saffron
#

fungus

noble field
#

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

noble field
#

there's a solid spacing in time between each post

#

I'm trying to get a reply somewhere, sorry again

knotty sun
#

4 minutes is not 'solid spacing'

noble field
swift falcon
somber tapir
swift falcon
#

Or would it? Correct me if I'm wrong

somber tapir
#

no it wouldn't

swift falcon
#

Yeah, so what do I do?

bronze crystal
#

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;

rigid island
bronze crystal
#

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

bronze crystal
#

thats something you would create later in the inspector

knotty sun
#

you have not even declared a variable so how could it be filled?

somber tapir
bronze crystal
#

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;

knotty sun
#

so why are you trying to access it with playerdata?

bronze crystal
#

vendor will check if you have the right currency

#

and then give you the sellingitem

bronze crystal
swift falcon
#

player.playerData.sellingItem += itemAmount;

bronze crystal
rigid island
swift falcon
# bronze crystal doesnt work

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

somber tapir
livid olive
swift falcon
rigid island
#

yup

hexed pecan
livid olive
#

For items you want to make...

swift falcon
#

Can you elaborate?

livid olive
#

its range is -1 to 1

hexed pecan
livid olive
hexed pecan
#

Mouse input is not clamped to -1..1

#

You are thinking of GetAxisRaw or something

swift falcon
livid olive
#

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.

hexed pecan
#

The amount depends on how much you moved your mouse, if that wasnt obvious

hexed pecan
# swift falcon ```cs var amount = Input.GetAxis("Mouse X"); transform.RotateAround(obj.positio...

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

hard viper
#

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

hexed pecan
hard viper
#

really? that is not what I would expect

hexed pecan
#

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

somber tapir
#

anybody know if these things exist in code as enums or something similar?

swift falcon
livid olive
swift falcon
hexed pecan
swift falcon
#

I feel so stupid now

carmine ridge
swift falcon
#

Oh god, using RotateAround wasn't even necessary

#

I'm a chronic idiot

rigid island
#

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

hexed pecan
#

And then applying that "velocity" to the bodypart's rigidbody when activating ragdoll

#

All this in world space

rigid island
#

are you just keeping track of positions and not rotations ?

hexed pecan
rigid island
#

Ahh like that

hexed pecan
#

Then when activating the ragdoll you could add a force that is currentPos - lastPos

hexed pecan
#

As a bonus you can do it with rotations + torque too, but I didn't bother myself, position looked good enough

rigid island
#

oh yeah thats a good idea i might try that too

#

does it matter that my RB start kinematic ?

hexed pecan
#

Probably not, as long as you make them non-kinematic before adding the force

rigid island
#

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;

hexed pecan
#

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

rigid island
#

its strange I thought animator would keep track of the whole avatar/limb positions or something

hexed pecan
#

I don't think it has any idea what happened last frame

#

It doesn't really need to know about it

rigid island
#

true

hexed pecan
#

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

rigid island
#

good idea Ill put that one after

hard viper
#

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

hexed pecan
#

Like having a different start and end rotation for the shape?

#

Nothing that I know of, though you could try doing it in steps

hard viper
#

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?

rigid island
rigid island
bronze crystal
#

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

hexed pecan
rigid island
#

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);
        }```
hexed pecan
#

nvm wait

rigid island
#

was about to say it does that lol

bronze crystal
hexed pecan
rigid island
#

will do

rigid island
hexed pecan
#

Would be less messy if the ray wasnt 100 long lol

rigid island
#

true lol

hexed pecan
#

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

rigid island
#

direction seems ok

#

but i tried 10 because it wouldn't addforce or barely

#

it still doesnt it just flops down 😦

hexed pecan
#

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

rigid island
hexed pecan
#

Yeah

rigid island
hexed pecan
#

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

rigid island
#

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

hexed pecan
#

Actually yeah I think you gotta multiply with 1f / Time.deltaTime 🤔

hexed pecan
rigid island
hexed pecan
#

Not sure, maybe Time.deltaTime goes crazy

rigid island
#

lol

#

it only happens when you frame by frame before transition to ragdoll and not after

#

nvidia physics is weird af mann

hexed pecan
#

I also suggest adding a slow-mo button/hotkey to your game that just sets timescale to like 0.1

#

Helps with debugging stuff

rigid island
#

good idea!

rigid island
#

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 :\

hexed pecan
#

It does seem to freeze for at least 1 frame

rigid island
#

yeah it like implodes on its own limbs

#

and then catches up

hexed pecan
#

Did you use unity's own ragdoll thing?

rigid island
#

yup

#

it might be the limbs intersecting

hexed pecan
#

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

#

And upping your iteration count in physics settings

#

A lot of trial & error goes into this stuff

rigid island
#

yeah it seems so, I have to play around with some settings
thank you for link as well this looks promising

hexed pecan
rigid island
#

yeah not as noticeable

hexed pecan
#

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

rigid island
#

enabled it but still does the same, its just not as bell

rigid island
hexed pecan
#

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

rigid island
#

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

hexed pecan
#

Yeah fix the colliders first. Also try disabling collisions in each joint settings

#

@rigid island make a thread so we dont flood?

rigid island
#

oh yeah you right myb

#

Ragdoll Transition Smoothness

hard viper
#

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?

leaden ice
#

yes

hard viper
#

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

leaden ice
#

No rotation is probably a dealbreaker for most people

#

as is the lack of non-box shapes

hard viper
#

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

knotty sun
# hard viper 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

hard viper
#

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

knotty sun
#

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

hard viper
#

I would need to think more about multi threading. The most expensive operation right now is getting contacts, which can be multi-threaded easily.

knotty sun
#

multi threading is where a own built system will win hands down over Unitys pedestrian system every day

hard viper
#

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

knotty sun
#

time to experiment and learn, its not that hard, honest

hard viper
#

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

knotty sun
#

yep, I understand, visualizing multi threading/multi tasking can be a royal pain in the arse and generate lots of headaches

hard viper
#

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

knotty sun
#

that would be a good start and pay big bonuses

hard viper
#

that’s probably as easy as it gets tbh

#

what is the best system to learn for multi threading? jobs?

knotty sun
#

nah, just microsoft learn, this is pure c# and Unity just unnecessarily complicate things with DOTS/ECS

hard viper
#

which is the right system to learn then?

knotty sun
#

just standard C# Threads and Tasks

hard viper
#

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) {}
knotty sun
#

not really, no

leaden ice
#

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

hard viper
#

i figured the end needs some work

#

what do I do then?

knotty sun
#

you could do

foreach (x in IEnumerable) {
Thread th = new Thread(ExpensiveFunction);
th.Start(x);
}
leaden ice
#

(there's also Task.Run)

hard viper
#

that makes sense to me too. but I also want to make sure everything is done before I continue main thread

knotty sun
#

lots of options, that's why I said experiment and learn

somber nacelle
knotty sun
hard viper
#

i think I’ll dip my toes in it to give it a shot and learn

knotty sun
#

it will repay you 100 fold

leaden ice
#

Once you learn these concepts it will be much easier to dip into the Job system too

hard viper
#

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

fervent furnace
#

course on OS should teach threading in general

hard viper
#

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

knotty sun
hard viper
#

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

knotty sun
#

as I said it can become very difficult to visualize, race conditions abound

hard viper
#

my plan is to ride the bunny slopes and say I skiid at least once in my life, steve

knotty sun
#

lol

#

btw System.Collections.Concurrent is your friend

uncut mantle
#

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.

rigid island
#

RAM use will go up until you crash

#

End Task

uncut mantle
# rigid island looks like infinite loop or something

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

rigid island
#

you can share the script if you want

#

!code

tawny elkBOT
uncut mantle
#

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

spring creek
uncut mantle
#

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

#

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

lilac pilot
#

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.

latent latch
#

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.

lilac pilot
#

It's because of the minimum and maximum points.
But can I use more than two dots, like 4, 8?

bronze crystal
hard viper
#

!code

tawny elkBOT
latent latch
# lilac pilot

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)

hard viper
#

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

hardy current
#

how would one add velocity to a kinematic Rigidbody?

woven matrix
#

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

hard viper
#

!code

tawny elkBOT
hard viper
#

you would need to call MovePosition every frame to advance

simple egret
# bronze crystal 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.

wind needle
#

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?

hard viper
#

i would use a class in the middle

lean sail
hard viper
#

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

wind needle
#

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.

hard viper
#

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

tiny jasper
lean sail
wind needle
#

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...

simple egret
#

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

dense rock
#

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?

delicate ibex
#

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:

lean sail
# dense rock I'm making a multiplayer game with photon pun 2, what would be the best way to s...

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

dense rock
#

thanks much :)

indigo pasture
pulsar holly
simple egret
#

This is pretty much unreadable

pulsar holly
#

How so?

somber nacelle
#

does your tab key not work?

simple egret
#

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

knotty sun
pulsar holly
#

Is this better?

simple egret
#

It's the same as before

pulsar holly
#

Well I formatted it.

simple egret
#

No

knotty sun
pulsar holly
simple egret
#

For reference, this would be your Start method, formatted:

void Start()
{
    if (transform.position.y == 5.5)
    {
        (set == set + 1);
        (preSet == preSet + 1);
    }
}
pulsar holly
#

What did I do to get the first strike?

simple egret
#

Lots of errors in it, but at least it looks good

knotty sun
pulsar holly
#

Block?

hexed pecan
simple egret
#

Steve's power trips, you can ignore
Only moderators can inflict strikes

#

Anyway, format your code correctly and post it again

hexed pecan
indigo pasture
pulsar holly
somber nacelle
#

lol you barely changed anything

simple egret
#

Mate just use the tools your code editor gives you

somber nacelle
#

but lines 12 and 13 are not valid

lean sail
#

your IDE will auto format this for you, is your IDE even configured though?

pulsar holly
hexed pecan
#

What code editor are you using?

pulsar holly
simple egret
hexed pecan
simple egret
#

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.

hexed pecan
# indigo pasture

Show inspectors of the wheel and its children, what object has what component etc.

pulsar holly
#

This should work

simple egret
#

Okay looks better now. Lines 13 and 14 are not valid

indigo pasture
pulsar holly
simple egret
#

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

hexed pecan
indigo pasture
lean sail
hexed pecan
#

Yeah probably imported from blender, there's a ~90 degree difference on X axis

pulsar holly
simple egret
#

This is your first error, did you change anything at all?

#

The CS0201

pulsar holly
#

Yes, I changed the == to =

simple egret
#

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

pulsar holly
#

The error is gone

hard viper
#

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

dim umbra
#

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

spring creek
stark sun
spring creek
stark sun
#

now it does not say Equipment Changed

spring creek
# stark sun 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

high condor
#

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?

spring creek
#

You can put the constructed instances in a list

#

Is that what you mean?

high condor
#

How would I create the list?

spring creek
#

List<Person> myList = new();

high condor
#

But don't I have to make the list before I can create constructors?

spring creek
#

myList.Add(new Person("John", 18));

stark sun
high condor
#

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

spring creek
spring creek
hexed pecan
high condor
#

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?

spring creek
stark sun
# spring creek What would you do in that?

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

spring creek
high condor
#

Maybe I'm using the wrong terms, sorry. But imma leave if you're gonna talk like that :/

spring creek
stark sun
spring creek
hexed pecan
#

Or perhaps ==

stark sun
indigo pasture
spring creek
cosmic rain
# high condor Idk where you got "Well the list obviously couldn't be in the Person class...." ...

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.

cosmic rain
hexed pecan
indigo pasture
#

It's 1000

#

I had to take the model out for changing mesh origins so it rotated properly

#

now it's not moving

cosmic rain
#

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.

hexed pecan
polar marten
hexed pecan
polar marten
#

it's best to start with a pre-existing correctly rigged vehicle

indigo pasture
#

thats what I followed

#

and it was working, ish

polar marten
#

there's nothing wrong in the inspector. your hierarchy is wrong

stark sun
indigo pasture
polar marten
#

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

spring creek
polar marten
#

trying to rig a vehicle with the unity standard assets will involve reinventing all the stuff that's in the free EVP package

polar marten
# indigo pasture how so?

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.

hexed pecan
#

Maybe suspension is adjusted wrong

polar marten
#

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

indigo pasture
polar marten
#

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

hexed pecan
#

Also what is the mass of the rigidbody

stark sun
indigo pasture
#

1500

#

The wheels are not colliding with the ground

#

I adjusted the collider and moved it up and it goes straight there

hexed pecan
indigo pasture
#

the mass is 1500

spring creek
hexed pecan
#

Okay yeah that's what the unity page suggests, nevermind

hexed pecan
#

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

uncut mantle
#

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?

hexed pecan
#

Seems like openSet.Add gets called more than openSet.Remove 🤷‍♂️

indigo pasture
#

now I can't see the wheel colliders

#

:/

leaden ice
hexed pecan
indigo pasture
#

They were on but they just disappeared

jaunty ore
#

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

hexed pecan
#

Making your own FPS movement controller is very complex

#

Maybe use some asset meanwhile

leaden ice
#

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.

hexed pecan
#

Yeah the people at Respawn are genius. Titanfall is so smooth

jaunty ore
indigo pasture
uncut mantle
leaden ice
#

for example maybe there's a cycle in the graph and your code doesn't know how to handle that.

jaunty ore
leaden ice
#

it would help if you understood the A* algorithm, which is essentially a modified DFS

leaden ice
#

Learning programming is free

jaunty ore
#

Ohhhh I thought Asset store

uncut mantle
leaden ice
#

if you keep following that path, you'll go forever unless you detect the cycle somehow

crude dagger
#

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!

spring creek
# jaunty ore Ohhhh I thought Asset store

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

uncut mantle
leaden ice
leaden ice
crude dagger
#

thanks both of you :)

hexed pecan
#

@uncut mantle Praetor is right, I think you are missing a 'closedSet' to check if a node was already visited

uncut mantle
#

Im adding it now, let me see if it works

hexed pecan
#

You can use a HashSet for faster Contains than with List

uncut mantle
#

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.

hexed pecan
#

(Second screenshot)

uncut mantle
#

huh thats interesting let me see, would have never thought of that

#

unfortunately its still hanging :/

hexed pecan
#

You could make it into a coroutine or async and visualize it, see where it goes wrong

uncut mantle
#

good idea let me write that

hexed pecan
#

What are Heapify and HeapifyDeletion? 🤔

uncut mantle
#

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...

▶ Play video
hexed pecan
#

Both are recursive*

uncut mantle
#

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

hexed pecan
#

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.

uncut mantle
#

grabbed his code from github I didnt write it

hexed pecan
uncut mantle
#

a lot of his code changed from the video to the github updates, he removed it himself for some reason

vale turret
#

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)

dusky lake
vale turret
#

I'll try those, thank you!

uncut mantle
dense rock
#

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.

cosmic rain
leaden ice
dense rock
#

what does that mean? sorry :')

leaden ice
dense rock
#

thanks much, that helps a lot :D

lethal lagoon
#

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?

cosmic rain
#

I don't think that checkbox affects anything aside from when regenerating the project files

spring creek
lethal lagoon
#

Visual Studio will work but the colors or the reccomendations wont work

spring creek
#

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

tawny elkBOT
lethal lagoon
#

These are what it looks like on and off

spring creek
lethal lagoon
cosmic rain
lethal lagoon
cosmic rain
lethal lagoon
cosmic rain
# lethal lagoon 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 .

sick crow
#

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

leaden ice
#

there is no data in the body of the response? Or the request?

sick crow
#

there's no data in the body of the request, Unity receives the json response just fine

leaden ice
#

also why is your data called "form" if it's json?

sick crow
#

I've tried a number of things

#

the latest is this

leaden ice
#

I would guess you likely haven't encoded your data properly

#

You probably haven't set the mime type/content type

sick crow
#

That would make sense

#

How would I do that correctly?

leaden ice
sick crow
#

is JsonConvert preferred over JsonUtility?

leaden ice
#

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

sick crow
#

ok, I'm going to sub in
string playerDataJson = JsonUtility.ToJson(playerData);

#

to what package does "GetBytes" belong?

leaden ice
#

I presume they mean Encoding.UTF8.GetBytes

sick crow
#

No, I just remembered, JsonUtility doesn't want to convert my particular list to a string

leaden ice
#

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
sick crow
#

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 += "]";```
leaden ice
#

Yeah JsonUtility won't be able to create that because it doesn't support naked lists/arrays

sick crow
#

great.