#archived-code-general

1 messages · Page 106 of 1

rough crescent
#

i think you can filter which layers the collider interacts with if i remember lol

#

haven't opened unity in 4 years forgot how fun this stuff is

night harness
rough crescent
#

uhh

#

then that's not possible i don't think

#

layer filtering the only way as far as i know

nova magnet
#

i plan to make a better ammo management system, and i have 2 options
1.) revamp all of my weapons and make them all run in one script
2.) make a new script with the ammo management, and do some tweaks in my code
what should i do?

latent latch
#

Really it depends on how you want to implement it. I don't think there is a single best way. It's probably easier to lessen the amount of abstraction though if that's your problem, so creating a super class may be ideal.

trail island
#

hello i'm facing issue with inputs when double tapping, the game should destroy a tile when user tap on them in certain range but when i do double touch on the screen it will destroy tile between the touches like in the video

prime sinew
#

then you should probably check if the first and second tap were on the same tile

#

if they're not the same, then reset the taps

trail island
#

issue starts at 0:04 in the video

prime sinew
#

so what do you want to happen

#

is it that when they tap those 2 tiles, it should destroy those 2 tiles?

trail island
#

it should only break when i touch them

prime sinew
#

you should be showing your code at this point

trail island
#

i'm off my computer rn it's something like

Tilemap tilemap;
public void Update() {
   if(Input.GetMouseButtonDown(0)) {
      tilemap.SetTile(null, myMousePosition) 
   }
}
prime sinew
#

maybe come back and ask later then

#

no point for people to help you when you cant even act on the help

trail island
#

okay then

drowsy harbor
#

Hello 🙂
Does anyone use Hybrid Renderer with Grass? Looks like Hybrid renderer does not support grass....?

full ermine
#

Hi. I have a script for walking and a RigedBody component in it. There are no errors at startup, the collider is configured correctly. But when it comes to walking, the animation is played, and the player does not walk.

prime sinew
drowsy harbor
full ermine
#

public float speed = 10f;
private Vector3 movement;
private Rigidbody rb;

// Start is called before the first frame update
void Start() {
rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update() {
// Read input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");

// Calculate movement vector
movement = new Vector3(horizontal, 0f, vertical).normalized * speed;

}

// FixedUpdate is called once per physics frame
void FixedUpdate() {
// Apply movement to Rigidbody
rb.MovePosition(transform.position + movement * Time.fixedDeltaTime);
}
}

prime sinew
#

and please use the discord formatting for code. it's easier to read.
!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
prime sinew
#

wow that example sucks

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

kind frost
#

Hi, short question:
Is List<T>.ToHashSet generates garbage?

swift falcon
#

What is the performance cost of accessing static values in a different script?

Say there is some static field I expect to use lets say 4000 times per frame, is there much overhead on just using it directly like GlobalData.antCache[i] for instance

#

I thought of just caching it at the start by doing like Matrix4x4[][] antCache = GlobalData.antCache but wouldn't that end up copying it every frame? That sounds expensive

#

For a bit of context, this is going to be used in a Graphics.DrawMeshInstanced() call

woeful narwhal
swift falcon
#

If it were bad I was thinking I could create a struct to contains all the things ants have that I'll use and then foreach it with 1 call instead

#

I just duno what goes on in the background for static referencing

#

I think it gets dragged into CPU cache actually

woeful narwhal
#

yeah thats a good idea since you only need to get the reference once

#

you could also trying sending data through c# events. Even though there static, Ive got a script sending 5 them to ~200 gameobjects in the update function and i still get 500 frames

swift falcon
#

I duno about c# events, I want to convert this to dots

woeful narwhal
#

then ig just do one static reference of a struct

swift falcon
#

Thing is I already batch these there are 1023 ants , that's why it's a 2d Array

So if I make them structs and then for each batch pass it to a job, I think it'd be cleaner, way cleaner

swift aspen
swift falcon
#

Thanks for the input Omle

woeful narwhal
#

alg

swift falcon
#

I am still curious about the inner workings of how static field accessing works tho

kind frost
swift falcon
#

Like I've heard accessing Unity internal static fields can be expensive which is what leads me to wonder

woeful narwhal
swift falcon
#

Hey Unity developers!

I have a little issue, when I make my A* character follow a path in the awake method he moves there all fine but when done in this "state" setup the end path switches between two blocks and starts to build up lag:

            case States.MovingToToolShed:
                if(unit.IsIdle())
                {   
                    unit.ChangePath(gameObject, MoveToNode);              
                    Debug.Log("On my way");
                }

This causes lag over time but

private void Awake() 
    {
        unit = gameObject.GetComponent<IUnit>();
        state = States.Idle;
        MoveToNode = GameHandler.GetToolAreaNode_Static();
         unit.ChangePath(gameObject, MoveToNode);
     }

Does not cause lag

swift aspen
prime sinew
swift falcon
#

i can send a video?

swift falcon
#

If I'm using a for loop and not foreach ofc

swift aspen
swift falcon
#

the Unity C++ backend part does make sense, I get that

#

It'd be an absolute micro change I guess to save a few pointer lookups

swift aspen
#

Maybe there' s small small perf gain but in the grand scheme of thing it's negligible

#

yeah exactly

swift falcon
#

Well thanks, I appreciate the info

steady moat
swift falcon
#

Well it's for uni, like an emerging tech thing with dots so I've been focused a lot on understanding the inner workings of things and how they affect performance

#

But yeh, it's quite easy to overengineer things, I'd care a lot less about the approach if it wasn't an assignment lol

swift falcon
swift falcon
#

Oh yeh logging really adds up

#

it was printing the position and got up to like 200k

#

I made a proc gen system once with logs on every tile and CPU hates that

#

pft

#

can I have some help with another issue if I send a video?

swift aspen
swift falcon
steady moat
swift falcon
#

Not sure why the black cube is switching

#

(the lag is just the shit recording)

swift falcon
#

But yeh I guess I should change my approach then

swift aspen
swift falcon
#

Okay well that is problematic because that would mean I'd need to merge a lot of scripts for them to work with burst

#

Wait unless I have the spawner populate the data in the 2nd script instead

#

Okay yeh I think I get it, thanks, I'll work on that

#

Matricies can hurt my head lol

swift aspen
# swift falcon Okay yeh I think I get it, thanks, I'll work on that

If you're doing a normal MonoBehaviour project then you don't really need to. Usually what you do is you collect all data that you wish to process through a bursted job and put it in to special containers and run the job. Then when it's complete you "put it back" to the MonoBehaviours and such.

No point complicating stuff unless that's your intention

swift falcon
#

Honestly I learnt a bit about dots in 0.5 and I'm not sure if that's been a boon or a burden

#

Still figuring out hybrid

#

Okay so I have a spawner and that creates everything the structs and etc and I'll get that to populate the data in script that's a container

I have my mono which we'll call the renderer for now... That has the update which grabs the information it needs from the container we created and then passes that to a bursted job with the data as a param?

That'll work? that is what u mean?

#

Okay yeh I think I understand, as long as I'm not passing it classes and etc

swift aspen
#

Yeah should work if I understand your explanation

swift falcon
#

Yeh so "Update" gathers and the "job" processes

swift aspen
#

yeah

#

then usually in LateUpdate you Complete() your job to make sure it's all done and put the data back

swift falcon
#

Ok thanks, wish me luck haha

#

goodluck!!

stuck glacier
#

hey i wanted to ask a bit of a technical question, not to troubleshoot but instead to learn something from it.
here are 2 pieces of code:
var XVelocity = RB.velocity.x;
var ZVelocity = RB.velocity.z;
XVelocity = Mathf.Clamp(RB.Velocity.x, -MaxXZVelocity, MaxXZVelocity);
ZVelocity = Mathf.Clamp(ZVelocity, -MaxXZVelocity, MaxXZVelocity);
RB.velocity = new Vector3(XVelocity, RB.velocity.y, ZVelocity);

and a more refined version:

var XVelocity = Mathf.Clamp(RB.velocity.x, -MaxXZVelocity, MaxXZVelocity);
var ZVelocity = Mathf.Clamp(RB.velocity.z, -MaxXZVelocity, MaxXZVelocity);
RB.velocity = new Vector3(XVelocity, RB.velocity.y, ZVelocity);

so basically, the code at the top is supposed to be the same/similar to the bottom. it's clamping the velocity on the X and Z axis. and yet, the one at the top has caused me a drift issue where (using Rigidbody.AddRelativeForce for movement) the player character sometimes goes diagonally to the right or left when trying to move forwards/backwards. realized i could shave off 2 lines to make it cleaner (the bottom code) and for some reason that fixed it? why? need to know to avoid future issues.

oblique basalt
#

how can i Serialize a dictionary? I need to store a ScriptableObject named Resource along with an integer for the amount of that resource the player has in an object named ResourceManager

heady iris
#

you'd have to do that work manually, of course

heady iris
#

Note that this will cause some unusual behavior

heady iris
#

you are clamping the X and Z axes (in world space) separately.

#

this means you'll be able to go faster on a diagonal

stuck glacier
steady moat
#

With Y = 0.

swift falcon
#

That's a lot better than my 2 dot product approach lol

oblique basalt
stuck glacier
steady moat
swift falcon
heady iris
stuck glacier
#

wait so, id set the y velocity to 0, then clamp x and z, then restore?

heady iris
#

Right. This way, you would clamp your horizontal speed without affecting your vertical speed.

steady moat
# stuck glacier wait so, id set the y velocity to 0, then clamp x and z, then restore?

You could also do the calculation manually.

        //
        // Summary:
        //     Returns a copy of vector with its magnitude clamped to maxLength.
        //
        // Parameters:
        //   vector:
        //
        //   maxLength:
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Vector3 ClampMagnitude(Vector3 vector, float maxLength)
        {
            float num = vector.sqrMagnitude;
            if (num > maxLength * maxLength)
            {
                float num2 = (float)Math.Sqrt(num);
                float num3 = vector.x / num2;
                float num4 = vector.y / num2;
                float num5 = vector.z / num2;
                return new Vector3(num3 * maxLength, num4 * maxLength, num5 * maxLength);
            }

            return vector;
        }
sharp lodge
#

can someone help please i have a twitch chat intergrated game and im trying to get pubsub to work when people drop bits on twitch how i can get the game to work and drop bit prefabs this is what i have at the moment in unity https://i.imgur.com/hBYOPVc.png

oblique basalt
#
[System.Serializable]
public class ResourceMap : MonoBehaviour
{
    public Resource resource;
    public int amount;
}

~~ ANOTHER SCRIPT ~~
public class ResourceManager : MonoBehaviour
{
    public ResourceMap[] resources;

    public ResourceMap GetResourceFromString(string resourceName){
        foreach (ResourceMap rm in resources)
        {
            if(rm.name == resourceName) return rm;
        }
        return null;
    }

}

Why cant i manually edit the resource map in the inspector?

heady iris
#

because the property drawer for a MonoBehaviour doesn't draw all of the properties of the object

#

it just draws the reference

oblique basalt
#

oh ok it doesnt need ot be a monobehavior

#

ill just removee that bit

#

thanks

heady iris
#

right.

#

monobehaviours must be attached to game objects

oblique basalt
#

yeah i noramlly just leave it there since it doesnt cause any problems, need to stop doing that UnityChanSalute

rain minnow
heady iris
#

i believe the intent was to just have a plain old C# object

oblique basalt
#

👍 working now thx

heady iris
#

but they, by force of habit, derived from MonoBehaviour

rain minnow
#

yeah, that what i wondered. makes sense . . .

clever canopy
#

ok i have 1 more thing
i made this but when the game starts then 1 and 2 is printed but when i move its not printed anymore

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectDeath : MonoBehaviour
{
    public Collider collider1;
    public Collider collider2;
    void OnCollisionEnter(Collision collision)
    {
        
        if(collision.collider == collider1)
        {
            Debug.Log("1");
        } else if (collision.collider == collider2)
        {
            print("2");
        }
        print(collision.collider.tag);
    }

}

i have a rigidbody component character controller and 2 box colliders for my player

#

i turned off the is trigger still didnt work

leaden ice
rotund burrow
#

I want to make something like a custom nav mesh link for custom a* pathfinding. The idea is to make a node graph and have nodes that are too far from each other act as links (or mark them somehow else). For example, for a unit with a jump ability the part of a* that checks for neighbor nodes will either check those links or not depending on cooldown and when the unit reaches it it will tell it to jump. The difference from normal link is that there will be unique graphs for units and unique links for abilities. Also there will be more links (for example navmesh will only generate 2 links for a cliff, while i want to have more). Is that a good idea?

#

what i want to do is make units seem to behave naturally in 3d environment with a lot of verticality where you can fly jump dash etc.

ashen yoke
#

links are typically a concept that connects graph parts that need to be normally traversed by anything

#

as in it acts just as a node connection for the purposes of calculating a path

#

in your case it seems you just want specific unit to be able to jump somewhere, which can be solved by just flood filling the graph, or sampling target area where it wants to land for valid nodes

#

what i mean is this doesnt specifically require additional links

rotund burrow
#

flood filling the graph?

ashen yoke
#

missed the second line you wrote

#

yes flood fill, search method

#

check all tiles starting from x for some condition

#

are we talking grid here?

#

or navmesh?

#

are we talking graphs layered on top of each other?

#

floor1-2..

rotund burrow
#

i have a 3d grid thing and unity navmesh which i use to test things, but i would like to make my own 3d navmeshes later if i'm able to

ashen yoke
#

yeah if you write your own navmesh or use recast/ a* pathfinding project, youll get direct access to node data so just adding a connection based on some ruleset is simple, problem is the ruleset itself

#

it sounds like a very daunting task to automate, given amount of edge cases

#

yes it would be insane, with all the collision checks you have to do, so that links arent generated through geometry, at impossible angles and all that

steady moat
# rotund burrow i have a 3d grid thing and unity navmesh which i use to test things, but i would...

A* can be used for anything. The only thing you need to define is:

  • The state (It can be anything, not just position)
  • The neighbor (All other state that you can get from one defined state, maybe you can use an item which takes you to an other state that is not a new position)
  • The heuristic (What is the estimate cost to get to the target.)
  • The real cost (What is the real cost that took you to get there)

For optimality, you need to be sure that your heuristic is always smaller than the remaining real cost. (How tight is the difference between your real cost and your heuristic will define the performance of A*)

Note: In your case, time could be a good value for the real cost instead of distance.

ashen yoke
#

max i can envision is custom tooling for mapwork, for example instead of unity's circly thingy, you define actual areas/rects/polygons which connect different heights

#

so that the whole area is working as a link, with any triangles in it automatically connected

rotund burrow
#

yeah i think i'm way over my head with this. It's hard to understand you but i want to learn. maybe you can give me some resources to start with

ashen yoke
#

ill draw it

#

imagine automating link generation in this scenario

rotund burrow
#

you mean it would be hard to automatically make a graph ?

ashen yoke
#

to generate "jump" links

ashen yoke
#

well its one solution

#

easiest to implement, more taxing on content creation

#

youd have to yourself create those areas and connect them, which would generate links

#

but at least have direct control and validation that those areas are valid for linking

rotund burrow
#

i think i get it. how would you connect it to the navmesh ?

ashen yoke
#

i dont understand what you mean

steady moat
heady iris
#

you could automate the placement of these links

whole night
#

i am not able to understand why attributes are required if they dont do anything to the code ?

heady iris
#

They can be retrieved via reflection

#

Unity looks for a SerializeFieldAttribute on your fields, for example

#

It’s true that they don’t do anything by themselves

whole night
#

There is this AmmoType attribute before the int ammoType

#

and this class is just empty. I am not able to understand why this is done

#

this was take from the Unity Learn's FPS Kit

knotty sun
whole night
#

how to find that ?

#

there is system.serializable tag above that class

clever canopy
knotty sun
knotty sun
whole night
knotty sun
whole night
#

is there a use case where putting attributes is good ?

knotty sun
#

lots and lots

#

custom inspectors being one of them

#

the Range attribute is also very convenient

clever canopy
swift falcon
#

Does anyone know an efficient way to get the child object index from name ?

heady iris
#

I believe you can get the child index from the transform

swift falcon
#

like index of "tool"

#

I think you could use a loop with a list but im tryna find an efficient quick way

heady iris
#

Why the object name?

swift falcon
#

cuz im tryna set and deactive the "farmers" tool at times but some farmers may have more bones etc

#

so the index will be different

heady iris
#

Store a reference to the transform

maiden fractal
heady iris
#

Finding stuff by name is very error prone

maiden fractal
maiden fractal
#

No

swift falcon
#

found an article that says you can use Guid's or UUIDs

#

same thing but

maiden fractal
#

Oh man, use [SerializeField] Transform smt;

swift falcon
#

Oh I thought you meant like in the code itself

heady iris
#

Well, sort of

maiden fractal
#

In the code yeah

heady iris
#

Create a field. Store a reference in it.

swift falcon
#

yeah i know what u mean now xd

#

I was thinking of binary formatter for some reason

#

lol

#

or protobuf

maiden fractal
#

You are overcomplicating things a lot

heady iris
#

You should pretty much never need to find things by index or name. Grab references ahead of time.

swift falcon
#

that makes sense

#

im sleepy its 12 am xd

swift falcon
#

lol thanks for the wake up

thin maple
#

is there a way to create something like a GPU background task? like having a compute shader run in the background with lower priority on the GPU while the rest of the game is rendering

swift falcon
#

" but adds a few frames of latency" suppose thats a minor cost

hexed pecan
#

I suppose theres a way to wait for it to finish right away if needed

#

WaitAllRequests?

thin maple
swift falcon
thin maple
#

basically I want to do long-running terrain generation in the background with compute shaders while the game is running normally

hexed pecan
#

Yeah this is what you want most likely

swift falcon
#

apparently you have to call ```cs
AsyncGPUReadbackRequest.done

clever canopy
swift falcon
#

oop

#

what are you trying to collide with

clever canopy
swift falcon
#

does the player/user actually collide or like a trigger

clever canopy
swift falcon
leaden ice
swift falcon
#

I think they mean as in not registering it

heady iris
#

Maybe the attack hitbox should turn off when successfully blocked

#

(Or is that bot your problem?)

#

I am unclear.

clever canopy
#

my problem is that i need which collider was hit

swift falcon
#
private void OnCollisionEnter2D(Collision2D collision)
{
Collider2D col = collision.gameObject.GetComponent<Collider2D>();
if (goal.IsTouching(col))
{
Debug.Log("Working");
}
}

this is a 2D example I found but should work the same

clever canopy
#

whats the goal variable?

heady iris
#

And give them components that respond to collisions

#

Alternatively, handle the collision on the weapon

#

Then it will know exactly which collider you hit

swift falcon
clever canopy
heady iris
#

Unity will have to reload before the file shows up the project correctly

knotty sun
swift falcon
#

how to make collision while game object is in (is trigger), is that possible?

heady iris
#

i do not understand

#

Triggers do not influence physics

potent sleet
swift falcon
potent sleet
swift falcon
#

thx

heady iris
#

You could put two on the same object if you wanted

#

But then you couldn’t tell them apart if you hit a trigger

clever canopy
zinc parrot
#

Hey can you call/run compute shaders in an async task?

left wedge
#

I have a character using a CharacterController and an enemy that also uses a CharacterController. My boss has an attack where it runs at the character and when it collides I want it to knock the character back. I'm having a mental block here because two CharacterControllers don't report their collisions consistently using OnControllerCollisionHit. Sometimes I get the "Hit character" debug message and other times I don't. I tried changing my boss to use a Rigidbody but this just introduces a whole world of pain with other weird physics reactions when the collision occurs. I've also tried straight up using a larger Trigger collider on the boss to detect it that way but this feels like a hack and again comes with its own issues.

Am I doing something obviously wrong here? I assumed two character controllers colliding would be a pretty normal thing to want to detect reliably but I can't really find any useful info online or in the forum. Any help much appreciated.

heady iris
#

using a trigger sounds fine to me

left wedge
#

Yup that was what I assumed would be the best solution but i ended up with odd issues. I may have solved it a slightly simpler way now. My RushAttackState already knows if it "hit" the player based on the distance to the player during the attack, when it reaches a certain threshold it stops, otherwise it stops after a set maxDistance. If it stopped because the player is within the threshold I can just assume they were hit and apply the knockback at that point.

#

I'll probably wanna do some sort of Line of Sight check but i'd have to do that with a trigger anyway I guess.

hidden veldt
#

Anyone know if there's a way to set an object to not be pickable through code?

hexed pecan
#

If you care my search terms were unity editor set object unselectable in hierarchy

potent sleet
#

neat

worldly hull
#

im using linq to cheese a little bit on recreating an array, the array is the base code of other 100+ scripts and wont be able to change, my team lead will NEVER EVER rewrite anything that affects more than 3 main scripts

soooo

GameObject[] newAllInteractables = QuestManager.instance.allnteractables.Except(gameObject);```

apparently the gameobject is wrong, how to convert IEnumerable<GameObject> to GameObject?
#

allInteractables is GameObject[]

heady iris
#

Except takes a sequence

#

you can make a one-element array

#

new[] { theThing }

worldly hull
#

nope im not going to change it to list lol

versed pagoda
#

Hi, did someone in here made an Leaderboard using Steamworks.NET recently? I've followed everything right but i can't get the player to upload it's score to the leaderboard... Here's my code for that, ignore the bad naming as i'm just trying to get it to work (i'm sending it each 2s only for testing purposes, i'll send only when the game is over):
https://hatebin.com/ndubsokuap

hidden veldt
versed pagoda
tacit lance
#

Don't know if this is the best place to ask but
I have a GameObject looking for touches with TouchPhase.Ended, and filtering out those that touched the UI with EventSystem.current.IsPointerOverGameObject(touch.fingerId). When it gets touched, it opens a menu. It works perfectly, except for a weird edge case: if you click the close button on the menu (which disables the canvas), and the gameobject that opens the menu is just under the button on screen, then in the same frame, the object gets a touch with TouchPhase.Ended, which causes the menu to open again. Is there an easy way to solve this?

wary latch
#

where should i save my save files and how?

solemn rune
#

Hi. I'm having some trouble with input and movement. I'm moving a game object left and right, depending on input axis (arrow keys in this case, only -1 or 1). This works fluent at 300fps, but as soon as I cap to 60fps the object moves one frame, upon button press, and then stops?

#

Vector3 newPosition = transform.position + activeSpawn.right * (setUpMoveSpeed * horizontalAxis * Time.deltaTime) ;

#

anybody any idea?

swift falcon
solemn rune
#

its running in Update. And I am setting newPosition to the transform, not using physics for this

swift falcon
#

you wanna put everything physics-related into FixedUpdate

#

and use fixedDeltaTime instead of deltaTime

solemn rune
#

it's not a physics object, just something that moves left / right. no colliders or rigidbodies needed

hexed pecan
#

Oh I see, Update

#

It looks fine then

#

Where does horizontalSpeed come from?

solemn rune
#

right? it should work. I'm following that thread right now, has to be the way it's called

hexed pecan
#

And setupmovespeed

solemn rune
#

horizontalAxis comes from a InputAction. I think I'm figuring it out. Testing just that line of code in a separate script

#

yeah, has to be higher up.. My systems are probably messing up. Thanks for confirming the code @hexed pecan 🙂

swift falcon
#

I'm using this piece of code to smoothly transition between hand's and VR controller's rotation

            Quaternion rotation = controller.rotation * Quaternion.Inverse(transform.rotation);
            rotation.ToAngleAxis(out float rotationDegrees, out Vector3 rotationAxis);
            Vector3 angularVelocity = Vector3.ClampMagnitude(_angularSync * rotationAxis * Mathf.Deg2Rad, (rotationDegrees * rotationDegrees * Mathf.Deg2Rad * Mathf.Deg2Rad) / Time.fixedDeltaTime);
            _rigidbody.angularVelocity = angularVelocity;

and it works just fine aside from one (expected) moment - hand does a 360 when the controller's rotation into any axis passes 0 and swings back to 359, any ideas on how to handle this?

#

I've encountered this problem before but I don't remember the solution

soft shard
visual flare
#

where can I download unity 4.7? the archive no longer shows it but i know that they keep links live for a long time

vagrant blade
#

I don't recall the archives every going back before 5 🤔

#

But if they're no there, then there's no official way to get it.

visual flare
#

you might be right. I do remember downloading it last year, wonder where...

somber nacelle
#

any particular reason you want to download a pre-historic version of unity? 🤔

dapper sparrow
#

hello mates ! i m trying to make a drawing program on 3D objects in unity with camera ray hitinfo on the coordonates of the texture but i discovered that the defaults objects do not have an atlas texture but a replicated texture on each face for a cube for example, how can i say to unity to create an atlas texture for each object i add ?

visual flare
#

they removed beast in 5

teal mica
hollow hound
#

Different behaviour in scripts of instantiated and dragged to scene prefabs

In short, I have events inside struct inside dictionary.

Dictionary<StatusEffect, StatusEffectConfig> _statusEffectsConfig;
public event Action<OnStatusEffectStartRecord> onLockMovementStart;
public event Action<OnStatusEffectEndRecord> onLockMovementEnd;

// init in Awake()
_statusEffectsConfig = new()
      {
        [StatusEffect.LockMovement] = new(
            new() { OnStartEvent = onLockMovementStart, OnEndEvent = onLockMovementEnd },
        )
      };

And then I invoke those events using struct:

dictionaryElement.Events.OnStartEvent?.Invoke()

Works perfectly when prefab with this script is dragged into scene. But doesn't work when it is instantiated.
The problem is that in instantiated prefab there is no one subscribed to the event.
I checked the event field in the class and from struct (that has this event inside) like that:

Debug.Log($"OnStartEvent0 {config.Events.OnStartEvent is null}");
Debug.Log($"OnStartEvent1 {onLockMovementStart is null}");

In the "dragged to scene" prefab both logs says "false", both delegates are not empty as expected.
But in instantiated prefab only second log is "false", so it doesn't have relevant reference to the event.
Why is this happening?

dusk apex
#

Does it differ from the prefab?

hollow hound
dusk apex
#

Where you'd instantiate a copy of the prefab but the one in the scene could have had it's inspector fields modified.

dusk apex
#

Are you cloning?

#

The clone would be identical to the instance in the scene.

hollow hound
dusk apex
#

I'm assuming hierarchy instance isn't the same as the prefab

dusk apex
hollow hound
hollow hound
dusk apex
# hollow hound > Show us the inspector for the scene instance What part of it? It's like "pref...

The error indicates that there is a difference between the components. We're needing to verify it ourselves because this is the most probable cause of the unwanted behavior. There isn't anything wrong with the code. Race condition would be the only other concern but as you're checking if something hasn't been prepared yet rather than the opposite, it isn't the case - you're checking for null.

#

We need more context else this isn't going to get anywhere.

teal mica
# hollow hound **Different behaviour in scripts of instantiated and dragged to scene prefabs** ...

from this description, it shows that onLockMovementStart is not null, meaning that the assignment could be correct, but the Awake function may not have been called correctly, or was not called at the correct time, otherwise, OnStartEvent should not have been null, it would be good to check if _statusEffectConfig[StatusEffect.LockMovement] has it's assigned parameters at the end of the Awake call

dusk apex
#

The most reasonable excuse why cs Debug.Log($"OnStartEvent0 {config.Events.OnStartEvent is null}");would differ between the instantiated instances and preset instance would be the availability of the OnStartEvent.

hollow hound
dusk apex
heady iris
#

I have a rotation that's made from a yaw followed by a pitch. Is there a neat way to recover the pitch from that?

#

The rotation is the direction the player is trying to look in. I want to adjust the camera's position based on the pitch.

dusk apex
heady iris
#

I was also just thinking of doing that :p

#

I'd like for this camera to work with any entity, not just a player

#

and only the player brain will be storing the yaw and pitch floats

#

other brains will just be using LookRotation to calculate their desired rotation

hollow hound
dusk apex
heady iris
#

You know, I wonder if I should just split this into two rotations

hollow hound
teal mica
heady iris
#

right now, the brain has one rotation property: "desired rotation"

#

but, really, there are two rotations here

#

the body rotation and the look rotation

#

i'm already doing something Gross(tm) to extract just the body rotation

#

currentRotation = Quaternion.AngleAxis(brain.DesiredRotation.eulerAngles.y, Vector3.up);

#

...yeah, I think I should just have two separate rotations!

#

i just realized this is exactly what I did in another game 🤦‍♂️

teal mica
#

im not sure what a config is, since this variable is never described, it could also be that you might be overwriting the dictionary somewhere down the line

hollow hound
teal mica
#

just the component with the script

#

we're trying to see if there is a discrepancy between your prefab and the scene object

hollow hound
teal mica
#

these snippets of code are not very helpful for understanding the context

dusk apex
# hollow hound I don't exactly understand what you mean.

I've placed quite a bit of effort to acquire the necessary debugging data for validating the inspectors of the referenced - implicitly config. The direction was to move towards why the event delegates weren't the same. You're fighting this every step of the way with "why is it necessary" or abstracts. The logs simply indicate that they are no longer both null. It has likely been modified elsewhere before the second has acquired it - sometime before instantiate. Good luck with the rest.

hollow hound
hollow hound
teal mica
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

hollow hound
teal mica
#

I literally mean debugging inside Awake, at the end of the call

rugged storm
#
        var _currentPacket = packets.Values.Where(p => p.columnIndex == start.columnIndex + 1);

        if (_currentPacket != null || _currentPacket.Count() != 0)
        {
            Packet currentPacket = _currentPacket.First();
            packetsAbove.Add(currentPacket);
            GetPacketsAbove(currentPacket, packetsAbove);
        }```
is there a better what to check if packets.Values.Where(p => p.columnIndex == start.columnIndex + 1).First() exists? when i do currentPacket  =packets.Values.Where(p => p.columnIndex == start.columnIndex + 1).First()  it errors instead of say returning null if the where has no results
dusk apex
rugged storm
#

oh its that the sequence has no elements

teal mica
#

do you mean FirstOrDefault

#

it returns a default element if none exists

rugged storm
#

Unity telly me FirstOrDefault is outdated?

dusk apex
rugged storm
#

IK why the issue is happening, its list.where() is empty so when i try to get list.where().first, it throws it

dusk apex
#

It says they were empty?

hollow hound
teal mica
#

so your problem isn't here at all

#

you've overwrote the entry further down the script

#

Awake is only called once on initialization, even when you change the event reference, the other reference will not get reassigned

rugged storm
hollow hound
teal mica
rugged storm
#

ah, also how do I set a default value for a list??

rugged storm
teal mica
hollow hound
teal mica
#

Your assignment is inside a struct, it will not be reassigned when the parameter you passed in was changed

rugged storm
#

i assume that the default of a list is null by default(which is what I need in my current case) but how would I set it if I needed to for say List<Packet> packets

teal mica
knotty sun
rugged storm
teal mica
#

I think they mean the returned default of FirstOrDefault, which happens to be null, afaik, there's no way to directly change this default

rugged storm
#

^ that is correct

knotty sun
#

that depends on the T value of the list

teal mica
#

yea you're right, for reference types, it is null

rugged storm
#

im guessing if T cant be null like for things like ints it will return something else?

knotty sun
#

indeed

rugged storm
#

in the case of int 0 im guessing?

knotty sun
#

default(T)

hollow hound
rugged storm
#

ty for all the help yall

#

another thing how would i overwrite a dictionary entry, currently it give this error if i try to add a entry with a key that already exists how would I instead overwrite the old entry with that key to the new one?

knotty sun
#

dict[key] = newvalue

teal mica
hollow hound
rugged storm
# knotty sun dict[key] = newvalue

Okay, would this also set the value of a new entry if one with that key doesn't it exist or should I run an if statement to see if that key already exists and chose between .add and doing that?

rugged storm
#

👌

knotty sun
#

use dict.ContainsKey

teal mica
# hollow hound Oh, I think I get it. Can I somehow create like "empty" delegate to use it as a...

your idea requires the object to be mutable, and you're relying on the side effect of mutable operations and having many references point to the same object to have synchronised behaviour, but in this case, delegate is immutable, you will not be able to achieve the same side effect, rely on pure mechanisms and assign the reference yourself, when onLockMechanism changes, assign the struct to the same Action, maybe with the set property

hollow hound
teal mica
#

im not really sure what you mean at this point, you seem to have a design issue right now, if different object subscribe to some governing event, then there should only be one event

#

if you have different events, then its normal that one event does not invoke the methods subscribed to another event

hollow hound
# teal mica im not really sure what you mean at this point, you seem to have a design issue ...

I have different status effects (like stun or burn).
I have Stats script that controls them.
From another scripts I want to apply effects like targetStats.Apply(StatusEffect.Stun).
And I need Stats to invoke events on applying (and when the effect is ended).
Other scripts should be able to subscribe to this events anytime like targetStats.OnStunStart += HandleStun
And I don't want to have different function for every status effect like ApplyStun(), ApplyBurn().
I want to use one function with rewriting code like Apply(StatusEffect effect)

#

Is there a better approach to this?

hollow hound
#

Basically, I want to store a reference to event. So if someone will subscribe to this event later, I should be able to get valid event with all subscribed functions.
Is it possible? Or I should try another approach?

teal mica
#

yes, it is possible, because both will be pointing to the same object, but you must ensure that the object is correctly initialised in the first place

hollow hound
#

So
new() { OnStartEvent = onLockMovementStart, OnEndEvent = onLockMovementEnd } is not correct way of doing that?

narrow summit
#

For anyone who's used addressables extensively, is it possible to use the SceneLoad API in it to load scenes normally? Basically, I don't want to use addressables, but I'd like to use its async scene loading API. (Loading scenes from paths)

hollow hound
teal mica
# hollow hound This is record, can change it to struct

i've actually never used records before, I'm not sure if this will work always. Generally do not use value types (i.e. don't use a struct) in your described use case, as changes to their variables will only affect that instance

hollow hound
hollow hound
teal mica
lament bloom
#

is there a good way to calculate a location on the HUD/screen overlay based on the position of an object as seen by the camera?

#

in this case, when a player picks up an enemy drop in my game, i want some on-screen text to appear where the drop used to be that says "Gained ..."

#

but i don't want this text to appear in world-space, i want it to appear on the screen overlay

dusk apex
#

Camera should have world to screen conversation

lament bloom
#

thank u

viscid tide
#

Hey so I’m trying to make a spaceship vr game and I need help with the throttle. I have most of the throttle code done except for one thing. So I want the throttle to follows the players hand position but I want it to stay on a line if that makes sense. Basically follow the hand position but then go the closest position on the line going up the side of the spaceship . I’m stuck so I was wondering if anyone could help me.

void basalt
viscid tide
void basalt
#

If your body is sitting in a chair, and you raise your hand forward, you can minus the hand position from the body position

#

and you'll get a forward direction

#

it actually might be backwards so you'll have to negate it

viscid tide
#

Ok I get it but how would I use that with throttle position? Just use the positions B - Positions A?

void basalt
#

Your throttle should be an alpha value between 0 and 1 representing 0% and 100%

#

0% means no thrust. 100% means full thrust. You can probably go to -1 (-100%) for backwards thrust as well

#

you'll need to scale the direction by your thrust value

#

normalize the direction first, then multiply in your thrust

#

If you're trying to do a large-scale space game also, you're going to run into floating point issues very fast.

#

@viscid tideLet me know if you're still stuck

viscid tide
#

Oh I understand now @void basalt Thank you!

unreal valley
#

This is problem a very easy answer for you smart folk out there.

How can I change the type of an object to another.

I have an Item, I get all Items. But now I wana dig deeper into what that Item actually is.

If its an EquipmentItem I want to be able to change it to that type, since it derives from Item.

I just don't know how to do this.

#

Nvm I guess I just figured it out.

#
foreach (var item in _inventory)
        {
            Debug.Log($"Item Name:{item.Key.ItemName} Item ID:{item.Key.ItemID}");
            if( item.Key.GetType() == typeof(EquipmentItem))
            {
                EquipmentItem equipmentItem = (EquipmentItem)item.Key;
                Debug.Log($"Required Level: {equipmentItem.RequiredLevel}");
            }
        }
grave fog
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BikeWheelScript : MonoBehaviour
{
    public float speed = 100;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            GetComponent<Rigidbody2D>().AddTorque(Vector2.right * speed);
        }
    }
}```

Keep Getting "Argument 1: cannot convert from 'UnityEngine.Vector2' to 'float'"
unreal valley
#

You need to pull out either the .x or .y values

grave fog
#

because it rotates the way I need it to.

potent sleet
#

it takes a float

grave fog
potent sleet
grave fog
#

Do I just rewrite it to

GetComponent<Rigidbody2D>().AddTorque(torque);
unreal valley
#

Yes

grave fog
#

Huh

#

Okay

#

Thanks!

unreal valley
#

Just a number

#

which in your case is your speed variable

grave fog
#

I changed it to torque to make it simpler.

#

Now I have another problem.

#

It seems that the torque is continuous.

#

Once I hit the Up Arrow it kinda just spins non stop

potent sleet
#

drag = less spinning over time

#

also just making sure you know
GetKey is constantly fired for more than 1 frame so even if you press it once it will call it at least 3-4 times

#

unlike GetKeyDown

grave fog
#

I'm a newbie. But, I get the gist of what I'm doing.

#

Better question, how do I know if I have drag

potent sleet
#

you will find angular drag there

grave fog
#

pretty sure thats the default value

potent sleet
#

yeah well it's prob too low for the amount of force you spinning it at

grave fog
#

5 seems to be a good number

frosty knot
#

is Allow Fullscreen Switch broken in unity?

potent sleet
frosty knot
# potent sleet wdym

LOL you won't believe it, but for the past hour even when I unchecked Allow Fullscreen Switch it was still allowing alt+enter. UP UNTIL I asked the question. Now it's working properly.

turbid lava
#

yo anyone here able to help me with some force troubles?

turbid lava
#

ok fair, but still

#

its not that the force isnt working, its just tryna get the values right for it

lean sail
#

u still havent asked the actual question

turbid lava
#

im tryna think of how to phrase it so it explains what ive tried already lmao

leaden ice
#

First explain what you want to do

#

Then explain what you tried and what the result was

turbid lava
#

im trying to make a flight sim sorta thing and i have the controls and everything setup, but i cant seem to get the values right for the acceleration so that the plane moves fast enough to use the wings to provide lift and not be a missile as it currently is.
if i lower the value of the "thrust" it barely moves fast enough and doesnt take off, but if i convert the engine hp to newtons ish it has way too much power.
i have a mini calculation bit to figure out how much lift the wings would be producing, and after some testing of the vertical lift value i need to get it to around 7500, which means the plane needs to moving at a little over 300m/s.
issue is that to get it to this speed the thrust value seems to be way to high at +108000 which means i can go vertical, which i shouldnt be

void basalt
#

ensure that you're applying force correctly at the ailerons using addForceAtPosition

#

and the propellers or whatever is driving your craft

turbid lava
#

the force is being applied to the whole aircraft atm cos im tryna get it to work first then break it down onto each part

void basalt
#

yeah that aint gonna work

turbid lava
#

so you reckon apply the force to the whole prop then?

void basalt
#

the forward thrust, sure

#

the lift needs to be applied at the ailerons

turbid lava
#

wings

#

ailerons control roll

void basalt
#

regardless, the upward lift needs to be applied at the wings

turbid lava
#

yeah

void basalt
#

and that's probably your issue

turbid lava
#

i did do that before but nothing happened because it wasnt getting enough lift

void basalt
#

more force

#

you could probably cheat and just apply some upwards force at the nose

turbid lava
#

yeah but the speed needs to be higher and the plane doesnt seem to want to go faster without making the thrust a rediculously higher number which then nullifys the purpose of the wings providing lift cos the plane can jsut go vertical

void basalt
#

you could make the lift force of the wings proportional to the speed of the aircraft

#

which is probably how it works in real life

calm talon
#

How do I avoid the animator preventing script from changing an element on the attached gameobject without disabling it?

#

(in my case it's the spriterenderer's colour)

turbid lava
#

ive got it setting the lift to be wing surface area * speed * air desity

void basalt
#

You should have two force multipliers. One for the actual thrust of the aircraft, and one for the wing lift

hexed pecan
turbid lava
#

but the other issue still is coming from the fact that it wont accelerate to a high enough speed with a lower value, and because supersonic if i set the real newtons value

void basalt
#

That just doesn't sound right

#

let's start over

calm talon
turbid lava
#

the current variables

calm talon
#
    protected IEnumerator Flash() 
    {
        thisRenderer.color = new Color(initialColour.r - 0.7f, initialColour.g - 0.7f, initialColour.b - 0.7f);
        yield return new WaitForSeconds(0.2f);
        thisRenderer.color = initialColour;
    }```
here's the code on it btw
hexed pecan
void basalt
#

@turbid lavaYou're using wheel colliders right?

turbid lava
#

yeah

hexed pecan
#

To get a coroutine equivalent of LateUpdate @calm talon

void basalt
calm talon
#

Thanks

void basalt
#

independent of thrust force

turbid lava
#

i have the lift for the left and right wings as their own values

hexed pecan
turbid lava
#

then the "lift wings" that i am using to add them together to apply it as a single force on the whole plane first

#

cos when i tried doing it at position it didnt work

calm talon
#

it really is the

void basalt
#

you need to use add force at position

hexed pecan
#

I mean it does what you put in the animations 🤷‍♂️ @calm talon

void basalt
#

the physics engine is much more complicated than you think

#

it imitates real life physics

#

adding force upwards at the center of the aircraft really isn't going to give you the desired results

turbid lava
#

i was using that as a way to debug what was happening and see when it actually starts lifting with what value

#

gimme a min to revert it to use the add force at pos

void basalt
#

if add force at position isn't working, then we need to figure that out first

urban stream
#

Hello! I'm wanting to know how can I force crash my game's application. I see the documentation for UnityEngine.Diagnostics but I'm not sure how can I code it. Is it a method I call? I want to call it inside a method.

turbid lava
urban stream
void basalt
calm talon
void basalt
turbid lava
#

ok cool

calm talon
#

that should do the trick

void basalt
#

if (crashGame) {
while (true) {

}}

urban stream
#

There's an actual method for this. But I'm not sure how do I call it

calm talon
urban stream
#

I'm gonna test this out.

void basalt
# urban stream

I mean, the docs pretty much tell you how. Call ForceCrash and then use one of the enumerations on the page you're viewing

urban stream
void basalt
#

@turbid lavaworking?

turbid lava
#

currently no, but there arent any console errors

#

but, i will try going faster hold on

swift falcon
#

So I am using this piece of code to move and rotate my VR hands, but I'm encountering an issue that the slowdown once they get really close to the controllers is too large, which results in a sluggish feeling and hands pretty much never being exactly at the controllers' positions. What would be the optimal solution here? I've been thinking about declaring a distance at which velocity's magnitude is instead capped at distance and not distance squared (a bit more complicated to provide a smoother transition but you get it) but wanted to know if I'm perhaps missing some obvious solution

        public void FixedUpdate()
        {
            Vector3 offset = controller.position - transform.position;
            Vector3 velocity = Vector3.ClampMagnitude(_velocitySync * offset.normalized, offset.sqrMagnitude / Time.fixedDeltaTime);
            _rigidbody.velocity = velocity;

            Quaternion rotation = controller.rotation * Quaternion.Inverse(transform.rotation);
            rotation.ToAngleAxis(out float rotationDegrees, out Vector3 rotationAxis);

            if (rotationDegrees > 180)
            {
                rotationDegrees = 360 - rotationDegrees;
            }

            Vector3 angularVelocity = Vector3.ClampMagnitude(_angularSync * rotationAxis * Mathf.Deg2Rad, (rotationDegrees * rotationDegrees * Mathf.Deg2Rad * Mathf.Deg2Rad) / Time.fixedDeltaTime);
            _rigidbody.angularVelocity = angularVelocity;
        }
void basalt
#

you can test if your add force at position is working by adding an absurd amount of force upward @turbid lava

turbid lava
#

yeah that is working

calm talon
void basalt
#

great to hear

hexed pecan
#

Might also need to add a yield return null before it, unless WaitForEndOfFrame can wait until the next frame, I forgot

calm talon
#

still no luck with: cs protected IEnumerator Flash() { print(thisRenderer.color.r); for (int i = 0; i < 12; i++) { yield return null; yield return new WaitForEndOfFrame(); thisRenderer.color = new Color(initialColour.r - 0.7f, initialColour.g - 0.7f, initialColour.b - 0.7f); } thisRenderer.color = initialColour; }

hexed pecan
#

Are you starting it with StartCoroutine?

calm talon
#

yes

hexed pecan
#

Then idk, that should happen after animations at least

turbid lava
# void basalt great to hear

part of the problem still exists of that it is requiring an insane force to accelerate the plane fast enough to actually get that lift

void basalt
#

that's really the only way

#

gotta find the sweet spot

turbid lava
#

i think i have made a few errors with the lift calc which im working on fixing atm

#

but that still leaves the issue of the realistic thrust value is way too much

void basalt
#

again, your thrust and lift multipliers should be completely decoupled

#

they should be two different values

plucky parrot
#

hello there, im having a very strange and weird issue and i hope someone can help me debug it
im trying to instantiate a custom class that derives from monobehaviour
Instantiate(playerPrefab, Vector3.zero, Quaternion.identity, null);
when i put that line of code anywhere, like the Start() method, it runs normally and the prefab appears.
the thing is, when I put that line of code, as it is, or inside a function like the following:

void something() {
// logging "A" and then "B"
  Debug.Log("A");
  Instantiate(playerPrefab, Vector3.zero, Quaternion.identity, null);
  Debug.Log("A");
}```
when executing `something()` inside of the part of the script im going to attach, it prints out "A" but not "B", and thus it does not spawn the prefab.
this is my whole code (the relevant part): https://pastebin.com/xXfMJWkx
line 71: i execute the instantiate function, and before that, i log something to the console; the message does get printed out but it does not spawn the prefab.
turbid lava
#

they are

void basalt
#

that doesn't make sense then

turbid lava
#

they are their own values

void basalt
#

you shouldn't need more thrust to increase the lift internally

#

you should just be able to increase the lift multiplier

turbid lava
#

but using the "real world thrust" converting the enigne hp to newtons with an estimate the in game results are no where near realistic

void basalt
#

forget about using real world values right now

calm talon
#

is there any way in general to make the animator lose out to script in regards to controlling an object's values?

plucky karma
#

The logger will print "A" no matter what.

plucky parrot
hexed pecan
#

If B never prints then you are getting an error in the console @plucky parrot

plucky parrot
#

for instance, to make it more clear: i added a second log after line 71 (code on the paste link) and it doesnt log neither spawns the prefab; but the first one does log

plucky karma
# plucky parrot sorry its an error but you get the point: it doesnt log the second one

At a glance, you're doing this code wrong. You are creating multiple of managers when you should only have one object existing in the game at time. You use gameobject to respond to your game mechanics, not treat it as a singleton entity that has to exist and attached to a gameobject in your game. It wouldn't make sense to destroy your manager when you go back to the main menu or something otherwise. You wanted to make sure your class exist anywhere in your game almost to a static class, but would refrain from that.

plucky parrot
#

where am i creating multiple managers?

plucky karma
#

For new gameobject you created with this script attached, you are going to open a new connection socket on your pc. Your PC can only have one socket open at a time.

plucky parrot
#

the playerprefab is just a dummy object with a script attached and nothing else

plucky parrot
#

that has nothing to do with the error tho

leaden ice
plucky parrot
#

i believe the problem is being caused by the code being ran inside of

#

that

leaden ice
#

You can't do much of anything in Unity in a background thread

plucky parrot
leaden ice
#

Unity will kill your thread if you try to touch anything related to the engine

plucky parrot
#

hmm that explains everything

plucky karma
#

You would need to create a queue.

hexed pecan
#

Does it not throw an error?

leaden ice
#

Nope

plucky parrot
#

now, how can i overcome that? is there any other way?

hexed pecan
#

Or just super silent fail?

leaden ice
#

Unceremoniously kills the thread

hexed pecan
#

No warning?

plucky parrot
void basalt
plucky karma
#

Push new invocation into the queue, then synchronize your queue in your game Update method.

plucky parrot
plucky parrot
void basalt
plucky parrot
#

i tried with a function but i think im not getting the point

plucky parrot
leaden ice
void basalt
#

If I have to elaborate, then you don't need to use multithreading

#

you're just going to slow down your code

plucky karma
plucky parrot
leaden ice
plucky parrot
#

its the first time i do any of these multithreading stuff, i didnt even know that was what i was doing

plucky parrot
plucky karma
#

You would need to use Unity's API calls.

void basalt
#

he's talking about his socket code

plucky parrot
#

my code goes something like this

socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) => {
    // and there is the big function here
})```
leaden ice
#

If you want to listen on a socket there's no avoiding multithreading

plucky karma
#

It's just a lambda expression.

#

The invocation behind BeginReceiveFrom is invoked on a background thread.

plucky parrot
leaden ice
#

Use ConcurrentQueue and TryDequeue it in an Update function somewhere

plucky parrot
#

so i should instead use something else like ReceiveAsync or something like that?

void basalt
#

You should also be avoiding TCP for online games

leaden ice
#

Push things into it from the bg thread

plucky parrot
leaden ice
#

Also don't make a custom network framework if you don't understand multithreading 😉

plucky karma
#

Have you look into other multiplayer package solution, @plucky parrot ?

plucky parrot
#

but i figured i want to make my own since it looks interesting and its not hard (other than that multithreading thing)

void basalt
#

@plucky parrotIf you're encoding with JSON, you're gonna have pretty awful performance by the way

#

when the player count goes up

plucky parrot
#

im currently encoding with plain utf8 strings but i plan to just use bytes

plucky karma
#

What defense do you have to rely on making your own framework instead of using an existing framework altogether?

void basalt
#

strings over a network is going to lead to awful performance

plucky parrot
#

so like the first byte meaning the packet type and the rest just encoded as is

void basalt
#

especially if it's every single message

plucky parrot
#

isnt a byte array the only option?

void basalt
#

You'll have to encode primitives yourself

plucky karma
#

You understand the code well

#

but do you understand how network works?

#

The smaller the data you compress into for network, the better.

plucky parrot
plucky parrot
#

less banana less weight :D

void basalt
#

When you're sending data packets for online games, you should pretty much only be working with numeric types

#

you can have strings for auth

#

and chat messages

void basalt
#

but that's you know, not every message

plucky karma
#

Instead of relying on string, you'd rely on smaller data, They're still Byte, but instead of restricting yourself to say 36 characters, you could just instead use int as "ID" that correspond action to your message.

plucky parrot
#

no but

#

i think im not explaining myself correctly

void basalt
#

If you're not compressing data, you're also going to run into bandwidth problems very fast

#

sorry, my rant is done

#

just letting you know what you're getting into

#

@plucky parrothttps://learn.microsoft.com/en-us/dotnet/api/system.io.binarywriter?view=net-7.0

plucky parrot
#

right now to get it to work i simply converted the byte array into a string to then analyze it, but i want to (after receiving the byte array) analyze the byte array one by one depending on the first byte

plucky parrot
#

the thing is, since i havent started working on that yet, i didnt even know that was how it was called

#

anyways that has nothing to do with my current problem

void basalt
#

If you want to analyze the first byte, just mask it out

#

actually

#

just index into the byte array LOL

#

sorry, adderall wearing off

plucky parrot
void basalt
#

you aren't going to optimize anything with binarywriter

#

you'll need to write your own binary encoder if you want proper compression and performance

plucky parrot
#

ok

#

anyways

#

so how can I not use the receivefrom thing?

#

so instead using something else

plucky parrot
#

how can i do that?

plucky karma
#

Classic X/Y problem then?

  1. Nothing in your example explains where your Debug.Log would print "B".
  2. Avoid multithread framework for networking. There's already firmware that can help you achieve better network connection and
  3. I've already gave you a solution, please look into Queue. Someone already said something better than Queue, but that's in the history.
void basalt
#

I heavily doubt receivefrom is using a separate thread

#

it does, for a fact though, allocate a ton of garbage

#

it's either the send or receive function

plucky karma
#

Doesn't it runs through Json de/serializer?

void basalt
#

No

#

It's not decoding anything

#

just writing bytes into a buffer

#

(as far as I know)

plucky parrot
plucky parrot
#

how would i use it in this case?

void basalt
#

You shouldn't be threading this in the first case.

plucky karma
#

This should be in a thread...

void basalt
#

why?

plucky parrot
plucky karma
#

_Not multi-thread I meant like discord thread my bad 😅 _

hexed pecan
#

Discord thread or cpu thread lol

plucky karma
#

haha

void basalt
#

ah

plucky parrot
#

omg wait i think i got what you said

#

you're a genius!! im going to try what you just told me and im going to be right back tomorrow to try it out

#

good night

void basalt
#

I feel like you didn't understand what we're saying

plucky karma
#

How did you learn all of socket stuff?

plucky parrot
plucky parrot
void basalt
#

if you understood properly, then you shouldn't be using a queue

#

so I don't think you understood

plucky parrot
void basalt
#

Nothing. Just call receiveFrom on the main thread

#

it doesn't use additional threads

plucky parrot
#

but how

void basalt
#

by writing normal code

plucky parrot
#

ooh wait you mean ReceiveFrom instead of BeginReceiveFrom?

void basalt
#

It doesn't matter

#

neither involves multithreading

#

Take a look at the docs if you want to find out how it works

plucky parrot
#

then i am not threading it

#

or am i?

void basalt
#

correct

plucky parrot
#

then whats the problem?

void basalt
#

there is 0 reason to spin up another whole ass core for such a simple task

plucky parrot
#

but then theres no problem XD

#

whats the problem with using a queue?

void basalt
#

I assumed you were multithreading this whole time

plucky karma
#

Right? Really hard to tell him it's a delegate function 🤷‍♂️

void basalt
#

I skimmed over your code

plucky parrot
void basalt
#

so what's the issue again?

#

oh right you were multithreading

plucky parrot
#

XD

#

🤦‍♂️

plucky karma
#

I believe he was trying to invoke instantiate inside the lambda function.

#

but couldn't.

plucky parrot
#

yes thats exactly

#

but it doesnt have to do with the lambda function (as i poorly thought) but it has to do with the inner-workings of the BeginReceiveFrom thing

void basalt
#

you can probably get rid of BeginReceiveFrom and just use ReceiveFrom

#

I haven't used C# sockets in a long time but you shouldn't need begin

plucky parrot
#

o wait

plucky parrot
plucky parrot
#

anyways i think my problem is going to be solved after i apply a queue to my method so thank you a lot guys, i learned a lot today!!

void basalt
#

or you know

#

just stop using beginreceive

#

and use sockets the normal way

#

and stop making issues for yourself

plucky parrot
void basalt
#

You shouldn't need a lambda expression for this

plucky parrot
#

i searched how to use sockets but i didnt understand

plucky parrot
#

im going to search tomorrow

void basalt
#

If you bother scrolling down, microsoft has countless examples

#

In the 3 years I've been messing with low level sockets, I've never had to use a lambda wrapper

plucky parrot
#

wow, you're right

#

it takes the same parameters!!

#

thats crazy, i overlooked that one

#

thank you very much im going to change it then

#

thanks guys ;D

void basalt
#

again, C# sockets have issues with them

#

so eventually gravitate towards a native C wrapper if you care about your project

cunning whale
#

are abstract and virtual methods the same performance-wise?

void basalt
#

at all

#

standard Unity's main CPU bottleneck is the random access pattern

stone echo
#

whats a good way to rotate to look towards a certain object using a rigidbody?

#

i know transform.lookat exists, but i don't want to snap in that direction, i want to turn slowly

void basalt
#

Just lerp over time

#

you're also going to break the simulation by manually setting rb rotation

stone echo
#

im thinking of using rb.moverotation, which won't snap to the object

void basalt
#

still breaks the simulation

stone echo
#

wdym

void basalt
#

your rigidbody isn't going to behave properly when you override the rotation

#

But if you really want to: then lookat, and lerp to it

prime sinew
#

using rigidbody.moverotation seems fine

#

it says it complies with the rigidbody's interpolation setting

#

it's only an issue if you use transform.lookat, isnt it?

void basalt
#

I mean, it really depends what you're doing

#

if you have a character with locked rotation, then yeah

prime sinew
#

usually using the rigidbody's movement functions make it behave with the physics loop nicely

void basalt
#

it would probably be fine

#

thats what I was referring to

prime sinew
void basalt
prime sinew
#

i see

stone echo
#

i guess my problem is i'm not sure how to get the rotation quaternion corresponding to a vector direction

void basalt
#

.eulerAngles

#

that won't be a direction

stone echo
#

o

void basalt
#

just the rotation in euler

#

You already pretty much answered your initial question though

#

just use lookat and lerp towards it

stone echo
#

waht is lerp, i'm unfamiliar with the term

void basalt
#

liner interpolation

#

let me explain

stone echo
#

ah i know what linear interpolation is, just never heard the term lerp

void basalt
#

do you know how to write a time accumulator for it?

stone echo
#

looking into it rn 🙂 seems fairly straight forward, will lyk if i run into issues

void basalt
#

So there's a few different ways to smooth this. Either you can do a continuous interpolation, or an interpolation over like 10 seconds

#

but yeah just let me know if you need help

nova magnet
#

guys help

#

i implemented a pickup system

#

and it works but my gun isnt facing the right way

void basalt
#

so then rotate it the right way.

#

if it's parented to your player then you probably just need the default rotation

#

If not, then you need to store the first person orientation data on each gun

void basalt
#

You know you probably should've mentioned you were using a multiplayer framework

void basalt
#

oh that's just an NPC

nova magnet
void basalt
#

idk what im looking at

#

do you want the local player or the NPC to equip?

nova magnet
void basalt
#

ok so position and rotate it correctly when he picks it up

nova magnet
#

i set the parent object to GameObject under camera

void basalt
#

is what I've been saying

nova magnet
void basalt
#

use local position instead

#

and probably local rotation as well

swift falcon
#
            Quaternion rotation = controller.rotation * Quaternion.Inverse(transform.rotation);
            rotation.ToAngleAxis(out float rotationDegrees, out Vector3 rotationAxis);

            Vector3 angularVelocity = Vector3.ClampMagnitude(_angularSync * rotationAxis * Mathf.Deg2Rad, Mathf.Pow(rotationDegrees * Mathf.Deg2Rad, _angularPower) / Time.fixedDeltaTime);
            _rigidbody.angularVelocity = angularVelocity;

I'm using this piece of code to rotate my hand to the controller's rotaton but once it passes a certain mark in rotation instead of properly rotating the hand does a 360. What bothers me is that this does not happen when I manually rotate the controller in the editor with controllers turned off, and that mark is 90 degrees instead of 0 which I expected to be the point

void basalt
#

@swift falconyeah that's the issue with euler angles

swift falcon
#

wdym

#

I'm not the best with quaternions, kinda hard to get my head around them

void basalt
#

quaternions exist to pretty much solve this problem

#

you can rotate a quaternion using vector3's

swift falcon
#

hmm, I'll look into it

#

I'm using this piece of code to achieve a smooth hand movement and rotation because simply assigning velocity makes them still feel inertia-less

void basalt
#

uhhhh

#

what?

#

is this like VR?

swift falcon
#

yeah

void basalt
#

that doesn't sound right at all

swift falcon
#

wdym

void basalt
#

your hand orientation should be coming directly from hardware

#

is it stuttering or something?

swift falcon
#

...yes, thats whats controller.rotation is. You don't want to directly assign rotation or position, as this will completely prevent them from being affected by other objects and make everything feel fake and weightless

#

your VR hands should not perfectly fit your real hands position at all times

void basalt
#

I mean

#

it should come pretty close

#

otherwise you're going to get motion sick and puke

swift falcon
#

yeah I know

void basalt
#

You should increase the sample rate

swift falcon
#

angularSync should be around a thousand and angularPower should be close to 1

void basalt
#

what you're doing is weird

#

and you probably shouldn't

#

increase the sample rate and interpolate between samples

#

60hz sample rate with interpolation is probably fine

swift falcon
#

...you do realise that this still doesn't help the physics issue?

void basalt
#

I can tell you that manually overriding the rotation of a physics body isn't going to help the physics issue

#

really sounds like your simulation rate is too low

swift falcon
#

I am not overriding rotation, angular velocity

#

uuugh

void basalt
#

the physics engine knows what it's doing

#

it's not going to help to manually override settings like this

#

especially on a VR hand config

#

the problem is that you're sampling and simulating too low

dawn nebula
#

Would anyone know how to make a shader that replicates the behaviour of these color pickers?

#

Or I guess a better question is, "Whats the math behind these?"

swift falcon
#

this won't produce any good results

#

thats the first thing everybody new to VR dev does and it results in either hands that pass through everything or feel completely fake and weightless

void basalt
#

and interpolating between samples

swift falcon
#

by samples you mean...?

void basalt
#

every time your hardware pushes a position and rotation to your computer

#

I don't do VR, so I can't help much more

#

but this is likely your issue.

swift falcon
#

FixedUpdate

#

values are received via OpenXR

void basalt
#

What's your fixedupdate rate?

swift falcon
#

0.009999993, any higher results in clipping when interacting with object

#

pretty much 100hz

void basalt
#

I wouldn't go past 60hz for this scenario

swift falcon
#

I already tried many methods and what I'm doing currently works the best

#

...told you, clipping

#

VR hands move too much

void basalt
#

can you like

#

send me a vid

#

of what the issue is

#

do you have rigidbody interpolation enabled?

swift falcon
#

not now, working through RDP with no physical access to VR itself, manually assigning controller values

#

yeah, interpolation and continuous dynamic

void basalt
#

use MoveRotation

#

and MovePosition

#

when setting orientation

#

wait wtf do you mean working through RDP?

swift falcon
#

...you're the second person suggesting this and it didn't work the first time

#

remote desktop protocol

void basalt
#

I mean yeah no shit it's gonna feel fuzzy

swift falcon
#

that's right now

#

I was working from my main PC and using the headset itself yesterday

#

I am not that stupid, just can't send it right now

void basalt
#

by clipping, you mean stuttering around?

#

or going through objects?

swift falcon
#

objects going through/into the hands when you try to interact

void basalt
#

That's gonna happen no matter what if we're setting physics body orientation manually using position and rotation

#

100hz simulation rate isn't sustainable

#

it's gonna cause you issues later on

#

so yeah setting velocity and angVelocity might be the only way

#

Try just doing the velocity for position, and then set the rotation itself

swift falcon
#

yeah I'm using somewhat similar to set velocity

#

it works just fine

#

smooth-ish enough to feel real, affected by other objects and their mass, but the difference is small enough to not cause any motion sickness

swift falcon
#

helps a lot with motion sickness

#

disableable ofc

void basalt
#

Yeah I've never used VR before

#

if it works, it works

#

you could also

#

have a visible hand, that just instantly snaps and interpolates between fixed updates

#

and then a ghost hand

#

with an underlying rigidbody

#

you'd probably get a lot of visual clipping tho

swift falcon
#

yeah clipping is the main issue

#

VR design isn't as hard, its just important to put everything into accessibility options, motion vignettes and ghost hands help new players but are extremely annoying to veterans who don't feel motion sickness at all

#

I'll post videos once I get back to my PC

#

I can't understand why the flipping point is 90 degrees, it would've made sense if it was 0

void basalt
#

I mightve been wrong

honest bane
#

Hi, guys

swift falcon
#

I tried

if (rotationDegrees > 180)
{
    rotationDegrees = 360 - rotationDegrees;
}

but it obviously didn't help at all because the flip angle is 90, not 0

#

in case it flipped to 359 instead of -1

void basalt
swift falcon
#

thanks, I'll check it out

void basalt
#

sounds like that's your issue

#

AngleAxis

swift falcon
#

hmm, its similar but doesn't help much.

            Quaternion rotation = controller.rotation * Quaternion.Inverse(transform.rotation);
            rotation.ToAngleAxis(out float rotationDegrees, out Vector3 rotationAxis);

I think the issue is in my rotation formula

void basalt
#

yeah I wouldn't know

swift falcon
#

thanks for the help

coral kettle
#

anyone know of an existing library of custom gizmos? like arrows and other weird shapes

hearty sphinx
#

When do you use abstraction and when do you use aggregation? I heard game devs prefer aggregation. I found myself preferring it when I did something related to tile types and methods

cold parrot
coral kettle
#

thanks!

cold parrot
hearty sphinx
#

Yes yes that

cold parrot
hearty sphinx
#

Is there a downside to only using composition

cold parrot
hearty sphinx
#

Thanks

cold parrot
# hearty sphinx Thanks

When using composition it is common to inherit only from interfaces and abstract classes and only ever inherit once. It can make sense to do more generational inheritance if you build an engine for something (eg unity’s MonoBehaviour ancestors) but generally those ancestors should be quite simple and semantically well thought out with close to zero reason to ever change

#

If you write code that is expected to change, use composition.

hearty sphinx