#archived-code-advanced

1 messages · Page 77 of 1

mighty dagger
#

Is it possible to disable mesh serialization? I'm working on procedural generated meshes (Minecraft-like). Sometimes the state of the mesh doesn't reflect what I have in my serialized data structures. But I suppose I could just clear all meshes upon start and re-generate. But then they would be stored somewhere in serialized form without purpose.

#

Or better, can I have a gameobject excluded from serialization totally (outside of editor)? If I'm using it just for reference when testing some generated stuff? So that I wouldn't have to delete it each time when I start the game.

#

Perhaps I could create a new scene but then I would have to copy lights / player stuff and keep that in sync in two scenes....

young shard
#

can I have an unity application communicate with a console application that runs a server for stuff like checking in a user walked thru a wall? If yes how woud I do that?

mighty dagger
young shard
fickle tinsel
young shard
#

well i need to do that if i wont figure out how to do this in unity

fickle tinsel
young shard
#

but i cant figure out ho to map signalR hubs in unity

#

so i though if i cant figure out how to do that i can have the hubs outside and use a client as a helper

#

perhaps you might know how to map those hubs?

#

i send a screenshot of the microsoft guide above

fickle tinsel
#

I've never heard of signalR hubs

young shard
#

well possibly you still might know how to do this in unity?

#

Im pretty sure signalR isnt the only service using this

fickle tinsel
# young shard well possibly you still might know how to do this in unity?

If you’re trying to roll your own game server using SignalR then you’ll probably have to serialize your unity game state from your player client to your SignalR server, and then use SignalR to parse the serialized game state to check things.

Transforms are already serializable. Somehow you’ll have to get mesh data into your game server so you can do boundary checking.

If it were me and I really wanted to do this, I’d probably read an open source library like Mirror to see how they do it. Mirror still gets to leverage Unity for the server so there would be a lot of translation into a DIY game server.

fickle tinsel
young shard
#

That does create an issue with multiple scenes tho

#

Can I have multiple scenes open but none of them interact with watch other only with themself?

fickle tinsel
fickle tinsel
young shard
fickle tinsel
young shard
#

Well with netcode for game object the serverRPCs are in the game so anyone cud just decompile and get it

#

I just want to make it myself

#

So you know if I can load multiple scenes at once that don't interact witth eatch other?

young shard
#

You can even host the game of a client

fickle tinsel
young shard
#

Il look into it

fickle tinsel
young shard
tall ferry
young shard
flat swan
#

Hi guys! New here and just getting back into Unity (I've forgotten so much 💀 ) and I have a question that I haven't been able to get answered on the forums, and ChatGPT is a bit stumped with
In the project window all C# scripts have the same icon - paper with the corner folded down - and I'd like some way for script files to automatically change their icon depending on what class they are inhereting from. So all Monobehaviour use A, all Editor use B, and all [insertcustomclassname] + children use C?
I know ScriptableObjects have this functionality (kinda) but I'd like something similar for all script types. I've tried a couple of things, but so far nothing is working

sly grove
flat swan
#

I'll ask there thanks 🙂

brisk minnow
#

so update on this situation (still waiting on an email reply, but figured it wouldn't hurt if i educate myself more)
after going through the code more (i've been learning how to use the debugger in visual studio) and i think i came across the culprit to what's going wrong.
Apparently this in some situations (that i do not know yet) can cause this code to infinitely loop. which sorta makes sense to what may be happening inside of unity.

So now, my goal is to learn some methods to fix infinite looping (or find a good way to create a method which will stop the script regardless)

so i guess my next question is.. would anyone know of any good methods to stop infinite loops?

#

because the code is pretty fast, but i think i want to put a forced stop if it takes longer than a few seconds to complete.

#

so is it possible to run unscaled delta time in editor?

dusty wigeon
brisk minnow
grave jackal
#

Hello, I am using unity version control, I have branch "A" with pending changes and I made a branch "B" child of branch "A", the problem I have is that I want to switch to branch "B" to upload the pending changes to that branch, but when I make the change it tells me that I have pending changes in branch "A" and that I cannot change to branch "B".

For example, on GitHub, when I switch branches, it gives me the option to take the pending changes to the new branch. Does anyone know how I can do the same in Unity Version Control?

fickle tinsel
grave jackal
fickle tinsel
#

Not really. Is plastic SCM software based on git?

vernal furnace
#

If I want to load an asset from the Resources folder at runtime on android, what should my path to that folder be?
I'm using this currently as my path
"jar:file://" + Application.dataPath + "!/assets/" + "Resources/serializedData.txt";
But it doesn't like that.
Any suggestions on my error?

grave jackal
fickle tinsel
fickle tinsel
grave jackal
# fickle tinsel What's it based on?

I don't know, it's their own software, in fact I only use the program where everything is managed visually, it's very similar to github desktop

fickle tinsel
grave jackal
untold moth
fickle tinsel
grave jackal
fickle tinsel
untold moth
#

In the check in drop down?🤔

#

Google plastic scm shelving.

grave jackal
dusty wigeon
#

In SVN, you can shelves your change. (It clear the working tree.) Then you can swap branch and unshelves

#

I guess it might be the same

grave jackal
vernal furnace
# jolly token Why not Resources.Load

Well it loads from the path, and android doesn't seem to even have a resources folder after it's built. So maybe Im stubborn and haven't thought it out using that method, but I'm curious how to do it using my current system. Or at least a less complicated version

dusty wigeon
jolly token
vernal furnace
grave jackal
vernal furnace
#

What method is advised for data storage on android? I want to save my settings at runtime, but I know I cannot save it back to Resources. The method that looks most promising is:
I save the file elsewhere and pre compile I have it pull that document into the Resources folder to have it read back as a TextAsset

#

I feel like its too late to go back to my very ugly PlayerPrefs model of saving an int.

jolly token
vernal furnace
jolly token
vernal furnace
modest vale
#

Hello can anyone help me understand this?
why does the unity commandbuffer make my class so slow, event when exicuting the command buffer in sync?
so I wrote this class this class is supposed to use a command buffer to dispatch a shader asyncronisly and collect the data whenever it s ready
the dispatching asyncronisly and waiting intill its ready works very well but there is one major issue using the command buffer to dispatch the shader async or sync slows down everything by so much and it takes about 20 times longer to do so this is my code and I commented some results

 private void Dispatch()
    {
        IsCompleted = false;
        watch.Start();
        if(dispatchType % dispatchTypeMod < 4)
        {
            _commandBuffer.SetBufferData(_jobBuffer, _Job, 0, 0, _currentParallelJobs);
            _commandBuffer.DispatchCompute(_vertexShader, 0, _res / 32, _res / 32, _currentParallelJobs);
        }

        switch (dispatchType % dispatchTypeMod)
        {
            case 0:
                Graphics.ExecuteCommandBufferAsync(_commandBuffer, ComputeQueueType.Default);
                break;//80-120ms
            case 1:
                Graphics.ExecuteCommandBufferAsync(_commandBuffer, ComputeQueueType.Background);
                break;//80-120ms
            case 2:
                Graphics.ExecuteCommandBufferAsync(_commandBuffer, ComputeQueueType.Urgent);
                break;//80-120ms
            case 3:
                Graphics.ExecuteCommandBuffer(_commandBuffer);
                OnComplete();//80-120ms
                break;
            case 4:
                _jobBuffer.SetData(_Job, 0, 0, _currentParallelJobs);
                _vertexShader.Dispatch(0, _res / 32, _res / 32, _currentParallelJobs);
                OnComplete();//about 3-5 ms
                break;

        }
nova summit
#

I want to rotate the upper arm "local rotation" such that the white debug ray rotates towards red debug ray. I want to change only local rotation of upperArm transform. Any way to achieve this?

spiral zenith
nova summit
#

In this case yes, but as I can see the local transform arrows I can find it out on which axis I need to rotate. but how to generalise it?
Basically I want to set the transform local rotation such that the white ray vector to be rotated towards red ray vector.

#

I tried Quaternion.FromToRotation but looks like it's valid only when in world space, so tried transforming both the vectors to local space of the parent transform as below.

#
private void CalculateLocalRotationAtParent(HumanBodyBones parentJoint, HumanBodyBones childJoint, Vector3 targetChildPosition)
        {
            Transform transformParent = m_animator.GetBoneTransform(parentJoint);
            Transform transformChild = m_animator.GetBoneTransform(childJoint);


            var currentBoneDirection = transformParent.InverseTransformDirection(transformChild.position - transformParent.position);
            var targetDirection = transformParent.InverseTransformDirection(targetChildPosition - transformParent.position);

            Debug.DrawRay(transformParent.position, currentBoneDirection * 10, Color.black);
            Debug.DrawRay(transformParent.position, targetDirection * 10, Color.blue);

            Quaternion rotationRequired = Quaternion.FromToRotation(currentBoneDirection, targetDirection);
            transformParent.localRotation = rotationRequired * transformParent.localRotation;
        }

targetChildPosition is where you see the red ray is pointing at.

//This code works when setting rotation but above fails when setting localRotation
 private void CalculateRotationAtParent(HumanBodyBones parentJoint, HumanBodyBones childJoint, Vector3 targetChildPosition)
        {
            Transform transformParent = m_animator.GetBoneTransform(parentJoint);
            Transform transformChild = m_animator.GetBoneTransform(childJoint);

            var currentBoneDirection = transformChild.position - transformParent.position;

            Debug.DrawRay(transformParent.position, currentBoneDirection * 10);

            var targetDirection = targetChildPosition - transformParent.position;

            Debug.DrawRay(transformParent.position, targetDirection * 10, Color.red);

            Quaternion rotationRequired = Quaternion.FromToRotation(currentBoneDirection, targetDirection);

            transformParent.rotation = rotationRequired * transformParent.rotation;
        }
spiral zenith
#

I don't know a lot about the Unity methods for this, sorry.
But if you have 2 rays, you can find the axis you need to rotate around, it's the cross product of the 2 vectors.
Than you can apply the rotation like this :

transform.rotation *= new Quaternion(Mathf.Sin(angle / 2) * axis.x, Mathf.Sin(angle / 2) * axis.y, Mathf.Sin(angle / 2) * axis.z, Mathf.Cos(angle / 2))
#

(But there are probably better ways to do that using some Unity functions)

nova summit
#

Any way to change only the localRotation? I want to change only local rotations alone for better control.

spiral zenith
nova summit
#

Oh ok. Let me see if anyone can help.

spiral zenith
#

But I don't really understand why setting the rotation of the arm would not work for you.
Why do you want to set the local rotation?

#

What happens if you use transform.rotation ? Do you not get the rotation you wanted ?

nova summit
#

Setting rotation is fine but want to know why localRotation isnt working to understand better.

spiral zenith
brave fog
#

Hi! I have a working local game that uses ChatGPT using the OpenAI API, I want to import it into itch.io and save some data in csv's after the game ends in a Firebase database, but I am facing a few issues:

  1. firebase doesn't have unity for webgl on their website, will unity for android work fine?
  2. it turns out that the OpenAI API key is private and shouldn't be distributed to everyone via itch, how can I let people use it without them having the API key?
tiny pewter
#

host a server and the client app send request to your server, and your server handle the requests

#

you have to define the http header or whatever connection between clients and your server

brave fog
#

thank you! wait so the OpenAI front and storing the csv's will be dealt with by the server without firebase?

tiny pewter
#

idk, maybe your server can send csv to another database

brave fog
#

Do you have a recommendation for a Hosting service I can use? Is there perhaps a different platform on which I can publish my game where I would be able to use convenient tools like Firebase or something similar?

#

Right now Firebase only works for android and apple but I would also like it to work on PC if possible

tiny pewter
#

i know nothing on backend

brave fog
#

Ok, thanks for the help!

spiral zenith
#

Hello!
I'm experimenting with Microsoft.CodeAnalysis.CSharp.Scripting and all of that stuff to evaluate expressions at runtime (like this : CSharpScript.EvaluateAsync("3 + 2").GetAwaiter().GetResult()) and it works when I build the game for windows but somehow it does not work when trying it in the editor.
Here is the error :
Would you have any idea why it works in a build but not in the editor?

dusty glacier
#

Hi, I am using UI builder to make my custom inspector and an editor script in this function 'CreateInspectorGUI()' and I made a few buttons that need to change which Visual Tree asset is being rendered, but the change only happens when i deselect and select the object that has the scirpt with my custom inspector.

#
        buttonElement.RegisterCallback<ClickEvent>(PrintClickMessage);

        Button buttonElement1 = Inspector.Q<Button>("b2");
        buttonElement1.RegisterCallback<ClickEvent>(PrintClickMessage1);

        Button buttonElement2 = Inspector.Q<Button>("b3");
        buttonElement2.RegisterCallback<ClickEvent>(PrintClickMessage2);
#

buttons call a function that changes an int to some value and that value determines which visual tree asset i return to 'CreateInspectorGUI()'

stuck vector
#

If I run diff -r Build1 Build2 on two Unity build folders (recursively compares the binaries)

And replace all differing files

Will that always work to update Build1 to Build2 ?

upbeat path
stuck vector
#

Working on automatic build updating. My computer has Build1 and Build2 is in s3.

Only want to download the different files

Then replace those in Build1

stuck vector
upbeat path
#

if you are using s3 buckets I guess you're building on AWS, correct

plush hare
plush hare
young shard
#

I research I did this before I'm prepered

#

I have a client shared and server projects obviously ik there needs to be shared code

plush hare
young shard
#

Why the hell would you assume they arent

#

There just simple on different branches

#

Leave ma alone God dammit ik what I'm doing and what I'm getting into I never asked on advice if I should do it

plush hare
#

Sorry, didn't mean to make you so angry over nothing

#

You can stop typing, I don't want to speak with you anymore

young shard
#

You didn't make me angry but you are truly wasting your own time as I will not change my mind

plush hare
#

Great, you can stop typing now

young shard
#

Good me neither

carmine swan
#

okay so I have this code that is supposed to make the player walk sprint look up , down , left and right and when I finished it I this

#
{
    [Header("Movement Speeds")]
    [SerializeField] private float walkSpeed = 3.0f;
    [SerializeField] private float sprintMultiplier = 2.0f;

    [Header("Look Sensitivity")]
    [SerializeField] private float mouseSensitivity = 2.0f; 
    [SerializeField] private float upDownRange = 80.0f;

    [Header("Inputs Customisation")]
    [SerializeField] private string horizontalMoveInput = "Horizontal";
    [SerializeField] private string VerticalMoveInput = "Vertical";
    [SerializeField] private string MouseXInput = "Mouse X";
    [SerializeField] private string MouseYInput = "Mouse Y";
    [SerializeField] private Keycode sprintKey = Key.Leftshift;

    private Camera mainCamera;
    private float verticalRotation
    private CharacterController characterController;
     
    private void Start()
    {
        characterController = GetComponent<characterController>();
        mainCamera = Camera.main;
    }
    private void Update()
    {
        HandleMovement();
        HandleRotation();
    }

    void HandleMovement()
    {
        float sprintMultiplier = VerticalMoveInput.GetKey(sprintKey) ? sprintMultiplier : 1f;
        float verticalSpeed = Input.GetAxis(VerticalMoveInput) * walkSpeed * sprintMultiplier;
        float horizontalSpeed = Input.GetAxis(horizontalMoveInput) * walkSpeed * sprintMultiplier;

        Vector3 speed = new Vector3 (horizontalSpeed, 0, verticalSpeed);
        speed = transform.rotation * speed;

        characterController.SimpleMove(speed);
    }
     
     void HandleMovement()
    {
        float mouseXRotation = VerticalMoveInput.GetAxis(MouseXInput) * mouseSensitivity;
        transform.Rotate(0, mouseXRotation, 0);

        verticalRotation -= Input.GetAxis(MouseYInput) * mouseSensitivity;
        verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
        mainCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0,);
    }
}```
#

Can anyone help me ?

upbeat path
#

is this line 56?
float sprintMultiplier = VerticalMoveInput.GetKey(sprintKey) ? sprintMultiplier : 1f;

#

@carmine swan

#

I think it should just be Input.GetKey

carmine swan
#

the error is still the same , thanks though

prisma goblet
#

And do the same thing to vertical

carmine swan
#

alright

carmine swan
#

It's fine I found a code that worked thanks

prisma goblet
copper plover
#

Can i use textmeshpro SDF shader on any mesh?

#

to create outline for other meshes

timber flame
#

Hey, I have implemented a generic ItemList class.
It is a monobehaviour, a container to create and keep a list of items.
Items can have an icon + some texts.
Do you prefer to implement these classes as generic <T> or something like a Dictionary<string,string> key/value pair to update text data in that item

public class ItemList<T>:MonoBehaviour where T : ItemViewModel{
   public void UpdateItem(T item){}
}
jolly token
#

Hmm actually you are making MB

#

Still I’d prefer some first class collection for the model

timber flame
#

but when it should be updated, I have to update all even if just one of them changes. By the way,It is OK

#

In ItemList view, it does not matter what Item is and what contains in

jolly token
#

🤔 then why it is a list

timber flame
#

It has some functionalities

#

Create Items from prefab, add, remove them

#

clear the list, update a specific item

#

So, this class can be used in different situations with different items (views)

jolly token
#

I don’t really get it but sure? However you can’t add generic MB from inspector

#

Unity would require concrete type

timber flame
#

public class ClassA:BaseClass<>{}

#

It is better than creating several ItemList for each Item type

untold moth
timber flame
#

Items can be completely different

#

I prefer the generic approach, by the way thanks.

untold moth
untold moth
#

If they have something in common, having a base class or an interface would make more sense than generics.

untold moth
#

Well, at least you know that it's related to compute buffers, which is probably related to compute shaders.
What are you using compute shaders for in your project?

flint sage
#

That sounds like some fun math error 😛

#

Maybe some over/under flow

bleak glade
#

So I made a simple script to generate a Terrain as a Mesh programmatically, also added UV's and materials. Now I want to add paths to these terrains, essentially mixing textures (texture splatting), but I've been unable to find a good method to do this, any idea? (Image of terrain for reference)

upbeat path
bleak glade
#

You mean the unity builtin terrain object?

upbeat path
#

yes

bleak glade
#

well uh im not using those

#

its just a mesh

#

because i need it to kinda be in chunks

upbeat path
#

Unity terrain can be in chucks

bleak glade
#

ye but its still like size limited right

upbeat path
#

no

#

a chuck is size limited but the number of chunks is not afaik

bleak glade
#

oh i guess i could make the individual chunks out of those terrains

#

idk feels like it'd be just a bit more complex but i guess i'll do that

upbeat path
#

less complex than trying to UV map paths to a mesh

bleak glade
#

yeah idk i thought there was a simpler way to blend those with like vertices

steel snow
#

does unity's mesh functions like recalculate normals run in linear time

#

i was thinking to parallelise it with job system but if unity's function already does that it would save me the time

sly grove
steel snow
#

ill assume its linear since it's unity

#

ill do a bench test against my job version

sly grove
#

Well it's definitely linear. The question I guess is that linear time split up among multiple threads or not.

steel snow
#

it doesnt need to be linear

#

you could technically use a compute shader i guess

sly grove
#

that's also linear

#

it's just that it's split up among many threads

steel snow
#

thats what i mean by linear vs non linear

sly grove
#

the amount of work done is linearly related to the number of vertices

steel snow
#

oh you referring to time complexity

sly grove
#

yes

#

but

steel snow
#

how about thread-able then 😛

sly grove
#

i won't hold you up with this silly semantic argument

#

It's probably thread_able_ but who knows if they actually multithreaded it

steel snow
#

ill report back on my bench test results

sly grove
steel snow
#

oh nice

#

though im wondering then maybe i just do it in the compute shader and pass it straight to my material shader

solemn talon
#

Not exactly code questions
Does anyone knows, what Load Cell is?
Google doesnt help

dusty wigeon
solemn talon
dusty wigeon
solemn talon
solemn talon
timber flame
#

The common data is just icon. I have one base class

#

When I say generics, I mean

 public abstract class BaseItem<T> : MonoBehaviour
    {
        public Guid Id { get; private set; }

        public abstract void SetText(T data);
        public abstract void SetIcon(Sprite icon);

        public void Initialize(ItemViewModel<T> data)
        {
            Id = data.Id;
            SetIcon(data.Icon);
            SetText(data.TextData);
        }
    }
  public abstract class GeneralItem : BaseItem<ItemTextViewModel>
    {
    }

Generic classes do not mean, they do not have inheritance.

dusty wigeon
#

Then it only means that you either did not use it correctly or it does not fit your needs.

stuck vector
#

Anyone know where to find a Unity Project's Build Version in the Build folder? it's not in app.info

timber flame
#

When I disable vertical layout, it smoothly scrolls and reset the position y of the panel. I do not want it.

#
 var anchoredPosition = root.GetComponent<RectTransform>().anchoredPosition;
            await UniTask.Yield();
            layoutGroup.enabled = false;
            root.GetComponent<RectTransform>().anchoredPosition = anchoredPosition;
            await UniTask.Yield();
            root.GetComponent<RectTransform>().anchoredPosition = anchoredPosition;
            layoutGroup.enabled = true;
            await UniTask.Yield();
            await UniTask.Yield();
            await UniTask.Yield();
            root.GetComponent<RectTransform>().anchoredPosition = anchoredPosition;

It does not work

#

root.GetComponent<RectTransform>().anchoredPosition.y eventually will be 0

untold moth
# timber flame When I say generics, I mean ```cs public abstract class BaseItem<T> : MonoBehav...

That's so convoluted for an item system. And you can totally go with interfaces or inheritance here. I really don't see the point of generics. Generics are for more generic stuff. Think of a C# list. It can contain any type at all without any constraints. The types can have nothing in common at all. In your case they do have things in common - they have to implement 2 abstract methods. Text is ultimately a string anyways, assuming you assign it to ui. And icon is always a sprite. No need to go generic here.

wary blaze
#

Just wanted to update my UnloadSceneAsync test results. Using Additive vs Non Additive loading doesn't seem to make a difference. I don't really understand how your team was able to unload scenes with 100,000-200,000 game objects when these are my test results from trying to unload a scene with only ~400 objects . . . unless all the game objects in your game were light weight? I did run a test with 500 empty game objects (only Transforms), and the unload operation has almost 0 perofrmance impact. But that is not realistic for a live game.

It seems that when unloading a scene, Unity will destroy all of the scenes game objects in 1 frame.

Again, this is fine. I am more than happy to iteratively destroy the game objects over multiple frames, even if it requires a bit more work. My main point of asking the questions I did here was to figure out if there was some advantage to using UnloadSceneAsync that wasn't obvious.

wary blaze
#

The profiler was attached so not sure if that makes some sort of difference.

untold moth
wary blaze
#

Windows

#

Unity 2021.3.21f1 - perhaps this behavour has changed in a more recent version of Unity

dusty wigeon
#

Also, we were developing on 2021.3.21f1 and only recently upgraded to 2021.3.27f1. Both version were working correctly.

wary blaze
jolly token
#

You get guarantee of ‘Destroy happens altogether' with unloading scene. That’s not something asynchronohsly processable. And yes if you wanna reduce overhead then destroying manually over time will give you less frame hiccups.

#

OnDisable/OnDestroy happening on random frame and order will break some games

wary blaze
jolly token
#

Same goes for loading scenes btw

#

Loading scenes have to instantiate everything on scene in single frame regardless of async API

proud steeple
#

I would say this is pretty advanced. I'm trying to create a custom editor for bitmasking tiles using a full 3x3 set of 256 tiles, similar to what Godot has. I currently have it where I can get the sprites from a 16x16 texture. I would like to create a button that slices the sprites and saves them to both the 2D sprite array and the original texture. Basically emulating Sprite Editor functions at the same time so I don't have to drag each individual sprite manually.

There is not a lot of good documentation on how to do this and what I've found suggests that TextureImporter.spritesheet is obsolete and I need to use UnityEditor.U2D.Sprites. However, it's telling me that the Sprites portion of that namespace cannot be found and I honestly have no idea where to begin looking for why it can't be found, especially since UnityEditor.U2D and UnityEditorInternal both work.

Apparently, this is a recent enough change that even ChatGPT4 doesn't know the answer as it keeps suggesting I use TextureImporter.spritesheets or, if I feed it the documentation that does exist, it just tells me to use that namespace, just like people on the forum say to do.

#

Alternatively, if anyone knows how I can get all the sprites from a texture that's already sliced, that would help immensely.

#

I currently have a method that uses Sprite.Create() and saves the asset, but it doesn't show up as a child of the original texture the way it does when using the Sprite Editor. In fact, when doing this, it gives me an Unknown Error.

thin mesa
#

you might need to check some more of the boxes in the external tools settings but i don't remember what options are there off the top of my head

proud steeple
#

I definitely have it installed and using the latest version. That was the first thing I checked.

#

Actually, it's specifically asking if I'm missing an assembly reference. This is currently in my Utilities assembly. 😲

thin mesa
#

then you need to reference the assembly if you are not already

proud steeple
#

Yeah, I think that might be it. Give me a sec

#

That seems to have cleared the error. Thank you, thank you. 🙏 peepoHeart

I'm still new to using assembly definitions in my workflow, so it's not something I've made a habit of checking yet.

tired fog
#

Is this better than a plain GetData?

                AsyncGPUReadback.Request(DataForCollisions, (AsyncGPUReadbackRequest req)=>{
                    if(req.done){
                        VegetationDatas = new VegetationSet.VegetationData[arguments[0]];
                        DataForCollisions.GetData(VegetationDatas, 0,0, arguments[0]);
                        DataForCollisions.Release();
                        DataForCollisions = null;
                        CollidersRecived = true;
                    }
                });
sage radish
tired fog
#

Oh

#

So how can i copy to VegetationDatas?

sage radish
#

The data you get back is in a NativeArray. You can copy that to wherever you want.

#

Or you can provide a NativeArray in the request

tired fog
#

Do i need to dispose of the native array?

sage radish
#

No, it will automatically dispose next frame.

tired fog
#

Okay, and If I want a certain amount of data? (on the normal get data there's teh count parameter)

sage radish
tired fog
#

Size being the length*the size of the data that i want?

prisma goblet
#

!code

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.

sage radish
tired fog
sage radish
#

Where stride is the size in bytes of one element.

tired fog
#

Cool stuff

#

So, this would be the right way

                AsyncGPUReadback.Request(DataForCollisions, arguments[0]*VegetationVisualizer.SizeOfData, 0, (AsyncGPUReadbackRequest req)=>{
                    if(req.done){
                        VegetationDatas = req.GetData<VegetationSet.VegetationData>(0).ToArray();
                        DataForCollisions.Release();
                        DataForCollisions = null;
                        CollidersRecived = true;
                    }
                });
prisma goblet
#

let me try

sage radish
tired fog
#

I would be technically creating it right there, so then it's good

#

Thanks!

#

Question, an asyncgpu readback for 4 ints, it's not really worth it right?

spark spade
#

Hello everyone, i have a suprising issue that is one of a kind to me (meaning i never had to deal with something like that). My game drops to 30fps out of nowhere, when before it runs around 80-120 fps on my device. This happens on multiple type of laptops. I really dont know what could cause it but here are some nice to knows:

Unity version: 2022.3.4f1
Render Pipeline: SRP
Post-processing: Yes
Models: STYLIZED - Sci-fi corridor pack
Netcode for gameobjects: Yes
Profiler in image attached

The scene only contains this one hallway, so i doubt it has to do with the heavy models. The profiler above tells us somthing in the likes of the particle system is causing issues, and thats fair, but it happens in burst sometimes, other times it happens for a long time, sometimes short. I would need assistance as optimizing unity rendering is a area im not known for

sage radish
tired fog
untold moth
spark spade
#

@untold moth

untold moth
#

Hmm

#

Are your particles affected by lighting?

#

Or emit light?

spark spade
#

I actually dont know, they come with the demo scene! Let me check!

#

They have emission checked on

#

All of them

untold moth
spark spade
#

Does this look like GPU hell to you?

untold moth
#

There's definitely a lot of lights. Are they all real time lights?

spark spade
#

I have turned all particles off completly, testing now!

sage radish
#

"emit light" would mean the Light module is enabled.

spark spade
#

Oh yeah

untold moth
#

Ah, right.

spark spade
#

This is a particles setting

sage radish
#

@spark spade Which Unity version are you using?

spark spade
#

2022.3.4f1 as mentioned in the OG post

sage radish
#

My understanding is that this profiler marker can appear when there is a bottleneck in the render thread. That would be too many draw calls for the CPU to handle.

spark spade
#

This might be the huge problem

sage radish
#

You say you're using SRP. Do you mean the built-in render pipeline?

spark spade
#

Yes

untold moth
sage radish
#

If you're using forward rendering in the built-in render pipeline, then each realtime light will cause a new draw call for every object it touches. That can lead to a lot of draw calls with this many lights.

sage radish
#

It's supposed to be fixed. Apparently it can also appear if you're accessing some data on the particle system at inopportune times.

spark spade
#

Looks like this asset pack has some intresting light usage. These are all for 1 small ceiling light. It looks amazing, but makes sense that is burns fps right

tired fog
#

So, im trying a diferent approach now, However , the request is called 4 times, but the Recived is called n random times, any idea on why?

Debug.Log("Request");                   commandBuffer.RequestAsyncReadback(InstancePositions,arguments[0]*VegetationVisualizer.SizeOfData, 0, (AsyncGPUReadbackRequest req)=>{
                        if(req.done){
                            Debug.Log("Recived");
                            pack.ChunkRepresentation.Colliders = CreateColliders(req.GetData<VegetationSet.VegetationData>(0).ToArray());
                        }
                    });
spark spade
#

What would be the best course of actions right now, lads?
Turning all the lights into baked lights?

untold moth
sage radish
#

Or you can use the improved forward renderer in URP.

spark spade
#

We are sticking with the standard render pipeline, because it brings the best out of this pack. How would i make that switch?

sage radish
sage radish
#

It can also be overridden per camera, with the Rendering Path property.

spark spade
#

Hold the phone, i might be an idiot and have no right to be here asking for help but is this normal 😂

sage radish
#

Yes, it's normal if you're using the built-in RP

spark spade
#

Okay few

#

Probably overlooking it, but cant find any settings related to render path. I see the deffered shader, but i doubt thats what you meant

#

Ah found it

#

Same results, just less often

#

I think ill try to fix the lighting

#

Ill get back with results soon!

#

So here is a funny thing. I turned off all the lamps, and now this is just the problem. No longer nested under particles

#

Mind you, it happens WAY less.

austere jewel
spark spade
#

No. this is cpu, lemme show gpu

#

This is the entire scene

#

If anyone needs access to the project, just ask!

austere jewel
# spark spade

This isn't the worst frame, perhaps go back to when you had a 50ms frame and look at the GPU profiler, expanding it and figuring out what's taking all that time

spark spade
#

My bad, this is a 60fps frame 😮

#

Weird, it does not seem to drop below 100 other then like 2 split frames of 60. Might have been the lighting after all

#

Ill dive deeper, thanks everyone who helped out! 😄

#

Lighting issue confirmed

mild sentinel
#

I'm using a tilemap to make levels. Each level is a scene, and I'm building each one by loading them additively in the editor. Though, the rule tile I use doesn't connect to the tiles of the other scene. Is there anything I could do for that?

cerulean minnow
#

Can someone help me figure out what is up with my nav mesh agent? Its going to the wrong location ( sorry had to take video with my phone , can't get my pc to screen record right now , stupid windows 11 )

#

You can see the location i want is to the left of where the line renderer ends

#

Line renderer should go to the left

dusky olive
#

I am trying to create a wiping/cleaning effect. What is the best way to get all pixel colour data from when this green cube intersects with the blue plane? I can get texture uv coords from a raycast but I want from the whole range of coordinates from a collision/intersection so I can use it on a variety of different meshes

craggy spear
#

will boxcast give you what you need?

dusky olive
urban warren
#

A bit of a broad question. But I am doing some mesh instancing, but I only want to show the meshes within a radius of the player.
I have all of the points that different meshes in a KDTree. I was wondering if it would be more performant to have a KDTree for each mesh (All RockA in one tree and GrassB in another), and do a radius search on each tree. Or to do one big one and then parse out the results to get the list of points for each mesh.

cerulean minnow
tired creek
#

Hello, I seek advice regarding an architectural problem. I have a few MonoBehaviours, each representing a System, meaning that:

  • It has functions handling a set of closely related tasks
  • Only one instance exists at a time
  • Needs to be referenced in many other scripts

An example of such system can be a Console, that takes text, pareses it and calls relevant functions from dictionary.

To solve this problem I can take a few approaches:

  • Pass references around in the inspector, using prefabs. I dont like that because it seems unnecessary and some of these systems do not need to be prefabs.
  • Make every system a Singleton. This is bad because global state is bad. Also thats a lot of Singletons.
  • Use FindObjectOfType to store reference to a system in every place that needs it. I think this is the best option Ive thought of so far, but also feels like a global state with additional steps.

Anybody knows how to handle this gracefully?

fickle tinsel
# tired creek Hello, I seek advice regarding an architectural problem. I have a few MonoBehavi...

IMO the “find object of type” is the best option from what you’ve presented.

I’m not a fan of singletons myself due to them being implicit dependencies and because I love me some automated tests.

That said… None of the options are bad really.

If you really wanted to go down a rabbit hole then you could always explore inversion of control: instead of every component having a ref to the system, what if the system has a ref to everything that needed it. Another hole: what if you rearchitected to be event driven.

tired creek
#

I am already switching to events to do some decoupling

fickle tinsel
#

Another rabbit hole: what if your systems weren’t centralized in a component — what if they were emergent behavior from component interactions

tired creek
#

but I need to have a reference to the event channel scriptable object at least hahah

tired creek
#

thats too much IQ for me

fickle tinsel
#

Point being that there’s so many ways to do something. Make sure you’re being pragmatic and moving forward lol.

tired creek
#
    public static T FindRequiredObject<T>() where T : Object
    {
        T[] result = Object.FindObjectsOfType<T>();
        if (result.Length != 1)
        {
            throw new System.Exception($"Invalid amount of {typeof(T).Name} objects: {result.Length}");
        }
        return result[0];
    }

I will do this to be extra secure and it should be fine

dusty silo
#

In my current project we're have custom serialize fields that allow us to select class implementations for weapon modifiers. Those fields are present in weapon configs and by nature after we instantiate a weapon we need to work with those implemented classes and mutate them.
So in that case what would be a better approach? Instantiate scriptable objects or write classes that consume SO and deep copy the data?

tired creek
#

also If I have a SO storing references, I still need a reference to the SO

#

so I might as well get the references directly

dusty silo
tired creek
#

yeah I have a Global class that stores references to global references

#

but global state bad

#

or so Ive read

dusty wigeon
dusty silo
# dusty wigeon Instantiation of Scriptable Object works well (However, you need to clear the me...

Modifiers can be preset per weapon so that it instantiates with some and then be changed on the fly, so they aren't unique and can be even moved between weapons during the play
Currently it's working with us spawning prefabs for said entities that contain modifiers, but it clogs the scene for no reason (there's no need to have an object with transform for them). So I thought that SO could work, but not sure whether it's a good approach to do so

dusty wigeon
#

If not, Scriptable Object will add a burden to your designer team and to your games.

dusty silo
dusty wigeon
#

Can you give an example of a standard modifier

#

I'll determine for you if they are.

dusty silo
#

And the usual +damage -attack speed stuff

dusty wigeon
#

Are they like tier ? Or more like actual number ?

dusty silo
dusty wigeon
#

Do you have like:
Tier 1: Weapon hits cause enemies to burn X
Tier 2: Weapon hits cause enemies to burn Y
Tier 3: Weapon hits cause enemies to burn Z

or

Weapon hits cause enemies to burn for X

dusty silo
#

In case player progresses

dusty silo
dusty wigeon
dusty silo
#

Yes

#

It's a droppable modifier that you can insert into your weapon

dusty wigeon
#

Oh, then ScriptableObject is definitly the way to go.

#

The alternative, is to have the data serialized on the weapon.

dusty silo
dusty wigeon
#

You must ask yourself where data make more sense to resides.

dusty silo
dusty wigeon
dusty silo
#

Well you see, the problem is

#

That entity that stores modifiers is droppable as well

#

And you can insert it into weapon to change it's behaviour

dusty wigeon
dusty wigeon
dusty silo
#

Then you need to be able to change modifiers inside of it

#

And when you do so the base SO mutates, no?

dusty wigeon
#

The effect itself should be mutable.

#

The only way an object mutate, it is if you change a variable.

#

inside of it.

dusty silo
#

I change the array with modifiers inside of SO

#

The List*

dusty wigeon
#

Then it should probably not be a SO.

#

Can you graph your structure ?

dusty silo
#

yup

dusty wigeon
dusty silo
dusty wigeon
#

It does not really make sense does it ?

#

Why would you have modifier out of the weapon if they cannot modified it if they are not inside an injector ?

dusty silo
#

So you can put injector in, and the put modifiers into it

#

And place modifiers into different injectors inside of one weapon even

dusty silo
#

It has reload data

#

And animations

dusty wigeon
#

I think I would go with the duality between Definition (SO) and Instance (GO/C#).

WeaponDefitinion (SO) -> Instantiate Weapon GO
InjectorDefinition (SO) -> Instantiate Injector C#
ModifierDefinition (SO) -> Instantiate Modifier C#

The definition contains: Name, Description, Icon, Initial Data (InjectorDefinition/ModifierDefinition)
Weapon GO: SerializeReference on Injector C#
Injector C#: SerializeReference of Modifiers C#

Inventory contains C# objects. (It can be the Injector/Modifier itself or a reference to the SO)

#

Having Injector or Modifier as a duplication of SO could work, however, you would duplicate data that is shared between all instance.

#

It is also really handy to use SO, because you can use them without having an actual instance. Something like a power selector

dusty silo
#

So basically I will take initial data and deep copy it to create C# class on the basis of it?

dusty silo
#

And static things like Name and Desc can remain in definition?

dusty silo
#

They are classes that are selected inside of inspector

dusty wigeon
#

I mean, yes there is my bad. In case of the injector and modifier.

#

The weapon is an instantiate.

#

Maybe that would be even better to simply use GO in all case.

#

No need for any manual copy.

dusty silo
#

Wait, you can instantiate GO based on the SO?

dusty wigeon
dusty silo
#

I see i see.
So it's fine to have empty objects that serve no purpose except hosting scripts?

dusty wigeon
#

You have no idea how many script are there just to be there.

#

Take any API.

#

You even create GameObject to structure your scene

#

If you do a level, you gonna divide your level in parts.

#

PartA

  • GPI
  • Environment
  • etc.
    PartB
  • GPI
  • Environment
  • etc.
    PartC
  • GPI
  • Environment
  • etc.
#

I hope your are doing that.

#

Otherwise, your scene must be a mess.

dusty silo
#

Well it's clean when things aren't running 😎

dusty wigeon
#

Then you probably are doing it.

dusty silo
#

(We need to start spawning stuff with some order instead of root dumping dozens of enemies)

dusty wigeon
#

Or eveything is generated.

dusty silo
#

Tho I'm not fully understanding how will I create GO based on SO and not mutate the prefab or avoid the need to deep copy

dusty wigeon
#

All data that does not needs to be mutated and is shared is in the SO.

dusty silo
#

Oh, got it

#

Tho the problem is initial data needs to be copied

#

If I instantiate prefab and then set it we're working with refernce from SO

#

If I change prefab first it mutates

dusty wigeon
#

You do not understand what I mean.

dusty silo
#

Seems like I don't

dusty wigeon
dusty silo
#

Oh, we're already basically doing this, but with just prefabs into go

#

instead of SO into GO

dusty wigeon
#

Yes, SO instantiate GO.

#

You can even preset your slot of your injector with a Modifier

#

That is a GO

dusty silo
#

Yup yup, works like this rn, just with prefabs wrapping stuff instead of SO

dusty wigeon
dusty silo
dusty wigeon
#

They also behave differently in build and editor

#

Also, you can not have ScriptableObject variant.

#

And also tends to stack really quick and become a nuisance as you have data that is unique per weapon.

#

Creating unique SO when it is not necessary.

#

If every variable was a SO, then what would happens ?

#

The answer to that, is what you want to avoid.

dusty silo
#

I see, thanks for sticking with me

wide anvil
#

Hiya, I was wondering if yall had any opinions on what player authenticator software to use if you've ever released a game with accs? I'm not a huge fan of building my own authenticator bc handling player passwords server side seems like too much responsibility.

#

I know about playfab but it seems a bit expensive

#

Oh and my game is cross platform mobile and steam, using fish-net. Fish has a authentication module which I can build hooks into

untold moth
wide anvil
untold moth
#

Well, that would really only work if you have separate servers for each platform. Linking between several platforms is more complicated. You'd need your own custom server or relying on a third party service like Playfab that you mentioned.

wide anvil
#

That does check out with what i've been seeing though. Looks like I should read more into playfab

untold moth
#

There are other similar service providers, like google firebase. I'm sure there's something in AWS and Azure as well. But the prices are probably around the same.

wide anvil
#

I think playfab is azure's solution afaik

#

firebase does look like it has some advantages but also it's not fully designed for games

#

I'll look into the aws gamelift stuff for sure too

#

tyty

steel snow
#

how do we run jobs in unity and get the result when they complete without using monobehaviours

#

i saw one example where they used Update() to keep checking if complete

#

but my jobs are not being run on a gameobject so i dont have that option

untold moth
#

Well, you'll need to check it from somewhere.🤷‍♂️
You could call a method in your non MonoBehaviour class from a MonoBehaviour update, a coroutine or an async method/loop. You need some kind of entry point.

steel snow
#

well im creating them from my api which are not inheriting from monobehaviours since its only crunching numbers it not related to gameobjects

#

i need some one way to run them async

#

but unity didnt seem to include a callback on complete type of feature

#

which seemed like a no brainer of an idea

untold moth
#

I'm not sure if it's even possible to schedule or finish jobs from non main thread. So a callback would probably just be invoked somewhere from the unity update loop anyway, which is kind of redundant. That's why there's no callback on complete. Probably.

#

Jobs are a way to offload work from the main thread, but you want to use their result on the main thread usually.

steel snow
#

dont regular csharp threads have callback supports ?

#

for completion/cancellation

untold moth
#

I'm not sure. I haven't used C# threads much. But jobs are not regular C# threads. They have different purpose.
If you want to use C# threads and they have callbacks, use them instead of the jobs.🤷‍♂️

brisk pasture
#

depends on how you implement it

#

you could do callbacks with regular C# threads, it async and await

#

its really up to you with them how you managing scheduling and executing them

urban warren
#

I have a bunch of objects that are generated, they can be different types. I am trying to figure out how to be able get groups of them sort of like ECS.
I need to get groups by type, or by a id (id of the thing that generated the object)

The only way that comes to mind to do this is requires a dictionary look up for every object one way or another. Also worth noting that the collection of objects needs to be serializable by Unity.
Any ideas or questions?

brisk pasture
#

as you generate them add them to dicts or hashsets

urban warren
#

Right, I was thinking about that but then I either have to repopulated them OnDeserialize, or serialize the same thing multiple times.

brisk pasture
#

still beats looping and type checking

urban warren
#

Guess you're right. Just wondering if there was a nicer way

lament briar
#

Hi! I'm coding a survival in a 3d map that's kinda like Valheim's map. The map is infinitely random and procedural, subdivided in chunks and it can have many thousands objects above it (trees and grass are the main objects). As many as 50 chunks can be loaded at once. The game itself with the world fully loaded runs at 80 fps with an old rx 480 and more than 170 fps with a 3060. It can easily handle thousands of objects loaded at once (spent many weeks optimizing it). With multithreading I reduced a lot of loading lag, but instantiating thousands of objects still lags a lot, taking away more than 100ms for every chunk, creating small "freezes" when the player moves and generates or loads new chunks. Currently my solution has been to create a spawn queue that instantiates a maximum of X objects per frame, but it still lags and if I enable the deep profiler even calling 5 times instantiates per frame takes more than 100 ms (I suppose it's the editor with the deep profiler that takes this much time). What can I do?

#

TL:DR I need a way to reduce instantiate lag

lament briar
stuck plinth
#

i think there's only so much you can do to get the cost of instantiating a particular object down because of the main thread restriction as you mentioned, is there any way to reduce the size of the objects being instantiated? reducing the depth of the prefab hierarchy, splitting objects up into multiple prefabs to load separately etc?

#

if you can guess where the player might go next and preload assets before they get there you could maybe spread out the cost over a longer period rather than doing it all when a chunk loads

fresh salmon
#

Pooling also, if some objects are instantiated very commonly

#

That way you only have to move them around when loading a new area

lament briar
lament briar
#

but they take a lot! Might it be the deep profiler?

#

Lag during normal gameplay without the profiler open is way less.

#

(for the other scripts that takes many ms in the screenshot - yeah i'm working on them)

lament briar
#

mainly because there are way too many objects, there's not a fixed amount and every object has different properties (scale, position, rotation and other data)

#

and the player could rotate and completely change the object that he's viewing, for example he might rotate in 2 seconds and the game should move 4k trees (and update all their data and transform) on the new direction

stuck plinth
errant plinth
#

Partial pooling is an option

#

That said, I would dig down in instantiate to see what takes up time

dusty wigeon
# lament briar mainly because there are way too many objects, there's not a fixed amount and ev...

You absolutely need to do pooling. This is not even a discussion. It is necessary for large game that has a lot of repeated element that needs to be instantiated regularly. Also, you do not need to pool in function of the view, only in function of the loaded chunk. Usually, you have a maximum amount of chunk loaded at the same time and you reuse the resources from one to the other.

You must also consider that Deep Profile is extremely heavy and that development build are also considerably slower. To have the best knowledge of the FPs you have, you should consider tracking it in a release build with an overlay.

lament briar
# dusty wigeon You absolutely need to do pooling. This is not even a discussion. It is necessar...

How would I do pooling with something like 10k trees? With 3 different types of trees. Of which each one could have one in 6 different meshes, and a completely different transform. And local data (like tree's age). Every object that gets reused would take probably more than the instantiate itself. If the player reaches a mountain, it could also look at half the loaded map, so the game would still need to instantiate 5k trees. And it changes by biome. Some trees spawns in a particular biome, so you might look at 5k pine trees. Another biome, 5k palm trees. Do I have to instantiate 5k trees per type? This seems simply worse than any solution.

#

It's not a top-down 2d game where you can see only 10, 20 trees at once. It's a 3d world

scenic forge
#

TIL * operator of things like float4x4 in Unity.Mathematics does component wise multiplication, thought I sucked at math.

brisk pasture
#

says in the docs, always double check for stuff like matrix and vectors since there are multiple things you could call a product for it

lament briar
# dusty wigeon You absolutely need to do pooling. This is not even a discussion. It is necessar...

That's a screen of what the player could see if he flies (I plan to add some flying features). Lag in-game (when the player is not moving) is prevented by gpu instancing. I still have a bit of memory problems, but I'm gonna fix them later. Let's suppose the player rotates the camera, in 2 seconds every tree in that view would be moved to the other side of the map. And what happens if the trees on the other side are another type of tree? Potentially another prefab.

lament briar
#

The main problem is that my game is a large game that has a lot of "repeated objects", as you say, but there are a LOT of different repeated objects. Many, many objects could be present in the scene, or not at all. It's simply impossible to pre-instantiate a large number of gameObjects for each object that could be present in the number of thousands. They could be 0, or 5k, and there's no way to predict that.

plucky trellis
#

I assume these objects need to be interactible, right?

lament briar
#

Yup, could be removed or placed. They also memorize how many hits they got by the player and the tree's age.

#

(they grow and change prefab)

plucky trellis
#

Hmm

dusty wigeon
# lament briar Same for the grass, which is way more common (even if it's loaded in only the cl...

Same for the grass, which is way more common (even if it's loaded in only the closest chunks). There are already 2 different grass types, and they follow the same tree's logic. Should I pre-instantiate 5k of each type of grass? This seems wrong.
You do not need to instantiate any grass. Grass should only be GPU instance.

How would I do pooling with something like 10k trees? With 3 different types of trees.
You only need 1 tree that you dynamic change. You could even only instantiate the tree on the GPU and simply have a pool of collider.

It's not a top-down 2d game where you can see only 10, 20 trees at once. It's a 3d world
You need to limit the view distance. The view distance is probably the easiest slider to make lower end device works.

The main problem is that my game is a large game that has a lot of "repeated objects", as you say, but there are a LOT of different repeated objects.
From the view I see there is tree. You can swap meshes and materials at runtime.

Let's suppose the player rotates the camera, in 2 seconds every tree in that view would be moved to the other side of the map. And what happens if the trees on the other side are another type of tree? Potentially another prefab.
You do not consider the camera (rotation) for the instantiate of objects.

plucky trellis
#

It could work if you maintaned a small pool of each object (like 50 at most) and moved them around to form a ring around your player, such that each tree the player could reasonably interact with would be a real tree. Having the gameobject refer to something else (like a global massive list of plain c# classes) for data, such that out of range trees can still remember how many times they have been hit

#

Then for any trees too far away to be "real" just gpu instance them without creating any gameobjects at all.

#

Dynamically swap in real gameobjects with the right data as the player moves and it could be pretty seamless

lament briar
# dusty wigeon > Same for the grass, which is way more common (even if it's loaded in only the ...

You do not need to instantiate any grass. Grass should only be GPU instance.
They're objects as the trees. Grass can have interactions (like, removed and placed again). Doesn't really differ by a tree from that sense.

You only need 1 tree that you dynamic change. You could even only instantiate the tree on the GPU and simply have a pool of collider.
I have absolutely no idea how to pool a single tree and use it thousand of times 😦 the pooling I know doesn't work that way (waht I know is that you instantiate a set of objects, and then move them where you need them. If they're out of the camera, you move them inside again, where the player is looking). Could you please give me some sources so I can better understand what you mean? Also, I'm already doing GPU instantiating. And this still doesn't fix the fact that the trees have a lot of properties that are loaded in its scripts, so they still need to be instantiated.

You need to limit the view distance. The view distance is probably the easiest slider to make lower end device works.
This will be a setting, so the low end devices can use the game. But many things must stay; for example the colliders. Decreasing the chunk size would impact gameplay since some entities are alive and move around even in distnat chunks (not too much far, but like 3 chunks max fromt he player)

From the view I see there is tree. You can swap meshes and materials at runtime.
What do you mean? There are a lot of different trees. The view is just very far and you've never seen them close so you don't really notice the differences.

You do not consider the camera (rotation) for the instantiate of objects.
That's linked to the second answer I gave; I have no idea of what type of pooling you're referring to

#

If you're talking about gpu instancing, that's already done by the shader, and it works greatly for the FPS during gameplay (it was literally unplayable without that setting, fps were less than 20). But that didn't reduce lag during instantiates.

dusty wigeon
# lament briar > You do not need to instantiate any grass. Grass should only be GPU instance. T...

They're objects as the trees. Grass can have interactions (like, removed and placed again). Doesn't really differ by a tree from that sense.
Grass is the text book use case for GPU instancing (Without GameObject). (by example: https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstanced.html) Also, you can still remove and place grass same if they are in the GPU.

I have absolutely no idea how to pool a single tree and use it thousand of times 😦 the pooling I know doesn't work that way (waht I know is that you instantiate a set of objects, and then move them where you need them.
Usually, pooling is done with instancing an object than reusing it. In your case, the object would be an hollow tree (No mesh, No material) that is dynamically constructed. Whenever you instantiate the object from the pool, you assign the appropriate mesh, position, scale and material.

not too much far, but like 3 chunks max fromt he player
In other words, you have 49 chunks loaded at the same time. Whenever you move, you unload a row of chunk (7) and the reuse the resources you just free to load the next row.

What do you mean? There are a lot of different trees. The view is just very far and you've never seen them close so you don't really notice the differences.
Instead of instancing a tree, you change the mesh and the material of an already instanced one. There is nothing more than that.

That's linked to the second answer I gave; I have no idea of what type of pooling you're referring to
I never saw a pool system that used the rotation of the camera. The only thing I can think of is frustum culling. This is not the same things at all and it does not reuse object. Pooling is usually done with things like projectile, audio source and VFX. However, you definitely can do it with other object. In your case, the tree could gain from that.

#

Personally, I would start by limiting the amount of objects in the game by limiting the view distance/chunk loaded to something appropriate.
Then, I would look into pooling for objects that are common and simple such as tree/rocks. I would not even use the hollow approach.
Nothing complicated, no GPU instancing of tree with pooled collider, straight GameObject with everything set on it. I'm pretty sure that would be enough for a considerable range of device.

#

Also, note that GameObject are relatively small in term of memory consumption in comparison to a Texture, an Audio Clip or a Mesh. Having 100'000 extra objects shouldnt be an issue.

#

(100'000 x 1000B = 100 MB) 1000B is way more than what most of your GameObject will/should cost. (Also, you will probably have less than 100'000 pooled objects)

A non compressed texture 2048x2048 (4 channel) is 16 MB.

lament briar
# dusty wigeon > They're objects as the trees. Grass can have interactions (like, removed and p...

Grass is the text book use case for GPU instancing (Without GameObject). (by example: https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstanced.html) Also, you can still remove and place grass same if they are in the GPU.

Yeah, when the object is just plain grass, that is never removed... just stands there and is a decoration. Grass is not a decoration in my game and has many interactions.

Usually, pooling is done with instancing an object than reusing it. In your case, the object would be an hollow tree (No mesh, No material) that is dynamically constructed. Whenever you instantiate the object from the pool, you assign the appropriate mesh, position, scale and material.

Ok - so how do I instantiate a single object and use it many times? I don't get that part. Also I doubt it's the mesh or the material that makes the instantiate lag, since it's already using the gpu instancing, and when I enabled that, each chunk loading dropped from more than 1 second to less than 100ms to load. It should not get reloaded into the gpu.

In other words, you have 49 chunks loaded at the same time. Whenever you move, you unload a row of chunk (7) and the reuse the resources you just free to load the next row.
Which resources? If I have a single tree and load it many times, it's still a single tree.. no?

Instead of instancing a tree, you change the mesh and the material of an already instanced one. There is nothing more than that.

Mesh, material, all of the transform properties and script data. Each tree has around 5 saved variables if I recall correctly. Plus, it has particle effects inside it. And 3 different LOD meshes and materials.

dusty wigeon
# lament briar > Grass is the text book use case for GPU instancing (Without GameObject). (by e...

We are just going in circle...

Yeah, when the object is just plain grass, that is never removed... just stands there and is a decoration. Grass is not a decoration in my game and has many interactions.
It might have many interaction, however, doing it through gameobject will definitely be an issue if you want a substantial amount of grass.

Ok - so how do I instantiate a single object and use it many times? I don't get that part. Also I doubt it's the mesh or the material that makes the instantiate lag, since it's already using the gpu instancing, and when I enabled that, each chunk loading dropped from more than 1 second to less than 100ms to load. It should not get reloaded into the gpu.
Exactly. That is why you change the material and other things instead of instancing a whole object. I really fail to understand why you do not see concept.

public void LoadChunk(Chunk chunk) {
  - Foreach TreeData
    - Tree = Pool.GetInstance(tree.prefab)
    - Tree.Init(TreeData);
}

public void Tree.Init(TreeData data) {
  - mesh = data.mesh
  - material = data.material
  - vfx = Pool.GetInstance(data.vfxprefab)
}

Which resources? If I have a single tree and load it many times, it's still a single tree.. no?
If it was, you would not be here. You would not need to instantiate multiple object each time you load a chunk.

lament briar
#

Well, we are going in circles because I don't actually get what you mean 😦

#

The code, for example, would work if all my trees were a single prefab, even for all the different tree types. Supposing that I spend a lot of time to refactor my tree system so it's a single prefab that loads and unloads all the tree data, how do I decide how many trees to load in the pool? 1k? 10k? What happens when there are no trees in the map? It's a big waste of resources. What if there are more trees? And when I'll have to add more items that needs to be pooled?

#

(like, the grass)

lament briar
bleak citrus
#

just like how a List<T> dynamically grows as needed, you don't have to fix the size of your pool

#

a very basic implementation would just allocate a tree every time you ask for one if the pool is empty

#

and would allow an unlimited number of trees to sit in the pool

#

Perhaps you could do some playtesting to work out a reasonable limit to the pool size

#

but, think of it this way:

#

if the game winds up loading 10,000 trees at one point, it's probably going to want to do that again

#

unless you have one freakishly heavily-forested region and the rest of the game is a desert

#

Pooling doesn't magically save you from needing to have 10,000 trees. It just means that you don't have to construct 10,000 trees from scratch every time you need them.

untold moth
#

Was the elephant in the room addressed already? The 3.5k batches 😅

dusty wigeon
# lament briar > If it was, you would not be here. You would not need to instantiate multiple o...

It is the exact same principle... Except that instead of simply changing the position, you change the mesh as well. It is like you cannot fandom the idea of having object constructed at runtime.

Also, as I stated, 10k is not that much in term of memory. And as stated by chemicalcrux, you can dynamically adapt the size of your pool.

Finally, I would not even do that. I would simply reduce the amount of chunk or size, implement a view distance and use simple pooling by prefab.

dusty wigeon
untold moth
fickle tinsel
#

Props to @lament briar for using and showing the profiler information. As a lurker I see plenty of conversations about "muh performance" and no party ever just profile their game.

bleak citrus
#

💥

dusty wigeon
untold moth
dusty wigeon
#

Is it better to do i++ or ++i.

#

That is the one that gets me.

bleak citrus
#

I think that used to matter in C++, depending on your compiler and the alignment of Jupiter's moons

fickle tinsel
#

You have to avoid one copy command so obviously never do i++. I'm ignoring that modern day compilers produce the same machine code when you use i++ or ++i.

dusty wigeon
#

Maybe copy

bleak citrus
#

since you gotta return the original value

dusty wigeon
#

However, the difference is rediculous

real blaze
#

the only difference is that ++A invokes the + operation and then uses A, while in A++ it first uses A and then applies the + operation

#

so

int A = 2;
log(A++); // 2
log(A); // 3
A = 2;
log(++A); // 3
log(A); // 3
#

in both cases, whether or not the A is copied depends on the implementation of the + operation. for structs it usually copies

jolly token
dusty wigeon
real blaze
#

what do you mean?

dusty wigeon
#

Yeah, I though that also. People usually do i++

real blaze
bleak citrus
#

oh no, we've gotten nerd sniped

dusty wigeon
dusty wigeon
#

What have I started.

tiny pewter
#

__asm__:......

real blaze
jolly token
bleak citrus
jolly token
#

So ++i; vs i++; alone

real blaze
real blaze
fickle tinsel
bleak citrus
#

C compilers are extremely scary

real blaze
fickle tinsel
near gull
#

Hello, how would I go around calculating the speed of an Android device? I've already tried using the accelerometer, but the sensor is probably low quality and 80% of the times doesn't detect decelerations. Also tried GPS, but it doesn't detect the speed correctly most of the times. My question is are there any other methods of obtaining the velocity of a device?

#

Knowing me I probably missed one step in the code, so here is the accelerometer-based detector:

void OnEnable()
{
    Input.gyro.enabled = true;
    Input.gyro.updateInterval = 0.001f;
    InvokeRepeating(nameof(AccelerationSample), 0.0f, 0.001f);
}

void AccelerationSample()
{
    accel = Input.acceleration - Input.gyro.gravity;
}

void Update()
{
    t.text = Mathf.Sqrt(accel.x * accel.x + accel.y * accel.y + accel.z * accel.z).ToString();

    velocity += accel * Time.deltaTime;
    velocityMagnitude = Mathf.Sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z);
    kmPerHour = velocityMagnitude * 9.81f * (18f / 5f);
}
regal olive
#

One option is using the magnetometer sensor to measure changes in orientation and calculate speed indirectly. But keep in mind the magnetometer can be effected by magnets.

regal olive
near gull
#

trying to make a little fun app to play motorbike engine sounds based on speed

sly grove
#

like

#

are you expecting to use this in a car?

#

while walking?

#

Also why Unity for that?

near gull
#

it's the program which I know most, and I can change the audio pitch very easily in it

sly grove
#

In general phones don't really have the hardware for precise velocity measurements.

near gull
#

I'm trying to use it outside

sly grove
#

The best you can get is something like what google maps does which updates your speed about once every few seconds based on GPS data

near gull
#

I tried that already

sly grove
#

yeah, it's not that accurate

#

again, phones don't really have the hardware for precise velocity measurements

near gull
#

it was not accurate at all in my case, probably my phone was using the cell tower signal and not real GPS

sly grove
#

btw you have a lot more control over where the gps data comes from when you make a native Android or iOS app

#

I think such an app as you described would be a lot easier to make that way, not in Unity

#

I can change the audio pitch very easily in it
Seems like a really weak reason to use Unity for this

near gull
#

eh, I've got some experience with unity and not a single bit of Java/Kotlin

#

I'll try the code that Mohammed sent me

#

Still doesn't detect decelerations with fast movements, only seems to work with slow movements

formal lichen
#

If you know~~ C#,~~ Microsoft Java, java is pretty easy to pick up

fickle tinsel
near gull
#

alright, I'll consider switching to a native android app, thanks for the quick responses!

formal lichen
tawny sand
stuck plinth
timber flame
#

It is not just one icon + one text

#

It can be anything

#

An item can have one icon + one text + two other images + three texts + a progress or bla bla.

#

Creating a generic class ItemList<T> I can isolate common functionalities such as add, clear, delete, update regardless of item types

formal lichen
#

well that sounds like a cruddy way to do it

untold moth
scenic forge
#

Is there a better way to write the following code? p0 to p3 are float4.

var min = math.min(p0, math.min(p1, math.min(p2, p3)));
var max = math.max(p0, math.max(p1, math.max(p2, p3)));

return _isY ? (min.y, max.y) : (min.x, max.x);
tiny pewter
#

i think this is fine, but i prefer write in this way

float4 min=a
min=math.min(min,b);
min=math.min(min,c);
...
#

more lines but easier to extend

#

you only consider the x y component of float4 maybe just compare them without compare the whole float4, idk how math.min works

#

the docu says componentwise......

scenic forge
#

Oh I guess I could do:

var values = _isY ? new float4(p0.y, p1.y, p2.y, p3.y) : new float4(p0.x, p1.x, p2.x, p3.x);

return (math.cmin(values), math.cmax(values));
scenic forge
#

Eh this is DRYer but harder to understand and probably performs worse, I guess I'll just stick with the previous one.

var matrix = math.transpose(new float4x4(p0, p1, p2, p3));
var values = _isY ? matrix.c1 : matrix.c0;
return (math.cmin(values), math.cmax(values));
muted root
#

Hello, my game uses lots of blendshapes to create custom characters, as well as custom clothes which have their own blendshapes too. But the result seems to create too many calculations and the game becomes very slow when I just pop 9 characters on screen.

#

Is there any way to optimize the number of calls besides reducing the number of blendshapes?

burnt hamlet
#

what equation does Unity use for addForce?

#

I'm making my own movement code which involves setting velocity, and I just introduced an equation that adds drag to any existing force, but when a force is being constantly set it negates drag, so I need a way to add to the force without canceling out the effects of drag

frozen imp
burnt hamlet
frozen imp
#

the default force mode

burnt hamlet
#

so whats the equation the engine does for that?

frozen imp
#

why are you inventing a bicycle though. Use existing physics system, just manage corner cases when you need to change behavior.

tall ferry
#

If you really need the equations (which I dont think you do in this case)

burnt hamlet
#

its because I'm building a system where I can calculate a theoretically infinite number of forces effecting an object and only have to actually apply the velocity once per game update, rather than doing it multiple times and having lots of conflicting velocities with unclear relationships, fighting for priority of what the objects velocity should be

#

since setting velocity is computationally expensive, I want to minimize the number of times, only once if possible

tall ferry
#

What you described is still completely and easily possible using the addForce function, other objects would just affect some other vector3 to say what additional force should be applied to the player.
The ONLY difference that I know of with doing it yourself vs using addForce is that addForce doesnt happen right away, it happens during the physics loop. Meaning velocity isnt set within the same fixedupdate

burnt hamlet
#

this is the method I'm using to add the forces together to get one final Vector2 for the velocity

#

though I just noticed there are some deprecated parameters left in there

#

Force being a data type I made that just stores a float and a Vector2 for the direction and speed of a force

#

and this is the code applying drag

#

iterates through each force and reduces them over time, and in practice it feels right, I can raise and lower it and forces set have greater or lesser effect, but then there's the continuous force problem I mentioned

#

that aside, looking at the addForce image it doesnt have parts of the equations in brackets to seperate them, is that how its supposed to be?

tall ferry
burnt hamlet
#

to specify that certain parts should be calculated independently of another part, or are they already written in an order such that brackets arent needed?

tall ferry
#

If you're referring to f * dt/ m, brackets dont affect anything

shadow vigil
#

Has anyone here used damped springs? I'm attempting to apply a critically damped spring for movement, which controls a positional change by increasing or decreasing velocity with an acceleration value until the target velocity is achieved. However, the acceleration changes with the velocity on each update until the target value matches. Hence, I'm not sure if altering the initial acceleration value would be a valid way to speed up the spring.

burnt hamlet
#

I just tried including mass in the gravity speed and the higher the mass the slower an object fell

#

that doesnt seem right

shrewd rover
burnt hamlet
#

figured as much

#

air friction I've already accounted for with drag

#

and when I add friction I'll just repeat drag but with a separate context, unless for some reason friction is very distinct in effect

bronze lark
#

Ok I got a GraphicsRayCaster that's not hitting any graphics. ... it's on a canvas nested into another canvas. (the outer canvas is Camera Screen Space). Never seen this before.
What are the prerequisites?

#

Ok, nested canvas... can't receive raycast?

#

Another canvas, further DOWN in the trnasform order, seems to be stealing the RCs.

#

Well, anything nested inside the transform I want to select stuff in seems to not get the raycasts.

sly grove
#

so this makes sense

bronze lark
bronze lark
#

Wow, even if I COPY another object that works, and use it as the Pip Surface, it doesn't work.

#

Order doesn't play a role btw.

jolly token
#

Because you need that

misty glade
#

I have some hex based methods that I want to be really fast and lightweight but don't know a lot about what I should be focusing on or doing to optimize. For background, I have an "open world" hex coordinate system, so I'll be using these methods often for pathfinding and gameplay. Any suggestions? Are the List allocations bad?

https://pastebin.com/1eKk3WBH

Don't worry too much about the functionality - it's already been tested and works to my satisfaction. I know the code is kind of dense - algorithms from https://www.redblobgames.com/grids/hexagons/ if you want to dig into it.

#

this struct will be used to draw the tiles in my Grid and pathfinding so.. it has to be pretty quick

sly grove
#

GetHexesInRange is something that will run extremely often

misty glade
#

should I keep a list in the struct and .Clear() it? or just use some other data structure

sly grove
#

I would make this function take a list in which to dump its results into

scenic forge
#

Make the method take a list.

sly grove
#
public GetHexesInRange(int range, List<HexGridPoint> resultsList)```
#

and it can add things to that

#

then the caller can reuse a single list many times

misty glade
#

hm... ok

#

Do you think the method should clear the list (and assume it's already been new()'d elsewhere?)

sly grove
#

I would leave clearing the list to the caller

misty glade
#

the newing is the expensive op, yes?

#

k

bronze lark
#

I don't.

#

Wtf.

sly grove
# misty glade the newing is the expensive op, yes?

new and Add can be expensive whenever the list needs to be reallocated for size. Cleaning up old lists with the garbage collector is also slow.
If you reuse a single list you basically eliminate all of these costs.

misty glade
#

ah, yeah, i forgot about resize costs

sly grove
#

once the list is resized it won't need to happen again. Even when you Clear it, the allocation remains the same

misty glade
#

I could probably cheat and allocate the list with some hard coded values since I already know the resultset size

sly grove
#

you can create the list with preallocated capacity

misty glade
#

(ie, range = 0 is 1, range = 1 is 7, range 2 is .. 20?)

sly grove
#
myList = new List<HexGridPoint>(maxCapacity);```
#

in the grand scheme of things this is a minor optimization compared to the list reuse though

scenic forge
#

If you are going to reuse the same result list all the time, it's not going to matter much if you give a good initial capacity

sly grove
#

reallocation will only be a one time cost per list - yea

#

but still if you have the data available, might as well

bronze lark
# bronze lark I don't.

Ok, I do something funky. 🙂 Oh boy. Th is is going to be hard. (I think I already resolved what that workaround was for, but let's just say Screen Space - Camera canvas mode cements Unity's failure as 3 for 3 in the options there are.

misty glade
#

yeah i.. have to think more about pathfinding and "aoe" type effects in my game.. when it comes to these methods though, is the memory allocation kind of the part i should be concerned about? i'm assuming the operations with the int primitives are going to be super fast compared to that

#

ie, trillions of ops per second no problem

sly grove
#

idk about trillions but yes memory management is often a big issue

#

and often the easiest to optimize

#

What you should be doing though is using the profiler to find the most costly things and focus your efforts on those

misty glade
#

k.. the algorithms themselves are a bit of black magic to me but I drew them from that dude who's smarter than I am, and the tests seem to work

#

yeah I was just googling up on benchmarkdotnet to see if it plays nice with unity

#

my hand rolled profiling kinda sucks

sly grove
#

yeah these look like helper functions for A* or Djikstra pathfinding yes?

sly grove
misty glade
#

yeah i know.. i meant like.. lemme paste this paragraph

#
Let's think about what you should do in a typical case. First, you should perform a pilot experiment and determine the best number of method invocations. Next, you should execute several warm-up iterations and ensure that your benchmark achieved a steady state. After that, you should execute the main iterations and calculate some basic statistics. If you calculate some values in your benchmark, you should use it somehow to prevent dead code elimination. If you use loops, you should care about the effect of the loop unrolling on your results (which may depend on the processor architecture). Once you get results, you should check for some special properties of the obtained performance distribution like multimodality or extremely high outliers. You should also evaluate the overhead of your infrastructure and deduct it from your results. If you want to test several environments, you should perform the measurements in each of them and manually aggregate the results.
#

I don't do any of that - i just run a loop a few million times and look at the profiler

#

🤷‍♂️

sly grove
#

oh yeah that's for benchmarking

#

I think the best way to profile is to actually just play your game though

#

unless you don't have that in place yet

#

and you're just testing this base layer functionality

misty glade
#

Yeah this one's hard though - since I haven't built the game yet but I already know that these methods are going to be used everywhere.. Revealing fog of war, aoe effects, pathing, mapping, tile/biome generation etc

sly grove
#

I wouldn't be overly concerned with benchmarking accuracy though. THis is more about finding the bottlenecks in the code which should be apparent even if you aren't doing benchmarking warmups etc.

misty glade
#

It's kind of like if I were writing int operator+ .. I'd want to like.. work really hard at making sure it's good

#

at this point as long as it works and isn't horrible, I suppose I'm ok. That's the bar I'm trying to clear. "Isn't horrible"

#

19 tiles, everything's good. 👍

jolly token
#

Minor tho

misty glade
#

Not sure, it's above my pay grade to understand. 😛

#

I just used the author's algorithm verbatim and tested it as thoroughly as I could for functionality. I'm assuming that %2 is going to work the same. Y/2 won't work though since it'll give 0 for Y = {-1, 0, 1}

jolly token
#

Oh yeah I wasn’t thinking negative nums

#

Guess in that case Y >> 1 is simplest

fickle tinsel
# misty glade I have some hex based methods that I want to be really fast and lightweight but ...

My suggestion is to ignore performance advice that you can't validate by looking at the Unity Profiler measurements (docs https://docs.unity3d.com/Manual/Profiler.html) and understand the concept of a "performance budget" for your particular app.

Most people on the internet don't actually know what they're talking about when they give performance advice. In fact many of those people don't apply the concept of a "performance budget" where expensive operations are A-OK as long as it fits into your performance targets. Even really shitty unoptimized code is okay if you're hitting your FPS targets and you're within your performance budget of your particular app as an extreme example.

#

If you learn to use the profiler you're going to be LEAGUES ahead. Same is true for non-game code too FWIW.

P.S. I'm not saying the discussion that happened here is BS or anything. My advice is generally true which is why I'm sharing it. 🙂

sly grove
# misty glade

by the way the Debug.Logs that are printing this are likely the most expensive part of this code

bronze lark
#

Screen Space Camera Canvas culls against the RectTransform's 2D portions, it seems.

#

Well, actually it's each canvasrenderer node. (?) or each rect transform. It doesn't even affect raycasts, just the rendering.

#

I can circumvent it by adding a transparent image and turning off "Cull transparent mesh", but obviously that's pretty bad.

#

(I'm placing transforms in 3D in the canvas, this generally works, and it works in a way that I suspect this new behaviour is a bug, only for Screen Space Camera)

steel snow
#

is many submeshes typically a performance optimisation vs seperate meshes

#

or is there some limit to that

bronze lark
#

Yep, works with World Space, which is funny. I can, due to another workaround, use world space as screen space. Okayyyy. This feels hacky. 😄

#

I don't even understand how that works, lol.

#

Dimensions of a world space canvas have zero effect on the camera frustum it is in, or vice versa. Good to know. 😄

waxen ruin
#

I didn't find any appropriate channels, so i'll use this one.
i need to compile c# code at runtime, and i know i can use some Microsoft.CodeAnalysis packages
i downloaded them and referenced them into the Assembly-CSharp assembly
i also edited the said assembly ".csproj" file, and manually wrote the references
problem: unity doesn't care, keep saying references are missing, and when i close and reopen the editor my modifications to the ".csproj" are gone

upbeat path
#

you will need to put the .dll's in a Folder called Plugins for Unity to recognise them

waxen ruin
#

let me try, thanks in advance

upbeat path
#

inside Assets

waxen ruin
#

ok

timber flame
#

but because an item can be updated and this item has specific data to be updated, the generic is one of reasonable solutions

#
public class ItemList<T>: MonoBehaviour where T:BaseItem{
   [SerializeField] private T _prefab;
   private List<T> _items = new();
   // events (Added, Removed, Cleared, Updated)

   public void Add(T item){}
   public void Remove(Guid id){}
   public void Clear(){}
   public void UpdateItem(T item){}
}
public class SpecificItemList: ItemList<ItemA>{}
waxen ruin
# upbeat path inside Assets

error CS1705: Assembly 'Microsoft.CodeAnalysis.Scripting' with identity 'Microsoft.CodeAnalysis.Scripting, Version=4.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
error CS1705: Assembly 'Microsoft.CodeAnalysis.CSharp.Scripting' with identity 'Microsoft.CodeAnalysis.CSharp.Scripting, Version=4.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

#

i kinda understand what it's saying but i don't get why

#

i copied the dlls inside the "net6.0" folders

upbeat path
#

Unity does not support .net6

waxen ruin
#

.net core?

#

thats what i got for each of them

upbeat path
#

depends on your Unity version, latest is .net Standard 2.1

waxen ruin
#

ok thanks

errant thorn
#

Imagine you were making an RTS where the "time of day" was very important. Special events happen at different times. This can be like a door opening at 12pm, or an enemy leaving work at 5pm, or the sky progressively going to sunset as time passes. How would you set up a system like this?

Would you have some type of "TimedEventManager" where entities could send their timed tasks to, and when it becomes that time the task activates?
Or maybe all the entities get told when the day starts and handle their own timekeeping individually?

upbeat path
#

you are asking for a world of pain doing stuff like this if you dont realy understand what you are doing

waxen ruin
#

error CS1705: Assembly 'Microsoft.CodeAnalysis.Scripting' with identity 'Microsoft.CodeAnalysis.Scripting, Version=4.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

clearly lying, i copied from the netstandard2.0 folder

upbeat path
#

you do know that Unity does not use Microsoft .Net?

waxen ruin
#

wdym?

upbeat path
#

exactly that

waxen ruin
upbeat path
#

May I suggest you go and do some research into Unity before continuing along this path

steel snow
#

Is it allowed to do this in unity editor api:
var data = serializedObject.FindProperty("_meshData[" + index + "]");

#

where _meshData is a List

#

im getting a null ref - wondered if its because i can't index into it like this

upbeat path
#

not allowed, get _meshData and index into data

#

this is why we dont use var

steel snow
#

hm i see it just seems to have broken everything when i switched to a list from an array

#

see i add an element to the list but my serialized property seems to think the array size is still zero

#

when i used an array it worked fine

#

but i need a list anyway since i need to add/remove

#

oh god damn i forgot to up call update on the SO

#

ok works now 😄

misty glade
smoky pike
#

tell me, is it possible to make the character go through all physical colliders of players and enemies, but have the opportunity to see both of them with the trigger?

#

I am using a CharacterController and a Sphere Collider(trigger), I need the CharacterController to be able to pass through other players and enemies without obstruction

sly grove
#

put the sphere collider on a child object with a different layer

smoky pike
#

and did that too

#

see the character is marked as Ghost which has no collision with all other characters and the child is marked with default layer. It doesn't work for me

#

I don't use rigidbody

cerulean minnow
#

Can I use a dictionary in a scriptable object?

smoky pike
sly grove
#

different layer for the trigger

cerulean minnow
sly grove
#

you can't serialize disctionaries though

#

so make a list of a struct that has the keys and values

cerulean minnow
cerulean minnow
#

Store and reconstruct later? Like closing and reloading the app?

sly grove
cerulean minnow
#

Oh ok. So I wouldn't see unserializable data in the inspector , like in my above example with the dictionary

smoky pike
cerulean minnow
exotic trout
cerulean minnow
exotic trout
#

yeahhh

#

honestly tho ive had a great time with ayellowpaper's

#

i have odin inspector and ended up using ayellow's implementation instead haha

shrewd rover
# sly grove you can't _serialize_ disctionaries though

I've seen a tutorial that teaches how to create a serializable dictionary class and it's not too complicated. I've been using it in a personal project to be able to save dictionaries in the save game file and it's been working

sly grove
#

but you can't serialize them out of the box

gritty python
#

How do i use HttpClient on linux dedicated server?
If not possible can i use unity http client on a background thread?

#

I`m having some certificate trust issue on linux

gritty python
#

Error sending request: Error: TrustFailure

gritty python
#

if anyone has this error i fixed by installing ca-certificates on server dockerfile ...

frosty patrol
#

I have a struct, I want the IntPtr of the struct to pass to some function (custom plugin) how do I convert the struct object to a IntPtr ?

burnt hamlet
#

if I have a variable being inherited from a class, is there any way (without using custom editors) to make the variable show in the inspector for the original class and all inheriting classes, except for a specific one?

#

as an example of the use case for this, say I need to manually edit a Jump_Height variable for most enemies in a game inheriting from an Enemy class that stores the shared methods and data, but a few enemies doesnt jump, so having the Jump_Height variable in the inspector is unnecissary clutter

compact ingot
#

You should also consider not going down the inheritance route with your classes

burnt hamlet
#

is there an alternative way to inherit variables and methods?

compact ingot
#

Not inheriting in the first place

#

Use composition

burnt hamlet
compact ingot
#

You’d make an ‘actor’ component maybe, that actor can have ability components, one of them being jump, another being hostility towards the player

burnt hamlet
#

so breaking things into various component scripts?

#

or is there a way to make one script contain many components?

compact ingot
#

that’s how unity is supposed to be used and the most powerful/flexible feature of it. Just make sure your components aren’t too fragmented so you still understand what they are as a whole.

compact ingot
burnt hamlet
#

in the current case I'm using inheritance I'm using it for what it's meant to do, have a class with basic features that should exist in every subtype of it, then make subtypes inheriting from it but adding new things

#

which is also why I used the Enemy example, having types of enemies that all inherit the same core functions, if most enemies have a Jump_Height variable than its useful to have in all of them, just not always show it

#

is it not the purpose of inheritance to avoid repeating code?

#

to be clear, I dont think composition is a bad idea, its good for cases where two very different things still need to call each other on the same object, but I'm just not sure if it fits this use case, since I could see it causing a tower of components in the inspector down the line, all just to run one script with 10 or more dependencies it's pulling from

#

whereas inheritance lets you have a script hierarchy leading down to the specific component on your gameObject

lofty forum
#

What is the best way to return a value from a Job? NativeArray<T> of size 1?

slow remnant
#

NativeReference<T> maybe?

lofty forum
timber flame
#

I cannot find rect3d in unity, is there any functionality like Rect but in 3d space in unity?

tiny pewter
novel plinth
#

^

frosty patrol
#

Why is unity's color 4 floats and not a uint32 ?
Uint32 is more close to what the hardware/graphics api would expect for textures

#

Or 4 bytes (4 bytes == uint32)

#

This makes its slower for me to constantly update a texture each frame

sage radish
fresh salmon
#

And HDR, to achieve these colors you usually pass values greater than 1.0

frosty patrol
spiral zenith
#

So a value between 0 and 3 for red, one for green, one for blue and one for alpha, that's not much 😅

frosty patrol
#

1 byte is 0-255

spiral zenith
upbeat path
#

Colour8 is shades of grey where 0 is black and 255 is white

spiral zenith
#

Wait what is a channel?

frosty patrol
frosty patrol
#

In unity normal color is 4 floats iirc

spiral zenith
#

Yes OK 🙂
So what I meant is that a Color32 is 8 bits for each channel

#

And Color is a float (32 bits) for each channel

frosty patrol
upbeat path
#

yes

frosty patrol
#

Ahhh that makes sense

#

Can I use it with texture.SetPixels ?

upbeat path
#

but Color and Color32 are interchangable in Unity

upbeat path
frosty patrol
upbeat path
#

Also GetPixels32

#

you know this is all documented

frosty patrol
#

Most of my work has been in c++ using vulkan itself not in a game engine

upbeat path
frosty patrol
#

Not used to have everything been managed for me

upbeat path
sacred linden
#

When i try WebGL Build

#

How can i fix it guys?

#

My Publishing Settings

stuck plinth
#

UMP is a plugin right? you probably want to ask the author of UMP for support with that

frosty patrol
#

Why couldn't c# just have a void* and allow all objects to be convertible to it 🥲

#

Would make marshalling data that much easier

stuck plinth
#

it does! you can write void* in unsafe code

tiny pewter
#

c# has void*....

#

the intptr itself is a wrapper of void*

sacred linden
upbeat path
#

yes, but tbh, if you are going to write unsafe in C# you may as well just use C++

frosty patrol
#

I didn't get it to work

tiny pewter
#

you have to enable it in project setting

#

allow "unsafe" code iirc

stuck plinth
#

if you're using asmdefs you have to turn it on for each asmdef too i think

heady void
#

How can i stop an object from falling from uneven ground/a hill via its velocity?
Gravity physics are causing it to fall, Ive been thinking about applying inverted force to nullify it perhaps
I wrote code that simply tries to reach 0,0,0 velocity if the object is not moving, that stops it from falling when its in place
But when the object is moving, it will be falling always

upbeat path
craggy sierra
frosty patrol
craggy sierra
#

Yeah that sounds about right

frosty patrol
#
  • having general knowledge about how dynamic libraries work
#

And how they are loaded

#

Etc

#

If u use c++ I would highly suggest just understanding creating dlls and loading them at run time
That would give you alot of clarity

craggy sierra
#

I have some base level of how dynamic libraries are loaded because I had to scratch the surface of that when I was making my OS kernel

#

But windows probably does weird bs with DLLs

frosty patrol
#

And almost every language ever will support c/c++ code in some form or another

frosty patrol
#

Just the api is different

#

Main thing is how do you marshal data from 1 language to another
That's gonna take some time to figure out and will make your life easier once you do

craggy sierra
#

Yeah

#

The engine I use auto-generates the bindings between c# and c++ which is handy but not for understanding it XD

frosty patrol
#

Prior to what I am working on, I never used unity or c#
So it was a learning curve
C# is a weird language for someone coming from c++ and python

craggy sierra
#

I mean I guess thats fair
What part was weird?

#

Although this is slightly off topic

frosty patrol
#

Unsafe requires a special flag
The syntax for type casting is more specific (than in c/c++, there are multiple ways to do the same cast)
U can't convert anything in IntPtr simply, it's a process (done GCHandle and other stuff ??)
Structs have layout options?
And so on

#

Also I have no idea how to marshal non trivial data like shared pointers

upbeat path
#

just dont use pointers

frosty patrol
upbeat path
slow remnant
#

Can I ask here DOTS questions? Or it is only for usual Unity?

heady void
flint sage
#

You can but it's more likely you'll get an answer in dots forum

slow remnant
#

Okay, thanks

frosty patrol
#

everything primitive in c# is atomic ?

#

did I read this correctly

dusty wigeon
frosty patrol
frosty patrol
#
Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, need not be atomic. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.``` so only primitive types, my struct isnt atomic by default
#

what about containers ?
they are also not going to be atomic then right

dusty wigeon
#

What are you even trying to do

#

And what you expect the atomicity to do.

frosty patrol
dusty wigeon
#

If you do if(bool) then it does not matter the atomicity of your type

#

Also, read-modify-write operation is not atomic.

frosty patrol
dusty wigeon
#

So, you gotta clear out what you want to do.

frosty patrol
#

maybe I should just use a mutex and call it a day

dusty wigeon
frosty patrol
dusty wigeon
#

In other words, you could have 2 thread executing the if body

frosty patrol
#

the other thread is doing other work

#

its kinda used for updating something in the main thread with the work done in a secondary thread

dusty wigeon
#
Thread 1
if (my_bool_var (true)) {
  -- Interuption
  my_bool_var = false;
  ....
}

Thread 2
if (my_bool_var (true)) {
  my_bool_var = false;
  ....
}
#

Both will run the if

#

I'm not an expert in threading, but I'm pretty sure that situation is possible.

frosty patrol
#

thread 2 doesnt read the value at all, just assigns it to true regardless of its current value
main thread is the only thread that actually reads the value before resetting it to false

frosty patrol
dusty wigeon
#

Using a mutex is more safe and it signals your intent as well.

#

Also, you would need to use the volatile keywords I think.

tiny pewter
#

suppose worker thread is something like
code segment A->set the bool->code segment B
and min thread
wait bool->????
then your main thread has to wait for code segment A finish, that means multithreadings is useless here

dusty wigeon
#

To prevent compiler from doing optimization.

dusty wigeon
#

It also does not mean to block the whole things.

#

You can do that in Update loop

#

Not necessary a while

frosty patrol
dusty wigeon
# frosty patrol fair enough, I should probably just use a mutex which will guarantee it being co...
public class Worker
{
    // This method is called when the thread is started.
    public void DoWork()
    {
        bool work = false;
        while (!_shouldStop)
        {
            work = !work; // simulate some work
        }
        Console.WriteLine("Worker thread: terminating gracefully.");
    }
    public void RequestStop()
    {
        _shouldStop = true;
    }
    // Keyword volatile is used as a hint to the compiler that this data
    // member is accessed by multiple threads.
    private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
    public static void Main()
    {
        // Create the worker thread object. This does not start the thread.
        Worker workerObject = new Worker();
        Thread workerThread = new Thread(workerObject.DoWork);

        // Start the worker thread.
        workerThread.Start();
        Console.WriteLine("Main thread: starting worker thread...");

        // Loop until the worker thread activates.
        while (!workerThread.IsAlive)
            ;

        // Put the main thread to sleep for 500 milliseconds to
        // allow the worker thread to do some work.
        Thread.Sleep(500);

        // Request that the worker thread stop itself.
        workerObject.RequestStop();

        // Use the Thread.Join method to block the current thread
        // until the object's thread terminates.
        workerThread.Join();
        Console.WriteLine("Main thread: worker thread has terminated.");
    }
    // Sample output:
    // Main thread: starting worker thread...
    // Worker thread: terminating gracefully.
    // Main thread: worker thread has terminated.
}

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile

stuck plinth
#

it's worth looking at the Interlocked class for simple atomic operations, if you just need a single atomic flag it's much simpler than mutexes

tiny pewter
#

i see.... so you have a long running background thread or task or whatever that monitor something and trigger the (Unity) main thread, i think it is just fine if the background thread is write only (to that trigger), even the main thread miss it will catch up in next update loop (since you cant block or even sleep the main thread, so no cond signal or await or sleep), and use volatile to keep the variable always in memory like what simferoce says

#
worker:
void Work(){
  while(true){
    if(something update){
      trigger=true;
    }
    while(trigger){
      //find some way to sleep it and wake it up, idk how to do this in c#
    }
  }
}
main:
void Update(){
  if(trigger){
    OtherWork();//prevent the worker check something update twice and main thread miss one
    trigger=false;
  }
}

btw the background thread may not write only....

scenic forge
#

Or you can just use UniTask.