#archived-code-advanced

1 messages ยท Page 60 of 1

sand acorn
#

Alright, I will, thanks!

bleak citrus
#

in case you're curious: a ref field on a class doesn't really make sense

you need to make sure that the ref never becomes invalid, but it's very hard to prove that a heap-allocated object's lifetime is finite...

sand acorn
#

I have seen this happening on my code when compiling / saving changes , it doesnt happen during play mode, my native arrays are being disposed on destroy, any ideas?

#

cant quite remember if this happened in the previous version I was using , I think it wasnt so maybe its a bug?

bleak citrus
#

well, try turning on that diagnostic flag :p

#

it's in the Jobs menu

sand acorn
bleak citrus
#

wait, where is that dang thing

#

i wonder if it's actually this guy here

#

JobTempMemoryLeakValidation

#

user settings, Diagnostics

sand acorn
#

I even enabled job stack traces and there is nothing

#

the error magically disapeared

#

Oh wait it suddenly appeared

#

I think this is happening because I am using a plain C# class instead of a monobehaviour, the stack trace points me to part of the code that should only happen during play mode

opal mural
#

Hi guy's

#

new person here

opal mural
#

no I meant new person in this discord group

#

been using Unity for past 3 years

#

actually I had been searching such find of discord channel

#

because of my college project, which is multiplayer FPS android shooter

#

please have a look in this video

#

so my move joystick is getting stuck at the last position as soon as I am pressing the shoot button

#

I tried adding them in there own separate canvas's, but this problem is still here.

tropic vigil
opal mural
#

this is my input managaer script

#
using UnityEngine;


namespace HOTTEA
{
    public class InputManager : MonoBehaviour
    {
        private static InputManager _instance;


        public static InputManager Instance
        {
            get
            {
                return _instance;
            }
        }

        private PlayerControls playerControls;

        private void Awake()
        {
            if (_instance != null && _instance != this)
            {
                Destroy(this.gameObject);
            }
            else
            {
                _instance = this;
            }
            playerControls = new PlayerControls();

            Cursor.visible = false;
        }

        private void OnEnable()
        {
            playerControls.Enable();
        }

        private void OnDisable()
        {
            playerControls.Disable();    
        }

        public Vector2 GetPlayerMovement()
        {
            return playerControls.Player.Movement.ReadValue<Vector2>();
        }

        public Vector2 GetMouseDelta()
        {
            return playerControls.Player.Look.ReadValue<Vector2>();
        }

        public bool PlayerJump()
        {
            return playerControls.Player.Jump.triggered;
        }

        public bool PlayerExit()
        {
            return playerControls.Player.Exit.triggered;
        }

        public bool PlayerShot()
        {
            return playerControls.Player.Shooting.triggered;
        }
    }
}
#

this my player controller script

#

this is my fpscontroller script

tropic vigil
# opal mural no i might not

When you press mobile device in several places several touches are registered. Some inputs like Input.mousePosition return the average position of all touches (e.g. the center of your screen will be returned if you press left and right sides of your phone at the same time). When designing an app with a UI like yours it's necessary to check if each input is interpreted properly.

opal mural
opal mural
#

kind new to android game development

tropic vigil
# opal mural so how do i do that ?

Here is a tutorial for using touches in the new input system:
https://www.youtube.com/watch?v=4MOOitENQVg

๐Ÿ“ฅ Download the Source Code ๐Ÿ“ฅ
แ…https://www.patreon.com/posts/75112992

๐Ÿค Support Me ๐Ÿค
Patreon: https://www.patreon.com/samyg
Donate: https://ko-fi.com/samyam

This video gives an overview on how to use Touch from the new Input System through Input action assets and the PlayerInput component, how to simulate touch in the editor game view, an overv...

โ–ถ Play video
opal mural
#

thank you will check this one out

fleet shell
#

I do a sphere cast in unity to detect the ground the player is standing on. When the player stands on the edge of a cube, the normal that is returned is not facing up. Instead, it is facing between the normals of the edge's faces. Since I'm using the ground normal to decide whether the player should slide off the surface or not, the player ends up slipping of the edge.
Does anyone know how to get the normal of the face?

In unreal, when you do a cast you get a "normal" and an "impactNormal". One represents the interpolated normal while the other represents the normal of the face at the point of the impact. Maybe there's an equivalent in unity?

dusty wigeon
hushed sparrow
#

So I've got an abstract class for a WorldObject, which can be stored in a Tile class as an Occupant. However, when I run this function that goes through the list of tiles for if the occupant is null and adds the occupant to a list if its not, its coming up with an error that states "Object reference is not set to an instance of an object". whats going on here?

#

from what i can tell its saying that a variable, which should have been set to have an instance, is null for some reason

sly grove
sly grove
hushed sparrow
#

but why would it be null? Its a List variable, its there!

#

its just saying its not there despite it being there???

#

and its giving me this same exact error message when other scripts call upon it, its just saying that its not there?

#

why would it not be there if its a variable that exists? why would it say it doesnt exist?

#

this gives the same exact error

sly grove
#

it's a reference to a potential list

hushed sparrow
#

this is what its saying is null

sly grove
#

it has to to be assigned to an actual List object

sly grove
hushed sparrow
#

i see

sly grove
#

Again you have a reference variable. It needs to be assigned to an actual object otherwise it's null

#

Note that Unity makes this somewhat confusing for beginners, because if the list is serialized Unity will create it for you automatically

hushed sparrow
#

that

#

that fixed it

sly grove
#

Also for future reference, NullReferenceException is the most common error people encounter in C# and it's really a #๐Ÿ’ปโ”ƒcode-beginner question

hushed sparrow
#

i am flabberghasted

#

i see

timber flame
#

Suppose if a building is completed, you should change and update some stuff. Some of them are related to that building itself and the others are not like levelup, etc.
There are many ways to handle and manage it but I would like to know your approach. What do you think? Which one is more flexible and elegant, cleaner and modular?
When a building is completed, the list of jobs you should apply in your game is

  • The progress bar and icon should be hidden

  • The building model should change and be updated

  • play an SFX

  • play a particle effect

  • Levelup and increase xp

  • play a builder's animation

  • etc.

1- Pure event system. All components and systems listen to an event (here BuildingCompleted event) and update themselves
2- One specific class handles the procedures after completion of building by calling methods of those systems and components.
3- The mixture of them. In the building gameobject, there is a specific class to handle all changes related to that building (model, particle effect, sfx, progressbar, etc.) and for external systems, they listen to that completed event and ...

hasty monolith
#

Hello, I'm working on an player stats system and I'd like to leverage SOs but not sure how to achieve what I have in mind.

I have a class for storing player bonuses such as:

public class ProfileManager : StaticInstance<ProfileManager>
{
    public float MiningExperienceBonus;
    public float MiningSpeedBonus;

Other scripts are referencing this class to know how much xp to give etc.. And bonuses can come from different sources (items, tech tree, ...)

Is there way to have a scriptable object like this that could somehow apply a bonus to a desired stat, without hardcoding the reference like this ProfileManager.instance.MiningExperienceBonus += value

public class Bonus : ScriptableObject
{
    public string description;
    public float value;
}
timber flame
#
public class Bonus : ScriptableObject
{
    public BonusType Type;
    public string description;
    public float value;
}
hasty monolith
#

yeah but I'm trying to avoid using an enum by using SO's

#

cause I might add and delete bonus types a lot and from experience, that gets messy quickly with enums

timber flame
#

Then for example for items, you can get all bonus with type Item and then add them together + item.value

hasty monolith
#

maybe I should just use a Dictionary<Bonus, float> in the profile manager instead ? and have a method within the SO to find the key in that dictionary and increment its value ?

hasty monolith
#

like an item that gives +5% mining experience and +10% mining speed for example

timber flame
#

Your player listen to picked up event, then get the collection of bonuses

// player class
 Dictionary<BonusType,int> _bonusDictionary;
public void OnItemPickedUp(Item item){
   var bonuses = item.GetBonusCollection();
   // update bonusDictionary based on.
}
#

In a loop

   _bonusDictionary[type].value += bonues[type].value;

When an item is dropped, it is the opposite one, subtract it

_miningSpeed + _bonusDictionary[BonusType.MiningSpeedBonus]
hasty monolith
#

Yeah that give me the following idea actually:

public class ProfileManager : StaticInstance<ProfileManager>
{
    public Dictionary<string, float> bonuses = new();
}

And the SO as follows

public class Bonus : ScriptableObject
{
    public void ApllyBonus(float _float)
    {
        ProfileManager.instance.bonuses[this.name] += _float;
    }
}

And the item can then have a dictionary of Bonus SO's with values

#

I could even initialize the dictionary in awake by doing a Resources.LoadAll<Bonus> to fill the dictionary automatically based on bonuses

timber flame
#

Yes but it is more elegant to change the direction of dependency

hasty monolith
#

so it makes it pretty much fool proof

timber flame
#

Bonus should not depend on anything

hasty monolith
#

ah you mean to do it the other way around so that ProfileManager fetches the bonuses ?

#

like a foreach var item in PlayerEquipment add bonus from item ?

versed coyote
#

How can I emit a Space key press manually via code?

dusty wigeon
#

It can take the form of a function or a something like a buffer.

waxen adder
#

Can someone explain why this => is used

[SerializeField] private InventoryItemData itemData

Then just 3 lines down you have this

public InventoryItemData ItemData => itemData

My first question is why does it have the => sign but also why have the exact same variable just different capitalization and use it interchangeably

dusty wigeon
waxen adder
dusty wigeon
#

By doing so you:

  • Increase Readability.
  • Increase Maintainability.
waxen adder
#

So how do I know when I switch between using the field and the property

dusty wigeon
#

You always use the property when accessing the field from the extern. For the intern, it is more of a style code question.

waxen adder
#

So the article says it just returns the value of it so does that mean ItemData now inherents from itemData

dusty wigeon
#

There is no inherents.

#

The [=>] is a like a lambda.

#

You could do:
public InventoryItemData ItemData => MyFunction()

#

Where MyFunction() return an ItemData

#

Do not overthink it, it really is just a different syntax for defining a property.

waxen adder
#

For me it is the difference between knowing what something is and knowing when to use it

dusty wigeon
#

What it is:
It is a way to define a read only property.
When to use it:
If you have a property that do not need to be set. (It really only a preference as there is other possible approach)

austere jewel
#

It's just a getter. This really isn't an advanced coding discussion

waxen adder
#

Sorry I should have just went to code-general

#

@dusty wigeon Thanks for the help

tidal breach
#

Hello! I wanted to ask something about Photon 2
I've been using it with Low Poly Shooter Pack 4.3.1 and so far it's worked like a charm, the only thing is that i can't figure out how to make the 3rd person models work. For example: One player can view another's player full body model and animations, weapon changes, jumping, crouching, etc.. But I can't see his first person model. Same thing goes for the other player. I need help on making this work

#

In case it's difficult to understand, currently if there are two players on the game scene, neither of them can see a full body model. they just see oddly tall floating hands

sand acorn
#

Hello there, does anybody have an example of using the MeshData API and procedural meshes? I could only find examples made for imported models and not on job system

astral onyx
#

can anyone tell me what this means "ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
"

#

i swear to god this error has been screwing my game for literally a week now

devout hare
#

Not an advanced issue but it means you're trying to access an element that doesn't exist in an array or list

astral onyx
devout hare
#

Log the array/list length and the index you're trying to use

astral onyx
#

how do i do that

devout hare
#

...

#

Which part do you not know how to do?

vapid rapids
#

Do a bounds check and have the program spit out info to the console when you attempt to access an out of bounds value

astral onyx
#

ill try solving it on my own

#

ive been trying to do it since 4am

plush hare
#

@astral onyxThere's one way to solve it and it requires checking if you're in bounds within bounds of the size of the array

#

If you can't do that, then you need to understand how arrays work.

astral onyx
#

Alr

plush hare
#

@astral onyxhttps://www.w3schools.com/cs/index.php

astral onyx
#

i actually solved the problem , turns it it was just one sneaky typo

plush hare
#

For future reference, that's not an advanced problem. You should also stop copying stuff from youtube.

astral onyx
#

i had multiple lists and when trying to transfer objects some objects from one list went into another

#

and it all went downhill from there but i managed to fix it

plush hare
#

When you want help next time, you also need to paste code.

astral onyx
#

understood

hardy sentinel
#

if I wanted to make TMPro.TextMeshProUGUI text selectable, so I could select the text in ways I can select text outside Unity, how would I go about it?

#

selectable as in like this:

orchid marsh
#

Mark

hardy sentinel
scenic forge
delicate tinsel
#

does anybody know what is going on here?

#

it says its this line of code

#

restarting unity didnt help

fresh salmon
#

You need to configure VS so it highlights errors in the code for you

#

!ide

thorn flintBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

fresh salmon
#

The bot message just above has links

delicate tinsel
#

i guess i am stuck

#

i literally work for every step soooo long, cause it has so many errors always, this network untiy thing ๐Ÿฅฒ

fresh salmon
#

Having a configured code editor is required to get help here

#

Please proceed with the configuration now

delicate tinsel
#

which link should i press from these 5 above

fresh salmon
#

Well, think about it for a momemt

#

What code editor are you using? That will eliminate 3 links out of the 5

delicate tinsel
#

Microsoft Visual studio

#

ou wait... i have the thing but its only not showing in this script i dont get it

#

i get red underlines where the code has problems usually

#

see

#

I dont even know why this code is poping up, i dont have this anywhere implemented this script

fresh salmon
#

Do you have your own class named NetworkManager per chance? It might be picking up yours instead of the one in whatever networking stack you're using

delicate tinsel
#

I dont have any NetworkManager script or Object

fresh salmon
#

Then your package failed to install properly. Close Unity, go to where it is on your computer, and remove the Library folder. Start Unity again and it'll regenerate the folder

delicate tinsel
#

Alr. il try that out. Thank youUnityChanThumbsUp

#

sadly it happend the same again way

#

but when i delete the package everything works, but when downloaded again it stops working again ๐Ÿ˜ฆ

fresh salmon
#

Maybe that package depends on another one you don't have? If you're following a tutorial make sure you have everything

delicate tinsel
#

Its the only thing thats beeing done and for me it makes 0 sense why this is even poping up this code. This Code looks correct for me

#

But its like it isnt even connected with unity, something is just broke

#

What is even SceneLoaderWrapper?

#

Alr. i found something.

#

So after a make these 6 lines of code into a Comment. Everything just starts to work normally

#

i really dont know what the problem is, whatsoever, everything works now and i see no problems in the game while playing with other people. It probably is important in some way but if it doesnt affect me then i am fine

orchid marsh
delicate tinsel
#

Ou, so you mean it doesnt get information. I see

#

But, in which way would this help me? Where do i need to know these things.

orchid marsh
#

Those lines of code subscribe functions that you've implemented (hopefully it was your code and not randomly copied stuff) and unsubscribe them on destroy.

#

An error would likely be generated if those functions were missing.

delicate tinsel
#

This is not my code. This is the code that you get after you download the package from unity, for network purposes

orchid marsh
#

Commenting them out would remove the errors but not do whatever it was meant to be doing.

delicate tinsel
orchid marsh
#

You're likely missing a dependency

delicate tinsel
orchid marsh
#

Something that the code you're using needs that you don't have.

delicate tinsel
#

mhm, i see

#

It could be. But i dont know how to find what is missing

#

i needed this package because of this:

#

So other players could see the changes from other people

orchid marsh
#

I can't help you either as I've got no clue what your project consists of.

delicate tinsel
#

Il just go on with commenting these 6 lines of code, and if there should be any kind of problems in the future then i guess il need to find out what it is.

orchid marsh
#

If you are following a tutorial, you've likely missed a step else your project is missing a package or wasn't properly installed etc

delicate tinsel
#

I first had the problem that my unity didnt want to download the package trough the git link, and then i played something in the settings and then it worked. But maybe it has now problems downloading everything??? It could be, but i guess we will never know

#

And that problem took me over 1 hour as well. Thats why i am a bit frustrated

brave spruce
#

I can't find a solution from googling, but does anyone know how to implement a walls disappearing depending on rotation perspective in an isometric game? Video attached of problem. I'd like to have the close side wall disappear when the user is viewing.

#

I'm being dumb - long day. I just need to implement a script that checks rotation.y of the camera and if certain value turns off the mesh renderer

#

Ignore me

#

using UnityEngine;

public class WallViewRemove : MonoBehaviour
{
    public float[] anglesToHide; // The list of angles to check against
    private MeshRenderer meshRenderer; // The Mesh Renderer component of the attached wall object
    public GameObject mainCamera; // The main camera in the scene

    private void Start()
    {
        meshRenderer = GetComponent<MeshRenderer>();
    }
    private void Update()
    {
        // Get the rotation.y of the mainCamera
        float cameraAngle = mainCamera.transform.rotation.eulerAngles.y;
        Debug.Log(cameraAngle);

        // Check if the cameraAngle is in the anglesToHide array
        bool isHidden = false;
        foreach (float angle in anglesToHide)
        {
            if (cameraAngle == angle)
            {
                isHidden = true;
            }
        }
        // Set the wall to be visible or invisible depending on the camera angle
          meshRenderer.forceRenderingOff = 
isHidden;
    }
}

``` if anyone wondered.
sage radish
brave spruce
sage radish
magic flare
#

I love ReSharper so much

mellow plinth
#

Does [BurstCompile] honours [MethodImpl(MethodImplOptions.AggressiveInlining)]?

sage radish
proud iris
#

I am wanting to make sure. Are Unity compiled games able to run via the command-line and if so, do all print statements and variants of Debug.Log output to the command line?

dusty wigeon
proud iris
dusty wigeon
proud iris
#

I see. Is there a way to output a message to the command prompt if the game is ran from it?

dusty wigeon
dusty wigeon
#

If you explain what you are trying to do we could maybe suggest other alternative.

proud iris
# dusty wigeon If you explain what you are trying to do we could maybe suggest other alternativ...

I am creating an online multiplayer game. I am making it a Client-Server architecture with players able to utilize the Dedicated Server build to host their own servers. I seen popular games, such as Rust and Unturned, output messages into the Command Prompt when running in Batched mode. I am hoping to find a way to utilize that logging feature to print messages to the Command Prompt / Command Line for players who are hosting servers.

dusty wigeon
plucky trellis
#

I have a camera controller script with a large number of values, and I would like to be able to swap them at runtime, ideally with some way to restore defaults. (eg. entering a scripted sequence which involves a clamped camera angle) I have considered scriptable objects to store the camera data, but can't find a good way to copy the data from those scriptable objects into the fields of the script without hard coding every property I want swapped.

#

Is there a good way to do this?

frank socket
#

Hey, I'm currently profiling the server build for my game (so no graphics) but for some reason WaitForTargetFPS is using 30+ms. I know that WaitForTargetFPS usually means VSync, but I'm confused on why that would be happening on a server build. I have disabled VSync within the quality settings and set Application.targetFrameRate to 0 but still with no luck. What's weird is that it only occurs on the server build and not the main client build? (which has graphics). My Unity version is: 2021.3.15f1

dusty wigeon
dusty wigeon
dapper cave
dusty wigeon
dapper cave
dusty wigeon
dusty wigeon
austere jewel
#

Debug.Log is not stripped ๐Ÿค”

dusty wigeon
#

You can exclude them from being reported though.

dapper cave
austere jewel
#

I have no idea what those mean. Though I don't use autosave

magic flare
#

Rider is the best out of everything imo

#

The only thing that I wish it did better is other minor IntelliJ-family features like rendering documentation comments inline and stuff.

#

Rider is a godsend

#

autosave always works for me. I'm on 2023.1.1

dapper cave
magic flare
#

have you tried factory resetting your preferences

dapper cave
#

physics interpolation happens when? it's not in the life cycle graph

dapper cave
magic flare
#

hmm interesting

#

are your laptop and desktop on two different operating systems?

slender cradle
#

Hello I am trying to find a way to use ECS for a topdown game with Unity, as currently I can not get more then 1.5k enemies to spawn with rigidbodies and collision, most tutorials no longer work with the current version of ECS, is there any any tutorials or guides for how to set up a basic ECS system for the current version of unity and ECS?

dapper cave
#

11 on the laptop

slender cradle
bleak citrus
#

bah, the "tanks" tutorial link is broken

#

I used this to get to grips with the ECS. It was extremely helpful.

#

wait, this has gotten rephrased a fair bit since I used it...

#

i'm pretty sure it used to have way more step-by-step content

#

ah, yes, it did

#

this is from before Entities 1.0.0

#

so it may no longer be accurate

slender cradle
#

Yeah I ended up following the 1.0 manual, got some entities to spawn, honestly still quite lost mainly due to all the new syntax and also the entity hierarchy system, I think I have the basics, it seems as though the last update to the project you posted was 4 months ago so I think most of it still fits, I will download it and see how they have set it up

slender cradle
#

well managed to get a few thousand spawned, albeit in the same spot/location, now to try and figure out how to get the entities to move, as spawning them with a basic enemy script doesn't seem to make them move.

bleak citrus
#

it's been a half year since I really dug through the system

bleak citrus
#

e.g. it finds every entity with a "movement" component and a "transform" component and moves them forward a little

#

this is ultra-efficient because all of the entities are grouped by what components they have

slender cradle
bleak citrus
#

components are generally single-purpose

upbeat path
#

or you just dump the lot and write your own. This has 2 major benefits

  1. It will work
  2. It will not change randomly
bleak citrus
#

they describe an attribute of an entity

upbeat path
#

ECS

bleak citrus
#

given that the Entities package is now up to a 1.0 release, it might be a ~little~ less turbulent

slender cradle
#

I just want a system to spawn 3000 enemies with rigid bodies for 2D top down game, have written a game in Godot and could not get it too deal with anything over 1500 rigid bodies, only thing in terms of game engines I have seen do what I need to do is this ECS and DOTS systems, but I am not really a great coder

upbeat path
#

Dream on, this is Unity. They have not produced a decent subsystem in the last 6 years that they have not consistently broken

slender cradle
#

yes I noticed from a fresh build using a 2022 version of unity and installing the packages I get all types of errors, quite odd to have official packages be broken from fresh install/builds, but currently there is nothing else on the market I can use besides really obscure things like Rust Bevy engine

compact ingot
bleak citrus
#

assuming all agents talk to all agents, at least

#

a good physics system will efficiently handle collisions between them

compact ingot
#

well, complexity is a space, its not whats actually happening, hence "depends on the specifics"

#

and what a "good physics systems" can do is still is bounded by the desires and ability of the programmer

#

there is no magic way to solve N:N collisions

slender cradle
#

nothing to crazy, just basic collision between each other and the ability to have them push each other around, but yeah having it iterate using a loop through each enemy makes it hard, considering from the performance tests I have seen I am hoping the ECS will be just enough as Godot almost got there with only minor changes( I used its internal API for physics and rendering not the scripting language version)

compact ingot
bleak citrus
#

the entire point of a physics engine is to efficiently solve collisions between many objects

#

they do a pretty darn good job of it, too

#

rejecting most impossible collisions and then testing just the ones that might actually have happened

compact ingot
#

if you have a mass of colliders that can all push each other and are in contact, you quickly run out of iterations in the solver

#

and there is just no way to fix that, its inherently a computationally hard problem

#

there are other ways to solve it, for example via tensors or flow simulation, boids (steering/avoidance) etc. but not via generic collision depenetration

slender cradle
#

I'm just trying to make a horde survival game with alot of enemies, set myself a goal of 3000 enemies who knew it would be this difficult lol

compact ingot
#

i'd say you should be looking at a steering/avoidance approach via entities, not via physics

bleak citrus
#

yeah, I see what you're getting at

slender cradle
#

yeah I think so, I mean I don't need them to simulate physics 1:1 but just the illusion aka certain weapons can push them

compact ingot
bleak citrus
#

if you just pile up 3,000 rigidbodies, you might get very wonky behavior

slender cradle
#

unity can handle about 2000 before it starts getting weird, just with a basic set up, no ECS or anything like that, with an enemyController that controls them all

compact ingot
#

yeah, if your agents are simple and have no physics, you can update 3k gameobject positions each frame

slender cradle
#

how would I want to go about the collision between them? I don't want them to pierce through each other

compact ingot
#

steering and avoidance

slender cradle
#

as in they don't have colliders, they just stop moving if they are going to hit and if they do hit they move out of each other ?

compact ingot
#

you can never solve the collisions perfectly, so you need an approach that produces an acceptable result, cowd simulation is one

compact ingot
#

you'd do this iteratively, updating all of them each frame

#

this then creates emergent crowd movement

bleak citrus
#

"data oriented design" generally means that you pack data for many things together

#

instead of having 3,000 random objects on the heap

#

this is a big part of what makes the whole ECS performant

slender cradle
#

yeah this is similar to the system I made in Godot, it just wasn't very performant using c# with godot so I switched back to unity , quite a big difference in terms of complexity of the system I was using though

compact ingot
#

there is this tutorial which seems to deal with the basic idea https://learn.unity.com/project/crowd-simulation

Unity Learn

In this project you will be working with a high number of agents to simulate crowd behaviour. You will discover how patterns of movement can be formed from the simpliest of rules that mimic crowd behaviour in the real world. By the end you will have created a crowded city street scene with humanoid characters walking along a pavement and avoid...

slender cradle
#

so instead of Rigid Bodies I would be using kinematic bodies in essence ?

bleak citrus
#

neat, I'll need to look into that at some point

slender cradle
#

well here is 10k easily spawned enemies, bit of a problem with the movement though lol, seems to only be moving the most recent creation slightly

bleak citrus
#

you have a few errors there...

slender cradle
#

yeah they been there before I even started coding so I just sorta accepted them as part of base unity

bleak citrus
#

pretty sure this one isn't, though...

slender cradle
#

oh yeah thats just the counter, theres probably around 5 or so to do with me and not the base packages and how they work with each other/obscure project settings not tuned from default, but currently none of them seem to break any of the code I am writing so no point wasting time on fixing something I might not even be using in 30 minutes from now lol

#

its funny cause it says it cant read from it but it still does anyway

urban trout
#

Hello, im with a metroidvania project, i want scale x * -1( scale X = 5 * -1 = -5) but dont function, someone can help me ? (https://dontpad.com/Metroid for the complete code)

bleak citrus
#

you just asked this in another chat

#

please do not cross post

tired fog
#

Hello

#

What would be the best way to schedule dispatch calls of a compute shader so that there's only one or two running at the same time?

#

I have to dispatch a compute shader, let's say 100 times, I would like to do it in packs of 5, so that the GPU stays busy, but not with memory overload

#

Not sure how could I schedule them, like in a queue or something

uncut burrow
#

Is there any way to make multithreaded prefab spawn? Main threaded instansiating gives me freezes and fps drops.

compact ingot
uncut burrow
#

thanks

stiff hornet
uncut burrow
#

ima just record a vid.

stiff hornet
#

it's a yes or no question lol

#

if it's yes, then do pooling

uncut burrow
#

i am spawning but not destroying

#

rooms that are not in range are just being disabled

urban trout
#

Okay, I want the player to face the other way; he's looking this way and he keeps looking in the same direction even when I press the button to go the other way, do you understand?

rough bolt
#

For JSON parsing in C#/Unity, do you have to explicitly define the class you want to parse into? I'd like to be able to handle any arbitrary data, but it seems like that isn't possible?

compact ingot
rough bolt
#

For example my websocket schema is usually:

{
  "type": "CharacterMoveEvent",
  "data": {
    ...
  }
}```
where the message gets routed based on type
scenic forge
#

Looks like a discriminated union to me.

compact ingot
rough bolt
compact ingot
#

Basically what you have there with your type annotation and untyped data field

scenic forge
#

Json.NET should have support for DU since it's pretty prevalent in web API.

#

But if not you can always just do your own primitive version of it with JsonUtility.

urban trout
#

I want the player to face the other way; he's looking this way and he keeps looking in the same direction even when I press the button to go the other way, do you understand?

rough bolt
#

using Newtonsoft.Json; doesn't seem to work?

thin mesa
rough bolt
#

The type or namespace name 'WebSocketEvent' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp] I don't quite know how namespaces work in C#/Unity

#
{
    public abstract class WebSocketEvent
    {
        public string Type { get; set; }
    }

    [Serializable]
    public class MoveEvent : WebSocketEvent
    {
        public string CharacterId { get; set; }
        public Vector3 TargetPosition { get; set; }
    }
}```
#

using WebSocketEvents; should work right?

compact ingot
thin mesa
rough bolt
rough bolt
thin mesa
thin mesa
#

is this error only showing in vs code or do you see it in the unity console as well

devout coyote
# rough bolt

Are you sure that websocket events are in the websocketevents namespace?

#

Your websocket client doesn't seem to be in a namespace

rough bolt
devout coyote
#

Sometimes you also have to let unity reload for it to find new types

#

Esp in vscode

#

Also can't you get vscode to automatically add the using when you are attempting to use the type?

#

Unsure if it matters but your client is not in a namespace either

rough bolt
thin mesa
devout coyote
#

Ide misconfigured

rough bolt
#

it is showing up in unity too though

#

ah ok, restarting seemed to fix it

#

strange

scenic forge
#

Is your player made our of two semi circles and a rectangle?

#

If so, just split the screen to those three parts and the rest just some simple geometry math.

timber flame
#

What is the best way to render a lot of icons in screen space unity UI?
Using a canvas causes awful giant spike when moving camera (icons should move as well, set the position)

timber flame
#

When using anchoredposition and set it, it is OK but when setting anchored max and min, it causes spike

tired fog
#

Im gonna send it again since it got lost

#

What would be the best way to schedule dispatch calls of a compute shader so that there's only one or two running at the same time?

#

I have to dispatch a compute shader, let's say 100 times, I would like to do it in packs of 5, so that the GPU stays busy, but not with memory overload

#

Not sure how could I schedule them, like in a queue or something

#

I tried using a graphics fence, but I'm running other compute shaders, that don't need scheduling, that would trigger the fence too

untold moth
#

Afaik, a dispatch is a blocking call, waiting on the CPU for the GPU to complete it's work.

#

There's an async dispatch that would queue the dispatches for execution asynchronously without blocking the CPU. I don't remember the exact API though.

tired fog
#

Okay, so what I would like to do then is to dispatch less compute shaders, so that the cpu stays less blocked, process a frame, and then run the other ones

#

An async dispatch would not stall the CPU?

untold moth
tired fog
#

Mmmm, then it wouldn't solve the issue. I would like to spread them in multiple frames. But wait, I'm having the same convo in #archived-shaders, let's talk there

untold moth
#

I think it's called AsyncGPUReadback

slender cradle
#

How would someone go about adding a physics collider to a enemyPrefab that is being created and controlled by an ECS? I can make them spawn and follow the player but I have yet to figure out the correct way to add collision onto them, like a rigid body.

uneven ermine
#

ive been using navmesh but the navmesh agent variables arent doing anything. I'm trying to make the agent not slow down when getting near to the destination using:

navMeshAgent.stoppingDistance = 0.0001f;

and i set auto braking to false but the agent still slows when near the destination... Can anybody help me fix this?

#

i want it to move at the same agent.speed

#

right until it hits the target destination

#

im changing the agent.speed and agent.acceleration in code every once in a while

#

i set acceleration and speed to the same value all the time

prime moth
#

Is Someone Into States MAchines

signal moth
#

I'm making a unity 2D game with ragdoll physics. The game revolves around a stickman which is able to aim weapons, where the weapons rotate towards the mouse position. An example issue I'm facing when aiming a weapon is that if the mouse is quickly moved from the right, then over the player ending in the left side of the screen, the player's rotation will be calculated wrong, resulting in the players arms being bent, no longer following the mouse correctly. How can this issue be resolved?

Attached is a video demonstrating the issue, as my articulate skills are not the best
For more information feel free to ask
Please @me

dusty wigeon
signal moth
#

I have tried adding a deadzone, where if the mouse enters the players center, the arms will simply stay at the last rotation. But this doesn't solve the issue for some reason...

dusty wigeon
#

And why does it not solve the situation ?

signal moth
#

How would I know? Perhaps the code is wrong

dusty wigeon
#

If you do not, then you need to work to know.

signal moth
#

Well I did some debugging by drawing the mouse position with gizmos. And seems the issue is that if the mouse position is on the right and you move it cross the center of the player, the position kinda just teleports to the other side, causing the limbs to move fast in order to reach the target making the issue occur.

dusty wigeon
signal moth
#

I have tried that without luck

#

This is how I move the arms: ```csharp
if (armsActive)
{
Vector3 difference = Target - (Vector2)transform.position;
float rotationZ = Mathf.Atan2(difference.x, -difference.y) * Mathf.Rad2Deg;
rotationZ += rotationOffset;
lastRotation = rotationZ;

        rb.MoveRotation(Mathf.LerpAngle(rb.rotation, rotationZ, speed * Time.deltaTime));
    }
#

If the speed is too low, his arms will simply rest along his body and he wont be able to hold the weapon up

dusty wigeon
#

@signal moth

Anyway, we cannot continue this as it is an advance channel. If you want more advance on how to debug, feel free to reach for #๐Ÿ’ปโ”ƒcode-beginner or #archived-code-general. I doubt there is anyone here that could directly help you with your issue, you probably know more on your problem then all of us. However, If I were you, I would try to come up with a better idea to make your character walk/aim. I would look how we can couple Animation and a Ragdoll. (Have something of a lerp between both, like an Additive Animation). This way, you would have a better control on your character. With luck, you might even solve your issue.

I tried to find some resource, but it seems there is a lack of it. Maybe someone else in the discord would be able to find something.

#

An other thing, might be inverse kinematic.

modest lintel
#

Any funky ideas on how to mark some Unity API's as non valid just for compilation sake? Mainly, GetComponent<T> and FindObjectOfType<T>

Example vanilla GetComponent<T> is slightly doable, by hiding the original GetComponent<T> and marking it as obsolete with error throwing on. But, still, GameObject.GetComponent<T> and Component.GetComponent<T> are still considered as valid.

Context is a little broad, but this is what the requirement is ๐Ÿ˜„

dusty wigeon
# modest lintel Any funky ideas on how to mark some Unity API's as non valid just for compilatio...

Have better code review policies...

Otherwise, you might want to look into an Analyzer such as https://github.com/microsoft/Microsoft.Unity.Analyzers. I have never done that, but I know it might be possible. (Same if I would recommend to not do this as it has a layer of complexity that would make your project harder to maintain)
Can also use a test in your CI/CD that looks anything that is GetComponent or FindObjectOfType.

modest lintel
dusty wigeon
#

A good documentation would suffice in my opinion.

modest lintel
#

Its a "enforced" suggestion to the user of this product to not use such API's. If they follow it, there's no problem at all. But I'd like to remove the chance altogether, since Unity still considers it as valid code

dusty wigeon
#

You could also develop a plugin for VS or Rider.

modest lintel
#

Too much money and effort ๐Ÿ˜„

#

I'll look into writing an analyzer that's somehow integrated with unity

dusty wigeon
#

This is maybe even harder then a plugin.

#

Feel free to test it, do not take my words for it. However, If I were you I would consider having a well layout documentation.

slender cradle
#

I'm having trouble getting some entities I have spawned to have any type of collision/colliders/rigidbodies or whatever unity.physics requires them to be, have an ECS system using entities,
currently my enemies are being spawned and also moved easily but I have no type collision, unsure if I am doing the component adding incorrectly(they do show up in the entity viewer) or if there is some other thing I have to do to enable them, here is my code :

class EnemyBaker : Baker<EnemyAuthoring>
{
   public override void Bake(EnemyAuthoring authoring)
   {
       var entity = GetEntity(TransformUsageFlags.None);
       AddComponent(entity, new Enemy
       {
           CurrentPosition = float3.zero,
           TargetPosition = authoring.TargetPosition,
           Entity = entity,
           PhysicsVelocity = new PhysicsVelocity { Linear = float3.zero },
           PhysicsMass = PhysicsMass.CreateDynamic(MassProperties.UnitSphere, 1.0f),
           PhysicsCollider = new PhysicsCollider { Value = Unity.Physics.SphereCollider.Create(new SphereGeometry { Radius = 8.0f, Center = float3.zero }) }
       });
modest lintel
modest lintel
plucky laurel
#

cecil?

#

you can just slap the attributes directly on the methods with it

#

but youd have to reapply for each unity version upgrade

#

small cli updater will suffice

plucky laurel
modest lintel
#

Hmm, supposing this works, this would be project wide, right? And I'm assuming its not Unity installation wide. Do you know if how this would interact with precompiled plugin assemblies using the API I just marked obsolete using cecil?

#

@plucky laurel

plucky laurel
#

unity install since its copying asmb from editor dir, but you can mod the cached ones in library instead

#

no idea btw

#

possibly wont throw if they are precomp since it will only copy them

#

afaik unity added analyzers

#

some way to integrate them for unity specifically

#

its just can be even more effort than cecil

#

because of all the possible edge cases

#

maintenance burden

modest lintel
#

Yeah I've been looking at them and looks like too much effort to even see a sliver of result

plucky laurel
#

yeah i wouldnt take that seriously

#

could have missed something, did something wrong, misunderstood whats copied where etc

#

could be just a fluke

#

lol unity changed so much since 4.6

#

i know for a fact cecil is used in prod and high profile plugins by this day

modest lintel
#

Hmm, this looks lesser effort than Analyzers, so I'll try this first

#

Danke!

plucky laurel
#

now i want to
public ~~sealed ~~class GameObject

#

and see where it can take me

#

probably somewhere unreal

scenic forge
#

Never used it, but seems to be just configure which APIs you want to ban and that's all.

modest lintel
modest lintel
#

Oh. My bad. I was looking in Library/ScriptAssembles

modest lintel
#

Hmm, I think that's only populated when the project is built

dreamy marlin
#

got a network problem:
somehow my outgoing packet rate is framerate dependent... if vsync (60hz) is enabled the outgoing udp packet freq is ~60hz, if vsync is disabled the packet freq is ~ 250hz, as desired.
Udp sockets are fed by seperate threads and threads are fed by the physics update rate, which is 250hz.

any ideas ?

flint geyser
#

How should I structure my hierarchy? I have like 40 worms with 60 moving parts each. Physics.SyncColliderTransform takes up several times more time to process than everything else in the game combined. The worm's hierarchy I think is about 7 transforms deep. Any tips? Appreciated.
There is this article but link to the described tool doesn't work, do you know if it's any useful and if yes then how to get it?
https://thegamedev.guru/unity-performance/scene-hierarchy-optimization/

TheGamedev.Guru

You've optimized all of the low-hanging fruits of your game. Except that you didn't. You missed a sneaky, non-so-obvious spot: optimizing your Unity Scene Hierarchy.

lament salmon
flint geyser
lament salmon
#

It was a problem for me, but if thats not the case here then nevermind

obsidian glade
bleak citrus
obsidian glade
bleak citrus
#

breathless to the end

#

it's like i'm getting beaten unconscious on the set of an infomercial

dreamy marlin
#

btw is the physics code somehere opensourced ? i'd love to integrate some physics deltas

bleak citrus
#

some whats

glad badger
#

In the docs about plugin default settings (https://docs.unity3d.com/Manual/PluginInspector.html) , what do they mean about the part of the path in brackets? Is it that you're supposed to create a subfolder simply named /x64 etc? Or do they mean adding that to the end of the subfolder's path like for example /myplugin x64?

bleak citrus
#

pick one of the options

#

that will be part of the path

glad badger
#

ok so like \plugins\myplugin x64\?

bleak citrus
#

no, it'd be like Assets/Foo/Bar/Plugins/x86/whatever

#

the key part being everything up to and including x86

glad badger
#

ah ok perfect. thanks

hasty monolith
#

Will this list be garbage collected after returning ?

    public List<Upgrade> GetActiveUpgrades()
    {
        List<Upgrade> list = new();

        foreach (var upgradeSlot in upgradeSlots)
        {
            list.Add(upgradeSlot.LastPurchasedUpgrade());
        }

        return list;
    }
thin mesa
#

you're returning it, so presumably you'll still have a reference to it. which means it wouldn't get GC'd

hasty monolith
#

so it will get GC'd when the other method invoking it won't need it anymore ?

#

not sure how to properly dipose of it in this scenario

thin mesa
#

it will get GC'd sometime after it is no longer referenced by anything that isn't also getting GC'd

#

you don't need to manually dispose of your List<T> objects. that's what the GC is for (it also doesn't implement IDisposable anyway)

#

as with literally any other reference type, when you no longer need it in memory you just set all references to it to null so the GC will take care of it for you

regal olive
#

How do I stop unity's name and hideFlags variables from being saved into my json file?

"name": "Gunname",
        "hideFlags": 0

I tried

[JsonIgnore] public string name;
    [JsonIgnore] public HideFlags hideFlags;
plucky laurel
regal olive
#

yes

plucky laurel
#

welp, i had to hack an opt-in in source due to such issues

regal olive
#

what's your get around then

plucky laurel
#

dont remember, but opt-in solved it

regal olive
#

gotcha

regal olive
#

yea thanks this will be much better

sly grove
#

But - Opt-In is a really good idea in general

regal olive
#

well yea i was just saving the whole scriptable object into the json file which is fine but it also came with name and hideFlags

sleek terrace
#

How can i update all tiles on the tilemap in another thread to save speed

#

I have a 100 x 100 tiles map, and I am changing the color of all tiles, however, as you can understand, it is quite costly

thin mesa
#

can't access the tilemap API off the main thread, just like most of the rest of the Unity API

sleek terrace
#

indeed

#

any* tricks? tips

sly grove
sleek terrace
#

negative, individually

untold moth
# sleek terrace any* tricks? tips

Make your calculations on the other thread and only assign the properties on the main thread. Something like a command buffer could be used.

sleek terrace
#

My calculations are quite fast, I've measured them, it's less than 0 seconds for the whole map.

It's the refreshalltiles that is killing me

bleak citrus
#

less than 0 seconds? ๐Ÿ˜›

thin mesa
sleek terrace
#

Yes

#

I'm simulating weather over the course of a year

dapper cave
#

onenable is called when the scriptable object is loaded -- what does loaded mean?

thin mesa
dapper cave
slender cradle
#

I'm trying to move a player that I made into an ECS, I can get it to spawn but I can't seem to get it to move from a movement key

untold moth
slender cradle
tropic juniper
#

Hi all, does anyone have any advice on how to do number recognition in Unity? So e.g. if a player/user draws a number on their mobile, I want to recognise which number it is, or indeed recognise that it's not a number.

The best my searching brings up is this: https://assetstore.unity.com/packages/tools/ai/noedify-easy-neural-networks-161940 which you need to train yourself. I would have thought it was a pretty standard problem, but I can't find much. Any advice?!

Get the Noedify - Easy Neural Networks package from Tiny Angle Labs and speed up your game development process. Find this & other AI options on the Unity Asset Store.

dusty wigeon
#

An alternative would be to use an external API.

tropic juniper
scenic forge
#

You can also train the model externally, and your Unity game only needs to run the trained model.

#

If the model doesn't need to interact with Unity or your game in any specific way, you can train it outside of Unity

#

And there are probably plenty pre trained digit recognition models out there, because practically every entry to machine learning uses this exact problem with MNIST dataset.

livid kraken
sand acorn
#

hello there, I know this question has to be posted in #archived-shaders channel, I already did, but that channels remains unactive for most of the day, so Im gonna ask here.

I want to learn compute shaders as they seem way more beneficial than using jobs for my current project, but the problem I have right now is that all the guides or tutorials use compute shaders with a texture rather than processing values or returning values such as floats or ints, so does anyone here knows a tutorial that does not uses textures for compute shaders?

hexed meteor
#

Why does this loop seem to execute instantly, and not respect the time ?

fresh salmon
#

The while loop condition is false first hand, or, the player isn't alive

#

Or, duration is lower than 0

#

Or, an exception occurs
Or, the coroutine was not started properly with StartCoroutine

hexed meteor
#

๐Ÿค”

#

It does perform the action, just instantly as opposed to over time

fresh salmon
#

Debugging required. You need to log the values of these variables or even better, place a breakpoint and step through the code line by line, inspecting the code flow and the values.

wispy osprey
#

is here something wrong

#

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

public class NewBehaviourScript : MonoBehaviour
{
public float speed;
private float Move;

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

// Update is called once per frame
void Update()
{
   Move= Input.GetAxis("Horizontal");

    rb.velocity = new Vector2(speed * Move, rb.velocity.y);
}

}

#

cuz i want to add it to compoments and it dosent work

thin mesa
thorn flintBOT
#
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.

bold berry
#

It has something to do with the offSet````Vector3 offset = playerCollider.bounds.extents.y * Vector3.up;```

fresh salmon
#

Is OnCollisionEnter being executed? Also this very much looks like code generated by ChatGPT seeing one comment for almost each line of code

bold berry
bleak citrus
#

this is spam

bleak citrus
fresh salmon
#

Yeah all that is pretty nonsensical

#

Do you want us to write the code for you? Well your AI is pretty much doing it right now

bold berry
bleak citrus
#

AI generated content is spam.

#

it is often nonsense, yet it looks plausible enough to make your pay attention

bold berry
#

Just a code question.

fresh salmon
bold berry
#

About why my character keeps bouncing

fresh salmon
#

Well you have code for that, better post it instead of some autogen'd code

#

Unless...

bold berry
#

I just posted the code.

bleak citrus
#

you are asking us to comprehend something that was randomly stapled together by a GPU

bold berry
#

Oke

hexed meteor
#

How can I make a thread?

#

I really need some help with some cursed code

zenith ginkgo
fresh salmon
#

And you're back here

#

Is sticking to one channel that hard

zenith ginkgo
#

doesnt like answers: hops channels

hexed meteor
#

Anyone experienced got a minute to help me with some code?

fresh salmon
#

Lord almighty

bleak citrus
#

๐Ÿซ 

fresh salmon
#

Yeah I suggested something in that thread, they proceeded to ignore it, and just closed it?

#

Like if you don't want help just say so lol

hexed meteor
#

I do, but I don't think you're able to help me lol

#

no offense

#

no shame in it

fresh salmon
#

Well you're not doing anything I tell you so you can't know

#

Eh you'll find out eventually that it's your code, but you won't admit it and the cycle will repeat

hexed meteor
#

I've done things you've told me. And have told you so. You're taking it personally and getting offended. I need someone more experienced to look at my code.

fresh salmon
#

haha

#

Your coroutine might just be getting executed twice in a short succession, you should add some code that checks if it isn't running already, and it it is, throw an exception for debugging purposes
This, I suggested this in the thread

#

Can you show me the results of that?

#

Also "needs someone more experienced", is this some kind of dunning-kruger effect?

hexed meteor
#

Dude, you said 'you're not doing anything I tell you' which is categorically false and you can go check the chat above yourself

fresh salmon
#

Debug results please

hexed meteor
#

that's the point I'd rather move on to someone else with a more reality based type of reasoning

fresh salmon
#

@plain abyss someone you know needs that reality check

plain abyss
#

Oh this fuckin guy

fresh salmon
#

Yeah that sums it up

plain abyss
#

Reminder

bleak citrus
#

oh boy

hexed meteor
#

haha you guys are a fun crowd

fresh salmon
#

Apparently I'm not "experienced enough" to solve their "cursed code" issue

#

Maybe call that exorcist after all

plain abyss
bleak citrus
#

when you are seeking out completely free help from people, you should really humor them when try ask you to do something

plain abyss
#

Spent a huge amount of time in the thread I pictured convincing them to do basic debugging steps because they "knew that wasn't the problem". ||Narrator: It was||

bleak citrus
#

hey digi, while you're here, have you considered adding a new category to your counter: Tutorial was actually ChatGPT

plain abyss
hexed meteor
#

it's just categorically true, I don't think you can help me

fresh salmon
#

You're just blatantly trolling at this point, everyone ignore!

brisk pasture
#

Not if you don't listen, a lot of people here are professionals they do this for their jobs and and shipped titles

#

Your problems are not going to be outside of those capabilities

plain abyss
hexed meteor
#

Well I don't know how to act on 'you're note debugging hard enough' my best approach is to debug log variables and narrow down the problem until I figure out what's the issue

plain abyss
hexed meteor
#

putting you on ignore, you do nothing but shit talk and it's pretty tiring

thin mesa
hexed meteor
#

yeah absolutely, seems obvious to do so... and so I did

#

didn't help me though

fresh salmon
#

Where

#

Provide links to messages where you asked for elaboration

hexed meteor
#

I don't care about arguing I care about finding out what's up with my code. You scroll up and re-read the conversation as much as you like

fresh salmon
#

Yeah that means "nowhere" ๐Ÿฟ

hexed meteor
#

don't let your ego get the best of you

fresh salmon
#

I'll return that statement to yourself

hexed meteor
#

I didn't blatantly state a lie

#

lol

fresh salmon
#

Lie? What are you on mate

#

Anyway this is a code channel

hexed meteor
#

'you do nothing I tell you'

fresh salmon
#

Let's not expand this useless conversation here

hexed meteor
#

and you keep bringing up my previous thread and pinging digiholic to join in with your shit talk

#

because you're offended that I think you cannot help

#

you're ego is obviously hurt so you lash out

#

super obvious

fresh salmon
#

<@&502884371011731486> spam

hexed meteor
#

anyway I'm moving on to someone who can help

plain abyss
#

Nah I was brought in because I'm the only person patient enough to deal with your bullshit but I'm actually on a clock today and I don't have time

#

So I'm afraid you're outta luck

humble leaf
#

@hexed meteor In the future, your questions belong in #๐Ÿ’ปโ”ƒcode-beginner, use that channel. Secondly, this is your first and last warning about resisting help here you don't like or don't want to implement. Every time you post here, it's always an issue, so putting this on record so that the next time it happens you can't complain when you're muted. ๐Ÿ‘

fallow dune
#

Sup! Having a really difficult time trying to figure out how to handle weapons.
I can switch weapons, shoot an enemy, apply different damage valued based on the weapon. I use scriptableObjects to store a bit of information about the weapon.
The issue I am having is architecting a solution to store bullets fired from a magazine , switching weapons and keeping track and possibly switching to other weapons later.

I would love some idea or input on how to approach I guess weapon state?
Side note: Not looking for code, I think I am more looking at how to possibly go about tackling the solution.

plush hare
#

Like you practically already know what to do.

hushed fable
#

Sounds like they don't have a place to store individual item state.
@fallow dune Straightforward approach is to have some sort of item class that represents a single item instance and all of its state. The issue with just ScriptableObjects is that by default they tend to represent all items of a given type, so you don't have the per instance data.

fresh salmon
#

That's what I did in one of my projects. Weapons on the ground have a pickup script attached which exposes common properties to apply on the weapon when it's equipped (on instantiate). Then when the weapon is dropped I can instantiate a pickup back, store the state it's in into the pickup script, and it's ready to be picked up again in the state it was left off. Switching weapons was as simple as disabling the weapon at the right time, "freezing" its state

plush hare
#

As for writing a central ammo system, a really clean way is to use enums as array indexes. myCharacterAmmo[_9mmAmmo].

hushed fable
#

If your ammo can be complex, you can also just also treat them as items

fresh salmon
#

Yeah, you could stack some modifiers on them like damage boost or increased range, in a list of modifiers you can edit from the Inspector

#

Another script can then loop through these and apply the mods to whatever property is relevant

sleek terrace
#

Why are my tilesmaps generating the colors in this shape?

untold moth
sleek terrace
#

So i thought, but doesnt seem to be the case

untold moth
#

Non uniform scaling perhaps?

untold moth
sleek terrace
#

damn your right

#

5 x 5 map

bleak citrus
#

ah yes

sleek terrace
#

everything is on 1 tho

untold moth
#

It could be that your sprites don't have the right ppu

sly grove
untold moth
#

Or was it upp?๐Ÿค”

sly grove
#

Certainly just seems like the hexes are double sized

sleek terrace
sly grove
#

and then there's just some z-fighting happening

sly grove
#

Does it have parents or no

sleek terrace
#

I was using the default hex, i assumed the ppu would be good

#

it was at the default 100 ๐Ÿ˜ฆ

#

instead of 256

untold moth
#

What's "the default hex"?๐Ÿค”

sleek terrace
#

The one that unity provides, standard white hex

untold moth
#

Did it provide such a sprite by default?

sleek terrace
#

Hexes look good, thanks @untold moth

sleek terrace
untold moth
sleek terrace
mellow plinth
#

I'm creating NavMeshLinkDatas at runtime and setting the NavMeshLinkData.owner value to the monobehaviour that create them...
At NavMeshAgent.currentOffMeshLinkData, how can I get that owner? There is no owner in OffMeshLinkData type.

zenith ginkgo
#

can you make your own class that inherits NavMeshLinkData and create a getter for the owner?

#

NavMeshAgent.navMeshOwner. according to gooogle, it's this

thin mesa
#

oh actually it's the NavMeshLinkInstance that has the owner property

zenith ginkgo
#

have the "advanced" navmesh things been put into the base engine yet? perhaps they're using that

#

from the github repo

bleak citrus
#

yeah, in the AI Navigation package

#

it left experimental in...2022? or maybe 2021, i forget

mellow plinth
dry bridge
#

Hi guys! I need help with something. So currently, I'm experiencing a bug wherein multiple instances of a controller button press via Oculus Quest 2 is inputted for every one press of a controller button. I'm using InputDevice.TryGetFeatureValue() and CommonUsages to extract the input signals coming from the Oculus Quest 2 controller button presses. Would you guys have any ideas on how I can make a single button press only translate to a single input signal in Unity?

sly grove
dry bridge
vale spindle
#

how do I learn AI? I want to make something complex. Right now I only know how a* works and I experimented a little. I need a course or maybe see how people are remaking other game's ai. I might want learn how to make my own navmesh later. Should I try to get into machine learning?

somber swift
novel nacelle
vale spindle
lament salmon
vale spindle
#

thanks i'll look into it. more advice would be helpful.

flint geyser
#

How do I make an array of arrays in job?
Kinda NativeArray<NativeArray<Vector3>>

lament salmon
#

And the vid descriptions usually have links to resources for further reading

#

GOAP is another concept to look into

flint geyser
#

Well, a parallel job working with arrays inside my objects

bold berry
#

someone can help me with my game mechanic

#

trying to let me player which is a smalle sphere stick to the bigger one Vector3 newPosition = gameObject.transform.position + (surfaceNormal * Time.fixedDeltaTime);

orchid marsh
dry bridge
flint geyser
#

Can I simulate a Collider without the Component? So that I have to do it every FixedUpdate

bleak citrus
#

i guess you could do physics queries

flint geyser
#

I need specifically others to be able to detect the Collider I am simulating

bleak citrus
#

i do not understand

sage radish
flint geyser
#

Imagine I have a Box Collider on my object. I don't want the component to be attached to any GameObject but want others to detect Collider in the place where the Collider component is supposed to be.

bleak citrus
#

for what purpose

flint geyser
#

The reason for why I want it is because I have many colliders I have to move by setting their position and it results in monstrous processing from Physics engine sometimes taking up to 11ms for single fixed update

#

The methods I see in profiler at this moment are Physics.SyncColliderTransform and Physics.SyncRigidbodyTransform

bleak citrus
#

unity doesn't do that work for no reason

#

it does that so that the physics system can work in the first place

sage radish
flint geyser
#

I do not know how to tell if a collider is kinematic but I suppose it became a little better after I added Rigidbody to them

#

And they are triggers if it matters

sage radish
#

It will also still always sync before FixedUpdate. But with this setting off, it won't sync every time a transform is changed.

flint geyser
#

Do you suggest I do it once every 2 frames or more?

#

Oh

sage radish
#

Or if you're okay with 1 frame delay, then you can just let the FixedUpdate sync handle it.

flint geyser
#

Seems like checked Auto Sync Transform provides the best performance...

hushed fable
plucky dagger
#

I'm looking to understand which approach gives me more precision when measuring time. I want the timing to be as precise as possible. Say for example, I want the image to switch at precisely 1.5 seconds. Should I use update method (or fixed update or other variations). Should I use a coroutine?

My target application is WebGL and I'm assuming it's going to be accessible to a variety of OS and browsers with different hardware configuration. So I want to ensure that 1.5 seconds in the application is precise across these systems.

sly grove
#

The best you can do is draw on the next frame which immediately follows the 1.5 seconds.
If you want something else to happen at some precise time after that 1.5 seconds, then you make sure after drawing the thing, you don't discard the intra-frame error in timing

#

so for example, a quite accurate 1.5 second timer:

float timer;
float interval = 1.5f;

void Update() {
  timer += Time.deltaTime;
  while (timer >= interval) {
    timer -= interval; // note we subtract interval rather than setting to 0.
    // setting to 0 would discard the error time

    DoSomething();
  }
}```
plucky dagger
#

Thank you! The application that I'm prototyping isn't a game but more like a UI application. What application should I be using if I'm concerned about precision of time measurement?

sly grove
#

there is no digital computer-based application that will not have this limitation without some custom hardware.

#

what exactly is the use case?

scenic forge
#

What are you making? We can give better advice if we know the use case.

plucky dagger
#

I was under the impression that frame-based approaches are better because the in-application timings are better when we factor frames vs. just measure system time.

plucky dagger
#

So imagine a simple UI application where the users react to a stimulus before it's gone.

scenic forge
#

In that case just vsync your game/crank up FPS to the highest.

#

It doesn't matter how precise your timing is, user's monitor is still refreshing at a set rate.

#

You can't display anything until the monitor refreshes.

sly grove
scenic forge
#

The new input system has raw input time reported by hardware as well.

plucky dagger
#

But the catch is that this application will be for a variety of hardware/software configuration. So I thought a frame-based approach would work better because let's say a browser is laggy. Then I don't want system time because that's not correct measurement but in-application time.

scenic forge
#

You would judge user's reaction time based on hardware input time, not frame time.

sly grove
#

only windows-targetted applications

#

Not sure what's available in WebGL exactly

#

You may be limited in your precision here by what the browsers actually give you in terms of input exposure

scenic forge
#

It will be limited to browser time precision and no way around it.

#

If you interop with JS, you can use performance.now() which provides the highest precision browser allows you, but even that may still be limited (eg Firefox limits the resolution to prevent time fingerprinting to protect privacy)

plucky dagger
plucky dagger
scenic forge
#

If what you are measuring is how long until user inputs after they see the frame, then that's exactly what you need.

plucky dagger
# scenic forge You simply use the frame time as the start time.
float timer;
float interval = 1.5f;

void Update() {
  timer += Time.deltaTime;
  while (timer >= interval) {
    timer -= interval; // note we subtract interval rather than setting to 0.
    // setting to 0 would discard the error time

    DoSomething();
  }
}

Something like this then right?

scenic forge
#

Just user hardware input time - frame time.

plucky dagger
hushed fable
#

Depending how these various input backends (from OS -> Browser) generate the input timestamp, I would start with that first before trying to create browser counters. Browsers generally avoid providing high precision timers anyway with recent CPU exploits.

gentle hedge
#

Hi. I want to create a 3d array of voxels. Each will have a float value and it's position (whole numbers). I will have millions of them, if not billions. Many of them will have the same values, even whole numbers. How can I compress the data so it's using as little space as possible?

sly grove
scenic forge
#

Probably the first thing you should look at is to not store the positions at all.

gentle hedge
gentle hedge
sly grove
scenic forge
#

Not sure what you mean, if you are concerning about stored size rather than runtime size

sly grove
#

but yeah important to think about storage format vs runtime data format

scenic forge
#

Then once you read it out of storage, you would compute their positions once and have it available as the exact same runtime representation.

sly grove
#

especially since you will absolutely want to use a world streaming technique

gentle hedge
scenic forge
#

I think you are missing the point

#

Positions are only omitted in storage, when reading it out from storage into memory, you can compute those positions once, and it will be exactly the same for your runtime.

#

There is no runtime penalty, if you are not changing runtime representation at all.

gentle hedge
#

It can be as large as a few gigabytes, so either way I'll need to compress it somehow, with capability of using them at runtime or to optimize regenerating the points when I need them

scenic forge
#

You would stream it like suggested above

#

You would never have your entire world in memory, that simply does not scale.

sly grove
gentle hedge
#

Maybe you're right. My application would require the massive amount of points at the same time, but maybe I can access them sorting by height, so I could fit them into 2d array and move it along the height

#

I need to create some sort of gradient in a 3d space to be specific

tropic vigil
gentle hedge
#

Where I start the gradient at the bottom, so instead of populating the 3d array, I can slide 2d array and gradient points with it

gentle hedge
scenic forge
#

Is generation of the data costly?

gentle hedge
scenic forge
#

Well, just by not storing positions, you already shrink your data size on disk to 25% of what it was.

gentle hedge
#

I'm thinking about some compute shader to speed it up, but I'm now only on designing the work flow, so I don't know how large structured buffers I will need

gentle hedge
scenic forge
#

Highly dependent on your data, but I doubt so.

gentle hedge
#

Ok, thanks for now. I'll think if I can do any workarounds ๐Ÿ™‚

scenic forge
#

If I was you, I would get rid of the positions, then just use any compression algorithm (gzip, whatever) and see what it ends up being.

#

If that's still not good enough, look at your data and think about how to transform it to create more repetition.

#

Eg if you transform:

1234 1238 1242 1246 1250 ...

Into:

1234 4 4 4 4 ...

It will compress extremely well by the compression algorithm you already chosen.

#

For most applications that's already good enough.

dusty wigeon
#

#archived-code-general for advice on how to debug. Here are some that you could take:

  • Start small (3x3)
  • Remove all obstacles
ebon flower
#

ok, thanks

plush hare
#

@gentle hedgeIf you really want to get the most out of compression, it's generally going to be lossy. But that shouldn't really affect much if you do it right

#

quantize the float data into integers. You'll lose a few decimals of precision. Really shouldn't be too noticeable

#

after that, you can just pack the integers using variable width encoding. You can do all of this yourself. Avoid using things like gzip

#

If you store individual positions based on the relative chunk location, it will also compress a lot nicer.

bleak citrus
#

yeah, gzip would work best if you had lots of repeating patterns, which is probably not the case here

vast shale
#

I'm trying to solve a problem where a headless server build of my game has a 0,0 viewport (as it's headless), which means my camera bounds checks completely break on the server logic.

Has anyone had to solve this before? I'm thinking I need to create an object that emulates a camera's frustum where I can supply a fixed ratio (e.g. 16:9 most likely) for visibility checks.

untold moth
vast shale
#

server-authoritative off-screen player respawns

plush hare
#

wat

hoary igloo
#

HI everyone. I have a 911 emergency. I'm working on a final project for the semester and I'm trying to spawn clones with a transform position script inside them.

plush hare
untold moth
untold moth
hoary igloo
#

Sorry let me find the words

vast shale
plush hare
untold moth
vast shale
#

But I'm also sure it's possible to emulate the geometric calculation a camera performs with a fixed ratio

plush hare
#

You still haven't said what you're trying to achieve

vast shale
#

that's the thing, I don't need the server to know the client's hardware. Even though we're supporting multiple resolutions, a fixed check at 16:9 would suffice for this issue

untold moth
vast shale
#

if the viewport is 0,0, what would those planes be?

untold moth
vast shale
#

there's no aspect ratio information and I can't see where to try injecting it

untold moth
#

You'll need to look up how to calculate frustum planes.

vast shale
#

that sounds the way. I guess that's platform agnostic and something I can look for

plush hare
#

@vast shaleHere's the problem with what you're doing. The client is going to be predicting his position and orientation. If you're spawning things in/out depending on what the server players are "looking at" then the actual clients are going to see things teleporting and spawning in and out. The client and server "client" are seeing different things at different times.

untold moth
#

There's also this overload:

public static Plane[] CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix);
#

You'd only need the "camera" transform for this one.
Maybe not. Confused with the transformation matrix.

vast shale
plush hare
#

that doesn't make any sense

vast shale
#

if that's the case, that's on me for not fully explaining the nature of the game, the server-client architecture, and the reason I'm solving this. But trust me, I just need to do this manual calculation

plush hare
#

I'm explaining to you how networking solutions work

#

it doesn't matter if they're viewing the same scene

#

unless this is being locally ran on the same machine, the clients are going to see things teleporting in and out, if I'm understanding what you're trying to do

vast shale
untold moth
#

Burt is correct though. If you do the check on the server just like that, there's a high chance your players would actually be able to see things spawning.

plush hare
#

Even in server authoritative networking solutions, the client always has a small, but fair degree of authoritativeness

vast shale
#

the players are supposed to see the spawning.

untold moth
#

Oh, then I guess we got it wrong.

plush hare
#

yeah idk

#

if it works then it works

untold moth
#

They still might not see it then.

vast shale
#

it's fine, haha. I really do appreciate the help. But yeah - players pop and teleport, other players see it, don't see it.. it's completely a non-issue and non-concern. The catchup off-screen respawn mechanic is completely surfaced on the front-end with full intention.

plush hare
#

sounds really janky

#

but alright

vast shale
#

it's just when the logic runs headlessly, they respawn constantly obviously, as they are always "off screen".

#

the fllback is we just use a world-position difference, which again even that is passable, it's just a bit shitter and will be way more visible and obvious.

plush hare
#

If you're fine with popping and teleporting, then why does it matter if they're within view of the frustrum?

untold moth
#

Or even an angle

vast shale
#

what matters is the essence of the respawn trigger. when the game is running in 4 player local, everyone has the same camera, if a player goes out of the camera, BAM, we fix it.

that's all it is, but with the architecture we have, we want that logic only running with state authority when in online sessions (dedicated server).

plush hare
#

so like if a player falls of the map

#

he respawns?

#

using the frustum data?

vast shale
#

yes

plush hare
#

that probably the worst way you couldve done this in a multiplayer setting

vast shale
#

well, not falls off the map, goes out of view

plush hare
#

why not just specify the bounds?

vast shale
#

OK.. imagine this. we're making an olympcs track runner game. Four players.

one player runs REALLY FAST.. camera holds pace with leader.. one player is so slow they go off camera. What to do? well, instead of eliminating them, we'll put them back on the screen behind the player.

game design feelings aside, that's the entirety (simplified example) of the technical solution.

plush hare
#

I don't work on rendering, but isn't each player's resolution going to absolutely screw this up?

compact ingot
#

there is a reason why its a good idea to separate logic from rendering ๐Ÿค”

vast shale
#

if some one players the game on a portrait monitor, yes, it'll be bad for them. But I'm going to accept 16:9 ratio as a baseline and it is what it is. that will cover a majority of players.

plush hare
#

bad solution

untold moth
vast shale
#

why is it a bad solution

#

the server and all four clients have the same "active zone" of gameplay. All players see the same screen, same view, at all times.

#

I'm not tlaking about screwing with resolutions? at all?

#

I'm talking about a way to approximate a camera's field of view when the regular way of doing it is unavailable

vast shale
#

no, if it were I'd set easily

#

there's dynamic camera logic for player-framing, so FOV is fluid, along with distance, and lerped movement and aiming.

untold moth
#

And that is not controlled by the server?

vast shale
#

that's simulated both sides

plush hare
#

can you like take a screenshot

#

of the game being played

vast shale
#

no

#

unfortunately

#

not at liberty

untold moth
#

Well, if you need precision, you'll need to figure out a way to calculate frustum planes manually. Probably a googleable answer.

vast shale
#

Yeah that's gonna be my approach

#

don't need full precision either, again this is a fully surfaced game mechanic, for soft rubberbanding. nothing about this execution has to be seamless or invisible to players.

arctic lake
#

How can I enable a global database into Unity

hoary igloo
#

OKAY... SO. I'm using Firebase with Unity and I'm trying to track in real time the position of IRL beacons to move some prefab objects that I'm spawning on the screen. FOR SOME REASON, the sensor values keep getting set to zero somewhere in the process, and I don't know why. I don't know how to find what I'm doing wrong. I come seeking advice from yee great Unity cabal! (gong noise)

#

seriously please help

untold moth
untold moth
arctic lake
#

I guess I should ask which database should I use with Unity if I want different PCs to access the same one

#

Would Firebase be good for that

untold moth
#

I think unity has some solution as well now.

hoary igloo
arctic lake
#

Well the database I want has to keep track of people's locations

#

latitude, longitude, etc.

untold moth
untold moth
arctic lake
#

Got it, thanks!

untold moth
hoary igloo
# untold moth Well, at what point is the value reset?

as far as I can tell, I think it's when I'm constructing the prefabs. I have a beacon class and a driver class and a datamanger class, the datamanger class calls the beacon class and then is supposed to be assigning a beacon to new instance of the driver class, which prefabs a car?

untold moth
hoary igloo
hoary igloo
untold moth
#

Are the database values only updated by the sensors?

#

Debug both the sensors data(specifically what they update the database with) as well as the data retrieved from the database in your game.

hoary igloo
untold moth
#

Really, there's not enough info to say anything specific.

hoary igloo
untold moth
hoary igloo
untold moth
#

How did you end up doing a project like that a day before deadline..?

#

Without having experience in unity, C# or databases.

hoary igloo
#

No I spent a month on it then had to start over from scratch

untold moth
#

Well, I'm not sure we can help you without you explaining your project structure and issue clearly.

ember frigate
hoary igloo
#

I was trying to do the entire thing with primitives the first time and that's just pure C# with lots of drawing calls. My code got so F'ed up that it was unreadable. I got permission to redo it in Unity but with only 3 days to do something that I have been working on for a month.

I have gotten WAY further using Unity than I did in a month of primitives. I really like Unity and if I could just get this one piece working and understand how it works, I could finish the project in a night.

#

To be fair Monday and Tuesday I coded and read tutorials 16 hours straight. My roommates actually had to check on me to make sure I was okay.

untold moth
hoary igloo
#

I do in fact get the data but it seems to disappear when I instantiate the clones.

untold moth
hoary igloo
hoary igloo
#

Data Manager Class

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using System;
//using Firebase.Extensions.TaskExtension;

public class DatabaseManager : MonoBehaviour
{
    public GameObject CarPrefab;
    public DatabaseReference Beaconreference;
    public DatabaseReference ParkingMapreference;
    public DatabaseReference Sensorsreference;
    // Start is called before the first frame update
    void Start()
    {
        Beaconreference = FirebaseDatabase.DefaultInstance.GetReference("Beacons");
        ParkingMapreference = FirebaseDatabase.DefaultInstance.GetReference("ParkingMap");


        Beaconreference.GetValueAsync().ContinueWithOnMainThread(task => {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                // Do something with snapshot...
                Debug.Log("Beacons: " + snapshot.ToString());
                foreach (DataSnapshot child in snapshot.Child("data").Children)
                {
                    
                    Beacon beacon = (Beacon)ScriptableObject.CreateInstance(typeof(Beacon));
                    beacon.SetupBeacons(child.Reference);
                    beacon.d1 = Convert.ToDouble(child.Child("D1").Value);
                    beacon.d2 = Convert.ToDouble(child.Child("D2").Value);
                    beacon.d3 = Convert.ToDouble(child.Child("D3").Value);
                    beacon.d4 = Convert.ToDouble(child.Child("D4").Value);
                    GameObject vehicle = Instantiate(CarPrefab);
                    Driver driver = (Driver)vehicle.GetComponent(typeof(Driver));
                    driver.StartEngine(beacon);
                    Debug.Log("Driver: " + child.Child("D1").Value);
                    Debug.Log("Driver: " + driver.thisbeacon.d1);
                    Debug.Log("Driver: " + child.Child("D2").Value);
                    Debug.Log("Driver: " + driver.thisbeacon.d2);
                    Debug.Log("Driver: " + child.Child("D3").Value);
                    Debug.Log("Driver: " + driver.thisbeacon.d3);
                    Debug.Log("Driver: " + child.Child("D4").Value);
                    Debug.Log("Driver: " + driver.thisbeacon.d4);
                    
                }
            }
        });



        ParkingMapreference.GetValueAsync().ContinueWithOnMainThread(task => {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                // Do something with snapshot...
                Debug.Log("ParkingMap: " + snapshot.ToString());
            }
        });

    }

    // Update is called once per frame
    void Update()
    {

        

    }
}
#

Sensors Class

using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using UnityEngine;
using Firebase;
using Firebase.Extensions;
using System;

public class Sensors : MonoBehaviour
{
    public static Sensors instance;
    // Start is called before the first frame update
    public static Point[] data = new Point[4];
    public static int total = 4;

    public DatabaseReference Sensorsreference;
    // Start is called before the first frame update
    void Start()
    {
        Sensorsreference = FirebaseDatabase.DefaultInstance.GetReference("Sensors");
        int i = 0;

        Sensorsreference.GetValueAsync().ContinueWithOnMainThread(task => {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                // Do something with snapshot...
                
                foreach (DataSnapshot child in snapshot.Child("data").Children) 
                {
                    data[i].X = Convert.ToInt32(child.Child("position").Child("x").Value);
                    data[i].Y = Convert.ToInt32(child.Child("position").Child("y").Value);
                    i++;   
                }

                
                Debug.Log("Sensors: " + snapshot.ToString());
            }
        });
    }
}
#

Beacons Class

using Firebase.Database;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Beacon : ScriptableObject
{
    public double d1;
    public double d2;
    public double d3;
    public double d4;
    public DatabaseReference beacons;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    public void SetupBeacons(DatabaseReference d)
    {
        beacons = d;
        //beacons.ValueChanged += HandleValueChanged;
        beacons.Child("D1").ValueChanged += HandleValueChangedD1;
        beacons.Child("D2").ValueChanged += HandleValueChangedD2;
        beacons.Child("D3").ValueChanged += HandleValueChangedD3;
        beacons.Child("D4").ValueChanged += HandleValueChangedD4;
    }

    void HandleValueChangedD1(object sender, ValueChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        // Do something with the data in args.Snapshot
        d1 = Convert.ToDouble(args.Snapshot.Value);
    }

    void HandleValueChangedD2(object sender, ValueChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        // Do something with the data in args.Snapshot
        d2 = Convert.ToDouble(args.Snapshot.Value);
    }

    void HandleValueChangedD3(object sender, ValueChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        // Do something with the data in args.Snapshot
        d3 = Convert.ToDouble(args.Snapshot.Value);
    }

    void HandleValueChangedD4(object sender, ValueChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        // Do something with the data in args.Snapshot
        d4 = Convert.ToDouble(args.Snapshot.Value);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
#

Driver Class

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

public class Driver : MonoBehaviour
{
    public Beacon thisbeacon;
    public void StartEngine(Beacon b)
    {
        thisbeacon = b;
    }
    void Start()
    {
        thisbeacon = (Beacon)ScriptableObject.CreateInstance(typeof(Beacon));
    }

    public static (double, double) TrackCar(double x1, double y1, double r1, double x2, double y2, double r2, double x3, double y3, double r3)
    {
        double A = 2 * x2 - 2 * x1;
        double B = 2 * y2 - 2 * y1;
        double C = Math.Pow(r1, 2) - Math.Pow(r2, 2) - Math.Pow(x1, 2) + Math.Pow(x2, 2) - Math.Pow(y1, 2) + Math.Pow(y2, 2);
        double D = 2 * x3 - 2 * x2;
        double E = 2 * y3 - 2 * y2;
        double F = Math.Pow(r2, 2) - Math.Pow(r3, 2) - Math.Pow(x2, 2) + Math.Pow(x3, 2) - Math.Pow(y2, 2) + Math.Pow(y3, 2);

        double x = ((C * E) - (F * B)) / ((E * A) - (B * D));
        double y = ((C * D) - (A * F)) / ((B * D) - (A * E));

        return (x, y);
    }

    // Update is called once per frame
    void Update()
    {
        double x, y;
        (x,y)=TrackCar(Sensors.data[0].X, Sensors.data[0].Y, thisbeacon.d1, Sensors.data[1].X, Sensors.data[1].Y, thisbeacon.d2, Sensors.data[2].X, Sensors.data[2].Y, thisbeacon.d3);
        
        transform.position.Set(Convert.ToSingle(x), Convert.ToSingle(y), 0);
    }
}
#

There's also a parking spaces class but I'm not doing anything with that yet.

untold moth
#

Ok,so what exactly is being reset?

hoary igloo
#

in the driver class r1, r2, & r3, should all have data in them. In the other classes they're called D1, D2, & D3.

#

There's also a D4 but I'm not doing anything with it because it's easier to do trilateration with 3 points instead of 4

untold moth
hoary igloo
#

yes

untold moth
#

I see that you create a new instance of Beacon and assign it to thisBeacon. Wouldn't that set default values? Do you set the d1 values somewhere after that?

#

Oh, nvm. You shared the Beacon script too.

#

The d values seem to only be updated when the value in the db is changed. That would mean that initially they're 0.

#

You probably need to update these values when you create a new instance of a Beacon.

hoary igloo
#

In my DataManager class, when I create the beacons, aren't I setting the values there?

untold moth
#

Ah, I see you're passing it in StartEngine.

#

Well, is it being called before or after Driver.Start?

#

Because if Start is called after that, you're referencing a new instance instead of the one passed to it.

#

Add logs in your Start and StartEngine methods and see the order of execution

hoary igloo
#

You're amazing. I commented out the line in Start and now it works.

#

or at least the values aren't disappearing

#

Thank you SO much

night stag
#

Hello! I'm working on a script that overrides the textures of a specific terrain layer at runtime. While the diffuse and normals are stored in their own Texture2DArray's, the Height/Smoothness/AO are stored within the green channel of the diffuse/normal textures (not sure how that works). However, those textures can also be accessed through a struct that's found within the subshader of the shader I'm using for this (MicroSplat). Is there a way to access the struct through code to override these textures?

#

My script:

    {
        StartCoroutine(ReplaceTexture());
    }

    IEnumerator ReplaceTexture()
    {

        yield return new WaitForSeconds(1);

        Debug.Log("10 seconds waited");

        myTerrain.materialType = Terrain.MaterialType.Custom;

        Material terrainMat = myTerrain.materialTemplate;
        Shader shader = terrainMat.shader;

        Texture2DArray diffuseArray = terrainMat.GetTexture("_Diffuse") as Texture2DArray;
        Texture2DArray normalArray = terrainMat.GetTexture("_NormalSAO") as Texture2DArray;

        Debug.Log("Array depths:" + diffuseArray.depth + " " + normalArray.depth);

        Texture2DArray newDifArray = new Texture2DArray(diffuseArray.width, diffuseArray.height, diffuseArray.depth, TextureFormat.DXT1, 11, false);
        Texture2DArray newNormArray = new Texture2DArray(normalArray.width, normalArray.height, normalArray.depth, TextureFormat.DXT5, 11, false);

        for (int x = 0; x < diffuseArray.depth; x++)
        {
            for (int y = 0; y < diffuseArray.mipmapCount; y++)
            {
                if (x == 1)
                {
                    Graphics.CopyTexture(diffuse, 0, y, newDifArray, x, y);
                    Graphics.CopyTexture(normal, 0, y, newNormArray, x, y);
                    Debug.Log("Custom layer replaced");
                }
                else
                {
                    Graphics.CopyTexture(diffuseArray, x, y, newDifArray, x, y);
                    Graphics.CopyTexture(normalArray, x, y, newNormArray, x, y);

                    Debug.Log("Texture copied");
                }
            }
        }

        terrainMat.SetTexture("_Diffuse", diffuseArray);
        terrainMat.SetTexture("_NormalSAO", newNormArray);

        Debug.Log("Textures set");
    }

}```
raw shoal
#

hi , i'm encountering this error with thundra and beedriver during build process ```[225/227 88s] GenerateNativePluginsForAssemblies Library/Bee/artifacts/WinPlayerBuildProgram/AsyncPluginsFromLinker

CommandLine

GenerateNativePluginsForAssemblies

ExitCode

-1

Output

BeeDriver connection terminated
Killed
*** Tundra build interrupted (88.58 seconds - 0:01:28), 225 items updated, 224 evaluated
ERROR: Job failed: exit code 1``` I have no glue where too look , any ideas?

orchid marsh
cold root
#

someone help me to make a character jump because in my code when it jumps it doesn't come back down

gentle hedge
#

Hi. How can I detect if a point is inside 3d mesh? I don't want to use colliders, because I don't want to be dependent of Unity Physics and my mesh can have way more triangles than max collider triangles count. I saw some implementation of a nice algorithm, but it's for 2d:
http://www.lighthouse3d.com/tutorials/maths/ray-triangle-intersection/

#

I thought about something that checks if some triangle crosses both X and Y coordinates of that point, then discards every other triangles. Then somehow if these triangles have a point inside with coordinates X and Y of that first point

tropic vigil
flint geyser
#

I give such a value to my NativeArray in FixedUpdate but when I am trying to read the NativeArray in LateUpdate it appears as already deallocated, any ideas why?

_foodPositionsNative = new NativeArray<Vector3>(foodPositions, Allocator.Persistent);```
tropic vigil
flint geyser
#

I now moved disposing to the point right before they are created, thanks

dusty wigeon
limpid vector
#

Hey everyone,

I'm currently using a singleton pattern, that the managers are created at run-time when they are needed, so it isn't just sitting there in the scene.
I'm loading the UI prefabs from resources since the singleton is not scene-dependent and whatever the scene the player is on, the manager keeps working. I've seen this method in a post, and I found it interesting, so I'm implementing it in my current project.

Though I'm feeling a little weird about this and I feel that there is a better way to do it. Since we load the UI and our singleton is not on screen until run-time, I can't just reference the UI elements on the inspector, instead, I need to find everything on my prefab for just then manipulate them according to my needs, which takes time.
My question is if this approach is bad and if it is, is there a better way to do it?

solar cape
#

Hello, I am trying to Implement a custom update to unity but I am having 2 problems, when I move the slider for target fps on the UI for some reason the gameplay update seems to go faster, and then I think I have a problem with delta times for smoothing movement
https://gdl.space/unegovoqoy.cs

thorn flintBOT
#
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.

plucky laurel
tropic vigil
solar cape
sly grove
remote drift
#

any suggestion how to distribute prefabs randomly across rect?

#

I can't come up with an algorithm

#

I need to fill whole area

sly grove
remote drift
#

well, that is pure random

#

which will not fill rect

sly grove
#

?

#

I don't understand

#

you asked for random

#

what do you actually want

remote drift
#

I need distribution

sly grove
#

what kind of distribution

#

explain yourself

remote drift
#

uniform

#

I guess

sly grove
#

just divide the width and height by how many items you want to place

#

and place them

remote drift
#

something like this

#

I mean

sly grove
#

looks like a random distribution to me

remote drift
remote drift
sly grove
#

you didn't say that was an issue

remote drift
#

and some areas won't be filled

#

I need to fill area fully

sly grove
#

look up Poisson Disc sampling

bleak citrus
#

sounds like you want --

#

dammit