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.
#archived-code-advanced
1 messages · Page 77 of 1
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....
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?
perhaps using these flags?
https://docs.unity3d.com/ScriptReference/HideFlags.DontSave.html
Thanks, I'll check that out
its a local application on the same commputer
Sure. awscli, docker and kubectl (and others I'm sure) are command line interfaces (CLIs) that interact with something else using RESTful interfaces.
No reason you couldn't use that as inspiration to have Unity talk to your console application via RESTful interfaces, if that's really something you want.
well i need to do that if i wont figure out how to do this in unity
That said, if you're just trying to find an authoritative server to validate if a player on their client are violating some game rules (like walking through a wall) you'd probably be better served by using unity multiplay (or mirror) and setting up a game server
well i want to make my own game server
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
I've never heard of signalR hubs
well possibly you still might know how to do this in unity?
Im pretty sure signalR isnt the only service using this
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.
I have no idea otherwise. I live at the higher level of abstraction afforded by using Unity Mirror or Unity Multiplayer.
What you’re describing is kinda like trying to make your own game engine. Your ambitions are so much greater than mine >.<
No I'm just trying to have the server run in unity on the same scene as the clients cus then every time someone updated there position I cud past a raypast from there old position to there new one if it hits something they collided with something simple
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?
You might want to check out Unity multiplay. You get that stuff essentially for free
Yea what you’re wanting is called “scene interest” you can run multiple copies of the same scene but players in one scene are isolated from other scenes
Ik but I want to keep the server code off the client release and I want to have a lot of control cus I'm trying to make an MMO and also just learn about all that stuff so I want to do it myself
When you build using multiplay you have two game software: one is the player client software and the other is the game server. You control what is in the game server software and what’s in the client software.
It’s conceptually similar to PHP; even though PHP is sprinkled all through your HTML, your users never see the PHP.
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?
That’s not true…
https://github.com/MirrorNetworking/Mirror/blob/master/Assets/Mirror/Core/InterestManagementBase.cs
See if that has answers, although it leverages UnityEngine so it might not fit your use case
Il look into it
You should probably figure out if you want to build an MMO or a DIY game server. Doing both seems like it’ll increase the odds of failure 😦
That's why I'm trying multiple things
Some people create separate builds if this is really a concern for server and client. But even members on the netcode team said this realllllly isnt needed in like 98% of cases
I have a separate branch for the server on git
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
#↕️┃editor-extensions
There may also be existing assets that allow this
I'll ask there thanks 🙂
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?
You want to know why it is looping first. Otherwise, you just gonna end with an other issue. (The function will not do what it is suppose to do)
yeah, i gotta learn the reason why first
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?
If you're workspace is dirty you can git stash the changes, switch to branch B, push your changes, switch back to branch A and then run git stash pop
I'm using Plastic scm software, don't you know how I can do it there?
Not really. Is plastic SCM software based on git?
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?
No, although it is similar it is not based on git
What's it based on?
Maybe just commit your changes in branch A then switch to branch B
Why not Resources.Load
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
Who is "their"? Your company?
Plastic csm
Plastic scm is one of the major solutions for version control. Unity happens to use it as the official version control solution.
https://docs.plasticscm.com/ Looks like it was bought out by unity. What a mess @_@
It's what I was thinking but since it's a test development maybe it won't be deployed in the "A" branch, and I can't put the changes there, the problem is that when I realized that I was working in the wrong branch it was already too late I already had many things in advance
I could help you if you were using git in exactly how to resolve that issue. However...
It seems to be called Shelving in plastic scm. It should be in the GUI somewhere.
In the check in drop down?🤔
Google plastic scm shelving.
Yes!, in pending changes there is the "Shelve" button
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
Don't worry, thank you very much for your help, I know how to use git but this time I decided to use Plastic scm because it gives me more GB of storage in the free plan and it was also much easier to upload my project unlike github
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
Every platform has resources. It wont be a folder though. The files are something like resources.assets and resources.resource.
I am going to try
You can’t access bundled asset with file system. You need to either use Resources.Load<TextAsset> OR use StreamingAssets folder which compatible with file system
I'll head down this path instead, thanks!
Thank you very much and I was able to move the pending changes to the corresponding branch, thanks to everyone who helped me.
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.
PlayerPrefs for player preferences and persistentDataPath for game saves
If I use persistentDataPath, should I still be using resources.load<TextAsset> for the read in?
No, you should use regular file API for it
Seems I mildly over complicated this. Will look into that tomorrow, thanks again!
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;
}
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?
So basically you want to rotate the object around its x axis?
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;
}
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)
Any way to change only the localRotation? I want to change only local rotations alone for better control.
I'm not sure what you mean, I haven't worked much with rotations sorry 😅
So I might not be the most qualified person to answer you.
Oh ok. Let me see if anyone can help.
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 ?
Setting rotation is fine but want to know why localRotation isnt working to understand better.
Oh ok, well localRotation is the rotation with respect to the rotation of the parent, not the rotation of the world, which I think in your case does not make much sense unless the vectors you use for the axis are also with respect to the parent's rotation (which they are not I guess).
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:
- firebase doesn't have unity for webgl on their website, will unity for android work fine?
- 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?
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
thank you! wait so the OpenAI front and storing the csv's will be dealt with by the server without firebase?
idk, maybe your server can send csv to another database
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
i know nothing on backend
Ok, thanks for the help!
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?
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()'
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 ?
yep
if you are going to do that why not just copy Build2 to Build1 ?
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
Does that make sense or is there an easier way to do this that I’m missing?
if you are using s3 buckets I guess you're building on AWS, correct
There's so much more than just sending data between the clients. You are going to have a pretty awful multiplayer experience if you don't implement things correctly.
Ik
You don't just simply make an MMO. The client and server almost always share code anyways. You are not going to get very far with SignalR
Dude ik what I'm doing can you stop?
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
The client and server should be one single project.
They are
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
Sorry, didn't mean to make you so angry over nothing
You can stop typing, I don't want to speak with you anymore
You didn't make me angry but you are truly wasting your own time as I will not change my mind
Great, you can stop typing now
Good me neither
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 ?
is this line 56?
float sprintMultiplier = VerticalMoveInput.GetKey(sprintKey) ? sprintMultiplier : 1f;
@carmine swan
I think it should just be Input.GetKey
the error is still the same , thanks though
How about change private string horizontalMoveInput = "Horizontal"; to float horizontal = GetAxisRaw("Horizontal");
And do the same thing to vertical
alright
It's fine I found a code that worked thanks
👍
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){}
}
KeyedCollection
Hmm actually you are making MB
Still I’d prefer some first class collection for the model
So, my way is OK? generic one?
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
🤔 then why it is a list
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)
I don’t really get it but sure? However you can’t add generic MB from inspector
Unity would require concrete type
yes, just create an empty class like below
public class ClassA:BaseClass<>{}
It is better than creating several ItemList for each Item type
Why not use inheritance? You can have ItemElement that the list would hold. And it could be inherited by different by different types providing additional or modified functionality.
I did not get your idea. inherit from ItemElement? why?
Items can be completely different
I prefer the generic approach, by the way thanks.
Well, for the same reason you might want to use generics.
Didn't you say they all have icon + text?
If they have something in common, having a base class or an interface would make more sense than generics.
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?
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)
Adding paths is as simple as adding a path texture to the terrain and modifying the alphamap for where the path should run
You mean the unity builtin terrain object?
yes
well uh im not using those
its just a mesh
because i need it to kinda be in chunks
Unity terrain can be in chucks
ye but its still like size limited right
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
less complex than trying to UV map paths to a mesh
yeah idk i thought there was a simpler way to blend those with like vertices
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
Unknown since it's closed source
Well it's definitely linear. The question I guess is that linear time split up among multiple threads or not.
thats what i mean by linear vs non linear
the amount of work done is linearly related to the number of vertices
oh you referring to time complexity
how about thread-able then 😛
i won't hold you up with this silly semantic argument
It's probably thread_able_ but who knows if they actually multithreaded it
ill report back on my bench test results
The good news is that this API exists: https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh.MeshData.html so you can likely use the job system for this task if you need to.
oh nice
though im wondering then maybe i just do it in the compute shader and pass it straight to my material shader
Not exactly code questions
Does anyone knows, what Load Cell is?
Google doesnt help
I think it is your code and not something specific to Unity. Something that register itself to: https://docs.unity3d.com/ScriptReference/Rendering.RenderPipelineManager-beginContextRendering.html
I would search if you have an asset that have Profiler.BeginSample("Load Cell") and that register to that event
Thanks, but no luck 😦
Even searching just for Load Cell doesnt help
It might be in a package
Only nature renderer comes to mind, will try to disable it
yeah it seems to be it, thanks again!
No, all have icon + one text or two, etc. also they can have different data as well
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.
Are you trying to do an MVVM ?
Also, Content Filter most have provider. It does not work by itself.
The size is determined by the minimum or preferred sizes** provided by layout element components on the Game Object.**
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-ContentSizeFitter.html
Then it only means that you either did not use it correctly or it does not fit your needs.
Anyone know where to find a Unity Project's Build Version in the Build folder? it's not in app.info
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
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.
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.
Found one interesting note on the forums that might be relevant:
https://forum.unity.com/threads/unloadsceneasync-scenemanager-doesnt-seem-to-be-asynchronous.789506/#post-5268630
Are you testing in the editor?
No, the testing was in a build.
The profiler was attached so not sure if that makes some sort of difference.
What platform was it?
Windows
Unity 2021.3.21f1 - perhaps this behavour has changed in a more recent version of Unity
I'm might take sometime at some point to look at it. I'm not at work for a couple of days so I won't be able to check.
Also, we were developing on 2021.3.21f1 and only recently upgraded to 2021.3.27f1. Both version were working correctly.
I wasn't expecting you to check anything on your end, but that is much appreciated! No rush at all. If you get to it you get to it. One other though I had was, perhaps there is a performance hit in your game, but it's just not a big deal since you are switching from one scene to the next (i.e., there is no player moving around)?
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
Well that's what I thought originally, and it's what my test reveals. But Simferoce indicated their live game didn't exhibit this behavior.
Same goes for loading scenes btw
Loading scenes have to instantiate everything on scene in single frame regardless of async API
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.
does the error also appear in the unity console? if not, then make sure you have the 2D sprites package installed, i assume you probably already do, but best to check just in case. then regenerate project files and restart visual studio
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
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. 😲
then you need to reference the assembly if you are not already
Yeah, I think that might be it. Give me a sec
That seems to have cleared the error. Thank you, thank you. 🙏 
I'm still new to using assembly definitions in my workflow, so it's not something I've made a habit of checking yet.
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;
}
});
AsyncGPUReadback doesn't work with GetData, it replaces it. You get the data from the AsyncGPUReadbackRequest req.
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
Do i need to dispose of the native array?
No, it will automatically dispose next frame.
Okay, and If I want a certain amount of data? (on the normal get data there's teh count parameter)
AsyncGPUReadback.Request has size and offset, in bytes.
Size being the length*the size of the data that i want?
!code
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.
Yes, the size in bytes, so length*stride
I posted it with the quotes
Where stride is the size in bytes of one element.
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;
}
});
You could avoid the ToArray if you already have an array created you can copy to, but that looks like it should work.
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?
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
Compared to calling GetData directly? The speed of GetData is limited by CPU/GPU synchronization. The amount of data doesn't really affect how long it takes, unless we're talking about a huge number of bytes that you run into bandwidth issues.
okay, thank you for the intel, good to know
What does the particle system wait for? I can't see the whole method name.
I actually dont know, they come with the demo scene! Let me check!
They have emission checked on
All of them
Perhaps that's causing the issue. I'd imagine that if each particle is counted as a light source in the lighting calculations it's probably crazy heavy on the GPU.🤔
Does this look like GPU hell to you?
There's definitely a lot of lights. Are they all real time lights?
I have turned all particles off completly, testing now!
"emission" is just particle spawning.
"emit light" would mean the Light module is enabled.
Oh yeah
Ah, right.
This is a particles setting
@spark spade Which Unity version are you using?
2022.3.4f1 as mentioned in the OG post
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.
Apparently, yes...
This might be the huge problem
You say you're using SRP. Do you mean the built-in render pipeline?
Yes
Isn't it waiting for the GPU?
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.
It's supposed to be fixed. Apparently it can also appear if you're accessing some data on the particle system at inopportune times.
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
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());
}
});
What would be the best course of actions right now, lads?
Turning all the lights into baked lights?
This kind of scene you'd usually bake instead of using real time lights.
You could try switching to deferred render path if you're not using it already. The forward renderer in built-in is really ancient and poorly optimized.
Or you can use the improved forward renderer in URP.
We are sticking with the standard render pipeline, because it brings the best out of this pack. How would i make that switch?
The setting should be in Edit > Project Settings > Graphics.
nvm
It can also be overridden per camera, with the Rendering Path property.
Hold the phone, i might be an idiot and have no right to be here asking for help but is this normal 😂
Yes, it's normal if you're using the built-in RP
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.
It's the GPU doing work, is this what you see when you have the GPU Usage section selected in the profiler?
No. this is cpu, lemme show gpu
This is the entire scene
If anyone needs access to the project, just ask!
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
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
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?
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
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
will boxcast give you what you need?
Yes this looks like the right track, would my out RaycastHit hit provide me with all the points in the plane the extents of the cube has hit?
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.
I think i figured out the issue with this ... I'm using pro builder and the 0,0,0 for pro builder is different then regular game objects 0,0,0
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?
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.
I am already switching to events to do some decoupling
Another rabbit hole: what if your systems weren’t centralized in a component — what if they were emergent behavior from component interactions
but I need to have a reference to the event channel scriptable object at least hahah
🧠 🧠 🧠
thats too much IQ for me
Point being that there’s so many ways to do something. Make sure you’re being pragmatic and moving forward lol.
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
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?
yeah that is good for stuff that needs to be modulaer like weapons, but idk about general things like Logger that needs to be referenced pretty much anywhere
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
I actually was asking another question 😅
But for your case might I suggest a static class that stores the references to the needed systems? That way you only find them once when you try to use them and every class has access to this ReferenceManager
yeah I have a Global class that stores references to global references
but global state bad
or so Ive read
Instantiation of Scriptable Object works well (However, you need to clear the memory yourself).
In your situation, scriptable object does not seem to be the way though:
Are modifier unique per weapon ? (Is the amount of modifier, and their value, a reasonable finite amount) ?
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
Are they limited in a reasonable amount ?
If not, Scriptable Object will add a burden to your designer team and to your games.
Weapons have limited slots for them, I think we might have something like ~15 per weapon and two weapons during players peak power level
Even more important to know if they are reasable limited.
Can you give an example of a standard modifier
I'll determine for you if they are.
- Weapon hits cause enemies to burn
- Hitboxes spawned by this weapon connect with damaging lines
- Enemies are pulled towards this weapons hitbox
And the usual +damage -attack speed stuff
Weapon hits cause enemies to burn, what are the damage value ?
Are they like tier ? Or more like actual number ?
Like rn it's set to 5, but we can spawn different burns with different stats
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
In case player progresses
We aren't sure about progression, but currently the system allows to do both
Also, is effect on the weapon or acquired during play ?
Oh, then ScriptableObject is definitly the way to go.
The alternative, is to have the data serialized on the weapon.
We tried doing so at the beginning, the problem is the system is very modular and it wasn't just allowing to do so (we have another entity that allows to control what the weapon does, e.g. shoot grenades, do sword slices etc)
It is more than enough for most use case, does not seem to be the case in your situation though.
You must ask yourself where data make more sense to resides.
Seems like SO, since we need to be able to both insert it into the weapon right away, drop it into the players inventory during play and then insert it from inventory to weapon, to another weapon and vice versa
For your question about if you should instantiate SO, the answer would be no. They should not be mutable in your case.
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
Not sure I see the issue there.
Yes, that is fine.
Then you need to be able to change modifiers inside of it
And when you do so the base SO mutates, no?
The effect itself should be mutable.
The only way an object mutate, it is if you change a variable.
inside of it.
yup
PMed you the image (share option isn't working for me for some reason)
So,
- Injector is a group of modifier
- A modifier is an effect that effect a weapon behavior/output
- A modifier can lives outside of an Injector
- A weapon is only modified by and Injector
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 ?
Yup, but to be precise, injector is not just a group of modifiers. It's weapon behaviour itself. E.g. Sniper Shot injector, Shotgun Shot injector, Katana Slice Injector etc
So you can put injector in, and the put modifiers into it
And place modifiers into different injectors inside of one weapon even
So, a weapon is hollow ?
In theory it can be (we usually have unique root injectors)
It has reload data
And animations
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
So basically I will take initial data and deep copy it to create C# class on the basis of it?
No, there is no copy.
And static things like Name and Desc can remain in definition?
Wouldn't I be mutating the SO then if i will be using Modifier\Injector definitons directly?
They are classes that are selected inside of inspector
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.
Wait, you can instantiate GO based on the SO?
The SO contains a reference to a prefab.
I see i see.
So it's fine to have empty objects that serve no purpose except hosting scripts?
Sure
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.
Well it's clean when things aren't running 😎
Then you probably are doing it.
(We need to start spawning stuff with some order instead of root dumping dozens of enemies)
Or eveything is generated.
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
All data that needs to be mutated is in the GO
All data that does not needs to be mutated and is shared is in the SO.
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
You do not understand what I mean.
Seems like I don't
Oh, we're already basically doing this, but with just prefabs into go
instead of SO into GO
Yes, SO instantiate GO.
You can even preset your slot of your injector with a Modifier
That is a GO
Yup yup, works like this rn, just with prefabs wrapping stuff instead of SO
Then, I think this is the best way.
So I wouldn't gain anything by fighting with deep clones.
And instantiating scriptable objects themselves isn't a good practice?
ScriptableObject will live longer than your weapon. You would need to manage their life cycle.
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.
I see, thanks for sticking with me
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
For mobile you can use the Google/IOS API for authentication. For Steam, the Steam API. Unless you want to separate the authentication from the platforms.
That makes sense but if they log in through say google play services on their phone, how would they log in on steam and be able to validate they are the same player?
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.
hmm that makes sense. Unfortunately, my game design plays better the more players there are online at a time, so I would want cross-play
That does check out with what i've been seeing though. Looks like I should read more into playfab
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.
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
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
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.
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
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.
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.🤷♂️
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
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?
as you generate them add them to dicts or hashsets
Right, I was thinking about that but then I either have to repopulated them OnDeserialize, or serialize the same thing multiple times.
still beats looping and type checking
Guess you're right. Just wondering if there was a nicer way
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
forgot to mention that I can't use multithreading while instantiating due to Unity API's nature
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
Pooling also, if some objects are instantiated very commonly
That way you only have to move them around when loading a new area
Nope, reducing object that needs to be spawned would decrease either gameplay features or look. Also the first thing that comes into my mind. The object is already split in two prefabs; kinda impossible splitting into another without remaking everything and turning coding into a mess that needs to handle even more prefabs 😦
It's pretty spread. 10 instantiates per frame should not be too many
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)
Not an option for many reasons
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
yes, you'll get much more accurate results running a real build with custom profiler segments inserted around the bits you care about
Partial pooling is an option
That said, I would dig down in instantiate to see what takes up time
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.
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
TIL * operator of things like float4x4 in Unity.Mathematics does component wise multiplication, thought I sucked at math.
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
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.
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.
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.
I assume these objects need to be interactible, right?
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)
Hmm
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.
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
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.
In reference to my answer, this would probably be the way to go. https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshInstanced.html
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.
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.
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.
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)
If it was, you would not be here. You would not need to instantiate multiple object each time you load a chunk.
What I'm saying is that if I use only one tree then I'm overriding it every single time I use it. I move it in a place, then in the second. It's a single prefab that it's getting moved around many times. I don't get how you from a single gameobject emulate many of them.
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.
Was the elephant in the room addressed already? The 3.5k batches 😅
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.
PC games range from 2k to 8k from my experience. But yeah, 3.5k that earlier is definitly going to creep up.
With so many similar meshes and materials, I'd expect a lot of batching/instancing going.
It is probably the shadow.
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.
should i avoid using the + operator? i want to optimize my game and i heard + is unoptimized
💥
😂
Maybe. Hard to say for sure without seeing the frame profiler. Shadow distance should probably be reduced as well.
I think that used to matter in C++, depending on your compiler and the alignment of Jupiter's moons
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.
If I remember correctly, one is assiging the value twice or something
Maybe copy
yeah, the postfix operator usually involves copying
since you gotta return the original value
However, the difference is rediculous
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
I think it still matters for something like iterators
No, it has implication on the compiler side also.
what do you mean?
We're already here lol
i++ is the one involving copy
Yeah, I though that also. People usually do i++
that is wrong. they don't produce the same machine code, and whether or not they copy the value is the same for both cases
oh no, we've gotten nerd sniped
Depends on the compiler
If you just want to increment the value, what is the most performant method ? Also, it does not matter.
but but but much cpu cycles
What have I started.
__asm__:......
what compiler produces the same machine code for both cases? that sounds very unintuitive to do so
They have same machine code if you don’t evaluate it and it’s primitive type
🫠
So ++i; vs i++; alone
You'd be surprised
for just incrementing, it doesn't matter. both will probably be turned into the same code in that case
yeah both would probs be the same.
both will probably be turned into the same code in that case
and also
what compiler produces the same machine code for both cases? that sounds very unintuitive to do so
love it.
C compilers are extremely scary
you missed the part where we they were referring to two different things
Right right right right
Edit: to be clear -- the two "different" things are actually the same thing.
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);
}
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.
Example:
// Calculate speed using magnetometer
float heading = Input.compass.trueHeading;
float speed = velocityMagnitude * Mathf.Cos(heading * Mathf.Deg2Rad);
kmPerHour = speed * 3.6f;
what's the use case?
trying to make a little fun app to play motorbike engine sounds based on speed
like
are you expecting to use this in a car?
while walking?
Also why Unity for that?
it's the program which I know most, and I can change the audio pitch very easily in it
In general phones don't really have the hardware for precise velocity measurements.
I'm trying to use it outside
Hm, how would that work?
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
I tried that already
yeah, it's not that accurate
again, phones don't really have the hardware for precise velocity measurements
it was not accurate at all in my case, probably my phone was using the cell tower signal and not real GPS
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
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
If you know~~ C#,~~ Microsoft Java, java is pretty easy to pick up
Say it with me... "public static void main args"
alright, I'll consider switching to a native android app, thanks for the quick responses!
...string array 🙂
...{system.out.println("hello world");}
in case it makes a difference, according to the docs, the accelerometer polling rate may be higher than the framerate, so for picking up precise movements you might get better results checking https://docs.unity3d.com/ScriptReference/Input-accelerationEvents.html each frame instead instead
I said several times and again I try to explain more.
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
well that sounds like a cruddy way to do it
In my opinion, the list itself doesn't need to care what kind of element it holds. You just need different list elements that have different layout depending on what you want to display.
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);
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......
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));
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));
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?
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
It depends on the mode. https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
Default behavior is to apply given force over period of time, so it is split over the amount of frames per second
which behavior would be best used for gravity simulation?
the default force mode
so whats the equation the engine does for that?
why are you inventing a bicycle though. Use existing physics system, just manage corner cases when you need to change behavior.
If you really need the equations (which I dont think you do in this case)
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
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
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?
What brackets would you need..?
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?
If you're referring to f * dt/ m, brackets dont affect anything
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.
I just tried including mass in the gravity speed and the higher the mass the slower an object fell
that doesnt seem right
Gravity is independent of mass. The acceleration is always the same for any object (not considering air friction, of course)
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
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.
further down objects are rendered in front of objects above
so this makes sense
This part, yes.
But look what I do with the button. Somehow the RectTransform "Pip Surface", formerly nested canvas, now canvas group, or nothing (bare Rect Transform), doesn't get the raycasts. (Or it's children don't)
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.
Did you attach GraphicRaycaster on subcanvas as well
Because you need that
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?
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
yes making new lists all the time is a bad idea
GetHexesInRange is something that will run extremely often
should I keep a list in the struct and .Clear() it? or just use some other data structure
I would make this function take a list in which to dump its results into
Make the method take a list.
public GetHexesInRange(int range, List<HexGridPoint> resultsList)```
and it can add things to that
then the caller can reuse a single list many times
hm... ok
Do you think the method should clear the list (and assume it's already been new()'d elsewhere?)
I would leave clearing the list to the caller
Yes, well, I'm past that point. And the CommandSurface works.
Interestingly, a 2nd copy of it doesn't work.
I'll check if I do anything funky in that script.
I don't.
Wtf.
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.
ah, yeah, i forgot about resize costs
once the list is resized it won't need to happen again. Even when you Clear it, the allocation remains the same
I could probably cheat and allocate the list with some hard coded values since I already know the resultset size
yes this is a good idea
you can create the list with preallocated capacity
(ie, range = 0 is 1, range = 1 is 7, range 2 is .. 20?)
myList = new List<HexGridPoint>(maxCapacity);```
in the grand scheme of things this is a minor optimization compared to the list reuse though
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
reallocation will only be a one time cost per list - yea
but still if you have the data available, might as well
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.
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
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
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
yeah these look like helper functions for A* or Djikstra pathfinding yes?
Unity has a built in profiler
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
🤷♂️
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
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
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.
this should be fine
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. 👍
Isn’t ((Y - (Y & 1)) / 2) just Y / 2 in int division?
Minor tho
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}
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. 🙂
by the way the Debug.Logs that are printing this are likely the most expensive part of this code
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)
is many submeshes typically a performance optimisation vs seperate meshes
or is there some limit to that
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. 😄
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
you will need to put the .dll's in a Folder called Plugins for Unity to recognise them
let me try, thanks in advance
inside or outside assets?
inside Assets
ok
Yes, exactly
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>{}
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
Unity does not support .net6
depends on your Unity version, latest is .net Standard 2.1
ok thanks
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?
you are asking for a world of pain doing stuff like this if you dont realy understand what you are doing
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
you do know that Unity does not use Microsoft .Net?
wdym?
exactly that
you talked about this
May I suggest you go and do some research into Unity before continuing along this path
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
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 😄
bit old thread but those log messages were just during testing and aren't in any of the inlined methods .. if I'm doing pathing or anything that requires several million calls i certainly won't be logging it 😛
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
layer based collisions
put the sphere collider on a child object with a different layer
i tried but if i disable collision then triggers stop working too
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
Can I use a dictionary in a scriptable object?
no, but if you dictionary has a Key = enumType and Value = gameObject, you can create 2 List and fill him
I explained what to do
different layer for the trigger
I'm looking to store a key value pair in a scriptable object ... My best bet would be two lists or nested arrays?
of course
you can't serialize disctionaries though
so make a list of a struct that has the keys and values
Thank you
I have this about serialization , but I'm not sure I'm understanding it. Can you explain it another way?
Store and reconstruct later? Like closing and reloading the app?
it's just how unity copies data around to do all kinds of things:
- store data in scenes and asset/prefab files
- copy objects with Instantiate
- show things in th einspector
Oh ok. So I wouldn't see unserializable data in the inspector , like in my above example with the dictionary
screen 1- character is ghost layer and not collision another characters. Screen 2 - detect enemies, this object a child in ghost layer character. That is not working
Would this be a worthy workaround
I've used a few serialized dictionary tools, i'd personally recommend https://github.com/ayellowpaper/SerializedDictionary
Thank you , I'll check it out
I've been looking at this solution also
yeahhh
honestly tho ive had a great time with ayellowpaper's
i have odin inspector and ended up using ayellow's implementation instead haha
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
correct it's not complicated
but you can't serialize them out of the box
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
Error sending request: Error: TrustFailure
if anyone has this error i fixed by installing ca-certificates on server dockerfile ...
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 ?
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
No, you’d use something like odin or naughty attributes and put a conditional show/hide attribute on it if you want to avoid writing customer inspectors for every tiny thing.
You should also consider not going down the inheritance route with your classes
is there an alternative way to inherit variables and methods?
I've seen that referred to elsewhere but given the naming of that Google will probably get confused if I search it
You’d make an ‘actor’ component maybe, that actor can have ability components, one of them being jump, another being hostility towards the player
so breaking things into various component scripts?
or is there a way to make one script contain many components?
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.
A gameobject is a container for MonoBehaviour components. And you can store references to arbitrary components in the fields of your class.
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
What is the best way to return a value from a Job? NativeArray<T> of size 1?
NativeReference<T> maybe?
Thanks!
I cannot find rect3d in unity, is there any functionality like Rect but in 3d space in unity?
https://docs.unity3d.com/ScriptReference/Bounds.html
maybe you are looking for this
^
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
Color32 is a 32-bit color. Graphics APIs support textures of many bit depths, including floats.
And HDR, to achieve these colors you usually pass values greater than 1.0
Is it possible to force color8 ?
Color8 would mean 1 byte for the whole color, I might be wrong but I don't think that exists 🤔
So a value between 0 and 3 for red, one for green, one for blue and one for alpha, that's not much 😅
Non hdr color is 1byte per channel
1 byte is 0-255
Yes 1 per channel so 4 in total so it's a Color32 🙂
Colour8 is shades of grey where 0 is black and 255 is white
Wait what is a channel?
I meant 8bits per channel 😅
All channels combined would be 32 bits
Red green blue alpha color channel
In unity normal color is 4 floats iirc
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
Is Color32 a different type ?
yes
but Color and Color32 are interchangable in Unity
SetPixels32
Okok
This makes my life so much easier
I am pretty new to unity and c# 😅
I have seen the docs but kinda get lost
Most of my work has been in c++ using vulkan itself not in a game engine
I'm damn sure you had to read and understand documentation to use either of those
Yess not denying that
Just been overwhelmed
Not used to have everything been managed for me
just think of C# as C++ without the buffer overflows, you'll get on just fine
UMP is a plugin right? you probably want to ask the author of UMP for support with that
Figuring out how intptr works and managed and unmanaged memory worked took me way too much time
Why couldn't c# just have a void* and allow all objects to be convertible to it 🥲
Would make marshalling data that much easier
it does! you can write void* in unsafe code
Wait a minute, I don't need UMP. I delete it and try again. XD
yes, but tbh, if you are going to write unsafe in C# you may as well just use C++
Thanks!!
Does unity support unsafe ?
I didn't get it to work
if you're using asmdefs you have to turn it on for each asmdef too i think
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
one thing you can do is increase the friction of the physics material
Do you know a good resource for learning how it works? Or did you just sorta read around? I should try to understand it better because Im in an engine where you can use C# and C++ both and interactions betweem them have been confusing to say the least
Google
+
Microsoft docs
+
Testing out stuff
Yeah that sounds about right
- 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
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
And almost every language ever will support c/c++ code in some form or another
I donno what windows does extra but should be much different from linux
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
Yeah
The engine I use auto-generates the bindings between c# and c++ which is handy but not for understanding it XD
Ahh 😂
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
I mean I guess thats fair
What part was weird?
Although this is slightly off topic
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
The whole point of C#, apart from the casting, is you dont generally need any of that stuff
just dont use pointers
👀 my home grown engine wouldnt like that
but yeah I get the idea
that's a different problem, do what Unity do, build C# wrappers around their C++ code
Anything else?
Can I ask here DOTS questions? Or it is only for usual Unity?
You can but it's more likely you'll get an answer in dots forum
Okay, thanks
If you mean atomic in the sense of thread safe, pretty sure it is not.
Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.``` from stackoverflow, so not sure if its reliable
Read and write operation could be. Also, check the reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references
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
What do you mean is an atomic ?
What are you even trying to do
And what you expect the atomicity to do.
read write to a bool from different thread
kinda like a mutex, but not exactly (I am not locking/unlocking the exec in anyways)
If you do if(bool) then it does not matter the atomicity of your type
Also, read-modify-write operation is not atomic.
if its getting assinged in another thread (ie write) it would wait for that before it reads the value in the bool right ?
So, you gotta clear out what you want to do.
ie ```c#
if (my_bool_var) {
my_bool_var = false;
....
}
maybe I should just use a mutex and call it a day
Your bool my be false in your if.
yeah its almost always false (unless written as true in a different thread)
In other words, you could have 2 thread executing the if body
no
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
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.
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
fair enough, I should probably just use a mutex which will guarantee it being correct
Using a mutex is more safe and it signals your intent as well.
Also, you would need to use the volatile keywords I think.
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
To prevent compiler from doing optimization.
(Note necessary) The mainthread can do something before waiting
It also does not mean to block the whole things.
You can do that in Update loop
Not necessary a while
the point is that
the worker thread is fetching the latest values from somewhere thats external to unity or c#
I cant make the main thread always update the contents (kinda expensive) so I make it check if there is a visible update, only then its gonna update
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
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
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....
Or you can just use UniTask.