#archived-code-advanced
1 messages · Page 87 of 1
Maybe have separate buffers for different data. One that contains data that doesn't change every frame and one that does. Then just link them with an index/id or something?
Does unity/mono suffer from tiered jitting / tiered compilation or whatever its called?
or is everything already optimized to fullest extent at compile time?
If you build il2cpp, it's definitely not an issue.🤷♂️
Okay so I have a somewhat complicated issue. I am trying to make sure my Bootstrap scene always gets loaded first. Currently I have it getting set as active if it is already in the scene. But when I am loading it into the scene through
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
The original scene will load in before it!
I have tried setting it active when I call Load scene, but that doesn't work as the scene isn't loaded.
I have tried unloading the current scenes, loading in bootstrap and then reloading the original scenes, which kinda works, but seems the SceneManager uses some kind of queue that doesn't clear when a new LoadScene as single is called if there are already scenes added to load. So that looks like.
OriginalScene -> Loads
OriginalScene -> unloads
Bootstrap -> Loads
OriginalsScene -> Loads
Which technically is okay, but will cause major performance issues.
I am setting Bootstrap as active through [InitializeOnLoad] but I can't seem to load scenes there, as when I tried to load Bootstrap addatively nothing happened. Also tried unloading OriginalScene here, and nothing happened.
Just found UnityEditor.SceneManager, so gonna play around with that
is there a "sane" way to get the size of the window decorations in unity so I can ensure that I don't make a window slightly taller than a maximized window (stuff ends up offscreen) - I have a widget ingame that changes from to/from fullscreen (fullscreen windowed), and sets a resolution in fullscreen, but when going back to "windowed" the window is now taller than the screen (because the client area is equal to the screen resolution which when added to the titlebar height etc overflows the screen)?
(I'm hoping to avoid needing to do overly platform specific stuff here since I'll then have to do that for mac etc as well)
Make it windowed maximized, like if you click the middle control on a Windows window
MaximizedWindow is documented to only do stuff on Mac OSX and on other platforms acts like fullscreen windowed modes
though, admittedly if there was a unity-way to set it maximized that would mostly solve my problem
`private bool IsVisibleInScreen(Camera c, GameObject target)
{
var planes = GeometryUtility.CalculateFrustumPlanes(c);
var point = target.transform.position;
foreach (var plane in planes)
{
if (plane.GetDistanceToPoint(point) < PlayerController.instance.cameratest)
{
return false;
}
}
return true;
}`
I'm having an issue turning this code into a job
can you guys confirm this, sometimes animations, when you drag and drop sprites in it, it doesn;t let you and some parts the window are uninteractable, it kinda seems to be bugged/broken.
The animation window is finicky, if you’re creating animations in Unity for a prefab, make sure the correct animator game object is selected in the hierarchy (the one that matches your params in the animation window). Check if you are in “record” mode too.
i've solved it thank you!!
It simply did not like having the animation in the same folder as the sprites for it.
i'm not sure it makes sense to turn this into a job. who authored CalculateFrustumPlanes? is it a unity function? it will have to take structural data, instead of a camera reference, as an input, if you want that line of code to be in a job
jobs work best when they are pure. that means that they have no side effects. that means a job is a function where all the data comes in as an argument, as copies and not references, and it returns all the data, and doesn't touch the scene.
you can touch the scene later with the thing that is calling the job
the windows title bar is 32 pixels high, and i believe unity windows are borderless. don't overthink this
this is a good start but it has a lot of API surface area that you will have to double check https://chat.openai.com/share/0cbe5804-a78d-447b-81ae-9850cad7afe9
yeah im trying to avoid taking a dependency on the windows api directly, thatvway is not sane
hmm, i suppose what difference does it make, if someone else writes that dependency for you or you do
if that's important to you use a y value of 32 pixels * screen scaling setting
Thats more or less what I ended up doing, though I couldn't find a way go get the screen scaling setting through unity
Hi all, I'm scripting the setup of the URP for my projects and I'm blocked. Hoping someone here can help!
I've done the following,
- Created a UniversalRendererData object
- Created a UniversalRenderPipelineAsset object
However, I'm unable to script adding the UniversalRendererData as the default renderer of the UniversalRenderPipelineAsset (see screenshot).
There must be a way to do this, has anyone else tried?
the source code is open. you can see what the editor sets yourself
For anyone interested in the solution / a good Bootstrap script.
https://github.com/XanNava/Levels.Unity_Bootstrap
Good point, I'll give it a go, thank you!
How can i accuretly calculate a normal map from a mesh through Jobs?
Im creating a mesh from a height map, and I would like to calculate the normals too from it, but im getting results that are not accurate (when comparing them with mesh.recalculate normals)
[NativeDisableContainerSafetyRestriction]
NativeArray<Vertex> vertices;
int Resolution;
public void Execute (int i) {
Vertex v = vertices[i];
int x = i%Resolution;
int y = i/Resolution;
var posA = position(x-1, y);
var posB = position(x+1, y);
var posC = position(x, y-1);
var posD = position(x, y+1);
var centerPos = v.position;
var normalA = cross(posC - centerPos, posA - centerPos);
var normalB = cross(posD - centerPos, posB - centerPos);
var normalC = cross(posB - centerPos, posC - centerPos);
var normalD = cross(posA - centerPos, posD - centerPos);
v.normal = normalize((normalC+normalD+normalA+normalB)/4);
vertices[i] = v;
}
public float3 position(int x, int y){
x = clamp(x,0,Resolution-1);
y = clamp(y,0,Resolution-1);
Vertex v = vertices[y*Resolution+x];
return v.position;
}
This is the code
This looks all whack to me. You're computing the normal using only vertices? Where is your index buffer? Assuming this mesh is rectangular based on your position, you might want to sketch out a 3x3 example and see what is happening on the edges
https://docs.unity3d.com/ScriptReference/GraphicsBuffer.SetData.html
Can anyone tell me what the overloaded version (specifically for native arrays) of this method implies? I just want to copy partial data from my array into this graphic buffer.
public void SetData(NativeArray<T> data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count); ```
If I want to copy indices of my native array, 5 through 10 into the buffer, then how would my implementation look like?
oh wait I get it nm im dumb, I was expecting to forloop through it all, but I guess I shouldn't be constantly setting the buffer like that
well, it probably does internally but unity maybe doing more stuff under the hood
hmm, well I guess the better question is what's the performance implications of doing something like this:
private unsafe void LateUpdate()
{
if(occupiedIndices.Count == 0)
{
return;
}
foreach(int index in occupiedIndices)
{
bufferDataPtr[index].Position = abilityDataArray[index].transform.position;
graphicsBuffer.SetData(bufferDataArray, index, index, 1);
}
//graphicsBuffer.SetData(bufferDataArray);
}
instead of copying all data every frame (since not all data is always changing)
General question, is there a simple function to static batch objects that are instantiated? I have larger objects that spawn later and they aren't being batched
no. the expectation is that you combine the meshes using some other approach. there are many mesh combine solutions in the asset store that work in runtime.
private unsafe void ExtendCapacity()
{
NativeArray<BufferData> newBufferDataArray = new(dataCapacity, Allocator.Persistent);
for (int i = 0; i < previousCapacity; i++)
{
newBufferDataArray[i] = bufferDataArray[i];
}
bufferDataArray.Dispose();
bufferDataArray = newBufferDataArray;
bufferDataPtr = (BufferData*)NativeArrayUnsafeUtility.GetUnsafePtr(bufferDataArray);
}
Question on using native arrays. Would this be the correct way to Dispose() of my array data or would I dispose after? I've seen a mixed of code samples that do both so I'm a little confused on the usage. Also, I'd assume I'd need to create a new ptr after.
Would I even consider using Allocator.Temp here if I am assigning my temp as my buffer array, or would that data actually be disposed of next frame?
I should probably make a new project to test this stuff out since a crash is technically a 15 minute relaunch of unity ;)
you want to create a third array with temp? what? you're doing this in a mega inefficient way anyways, performance in editor will be absolutely trashed if you have collection checks on. Why aren't you using memcpy? https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.Copy.html probably does the right thing, the instance methods require same length arrays
it won't matter when you dispose of the original data, as long as you do it after you access it
Ah, ok I was looking for something like that. Just trying to extend the capacity to a buffer is all and haven't actually touched native arrays before.
Is there a reason why you are not using a NativeList?
I have a main Unity project, MainGameProject, which includes a CommonCodeRepo library for shared code. I'm planning to integrate two other projects, ProjectA and ProjectB, into MainGameProject as Git submodules. My challenge is enabling ProjectA and ProjectB to access the CommonCodeRepo located within MainGameProject. How can I configure this access efficiently, ensuring that both subprojects can effectively utilize the shared code in CommonCodeRepo?
Unity doesn't have a concept of "subproject" afaik
If you're just asking how to make a reusable library in Unity, make a UPM package
I'll do it with git submodule
When you say "project" I assume you mean Unity project
Anyway if you want a shared library for multiple Unity projects you use UPM
NativeList is implicitly convertible to NativeArray.
//Edited
I want this to be private, do you have a suggestion for that?
Nothing about a Upm package needs to be public
https://docs.unity3d.com/Manual/cus-share.html for options
Easiest way. Make everything in your Common library internal and use the assembly: InternalsVisibleTo attribute
The 'Common' folder also contains some package files, like 'addressables'. How can I keep the Common in ProjectA and ProjectB constantly updated?
Now you've confused me. You said you were integrating ProjectA and ProjectB into MainGameProject so the Common Folder is Common to all
Hello,
I'm working a game which need fast and accurate physic. Is there any examples showing how to use Unity Physics without DOTS ?
But ProjectA and ProjectB are different repos, yes the common folder is common in the main project, but when I open the ProjectA repo, there is no common folder because it is a different repo.
To summarize
I have a common files
And I need to use this common folder in my two different projects and mainproject needs to have all the files.
Common
ProjectA
ProjectB
But ProjectA and ProjectB are separate repos and my goal is to develop them separately to avoid confusion.
These are VS projects or unity projects?
ProjectA and ProjectB should be standalone repos that are not projects. When modifying one of those, have the repo as a local package in a unity project and also the common. When updating those projects, they should still be independent pacakges with no files from common (only the references to it). When doing any project you will import through package manager what you need. In the case of the main project you would import COmmon,ProjectA and ProjectB
If you want to modify ProjectA, you would create a new UnityProject, import locally the package of ProjectA and download the Common package from your git through package manager
If I understood correctly, you are doing what Im doing too
If these are Unity projects we are talking about, there is a way simpler way to handle this
https://assetstore.unity.com/packages/tools/integration/asset-link-editor-263822
But that's an investment, that with some care you can avoid, (but always an option neverthless)
That is true of any asset you use, you can always do it yourself if you have the time, knowledge and skill to do it
Yeah, but in this case is just an hour work the most
My head is getting more and more confused 😐, are you talking about transferring common files to ProjectA and ProjectB using UPM through the package manager?
Hello, I'm trying to make a custom library for myself and wanted to implement few extension methods, is it possible to do
ObjA.MethodA().MethodB();
Where methodB() can only be called after MethodA()
I.e. ObjA.MethodB() should not be possible
Unity Projects
So first you grab the Common Files, and make a package that can be imported by the package manager. Then you do the same with the rellevant files of ProjectA and ProjectB. The idea being that you should be able to create a unity project, import ProjectA and Common, and projectA should work fine. To do that, you will have to add dependancies to Common from ProjectA (meaning that ProjectA cannot work without Common)
Once that's done, you can import those packages anywhere and as long as they are all there, it will work
Yes, I understand what you mean, but it seems to be difficult to output it as a package and keep it updated for ProjectA and ProjectB and even later for ProjectC.
it shouldn't if its you who is managing it. If you ever update common (meaning that you made changes and uploaded them to your git repo), you just have to go to your other projects an click on update from the package manager
All of the packages im talking about are in the form of git repos
So is there a method to make it private (a free method)?
yeah, the repos can be private and can be imported to unity too, you will just have to login the first time you import them
Here ?
yup
Hi i have a school project that is for a weeks time and i need someone to do it for me as i have not been able to do it. I will pay whoever does it a decent amount. It is not hard. Reply to this message if you are interested.
But cannot import a private repository
why not?
How can I do this without logging into my own git account?
You need to login to add private repos, it's the only way unity knows they are your packages
Why do you not want to login?
would you be interisted in this please. Hi i have a school project that is for a weeks time and i need someone to do it for me as i have not been able to do it. I will pay whoever does it a decent amount. It is not hard. Reply to this message if you are interested.
Im not interested, but If you explain what type of project you need to do ina weeks time we might be able to help
Guys can anyone tell me how to use a shader and where and how to get it
#archived-shaders but that's an extremely generic question
I think because I had logged into git before, unity didn't prompt for any login and added the package without any problem. I didn't know that it works on private repos, this is new information for me.
Thanks
Ah, no problem! glad to help :))
Hey, so in the editor, I am processing a RenderTexture with multiple compute shaders via a CommandBuffer. Then doing a GPUReadback in a async method and awaiting this readback. Then doing texture.ReadPixels(..) to get the resulting texture.
The issue is that I sometimes get an exception
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
But not sure how I could go about solving this. Any ideas?
You should use either AsyncGPUReadback or Texture2D.ReadPixels, not both.
The AsyncGPUReadbackRequest returned by the API contains a GetData method.
But that returns a NativeArray?
Ooh!
Yeah yeah, that should work you're right!
Yes. You can either copy the data to a Texture2D using LoadRawTextureData, or you can use GetRawTextureData to get a NativeArray that points directly to the texture pixel buffer and have the GPU readback write directly to it with AsyncGPUReadback.RequestIntoNativeArray.
Totally forgot about that, thank you! 😄
how do you want to control access to a git repository? if ssh keys work for you, then adding a package.json to your private github repo, and adding it to your manifest.json via an ssh url will work correctly. you can also add a git submodule pointing to a private repo, and use a file: url in manifest.json pointing to the path relative to manifest.json. you will need to not screw up and make sure to add the submodule as an ssh remote, not an https remote. does this make sense?
@pale basin you do not need to login to anything for private github repositories
or any private git repositories anywhere. you should not be using usernames and passwords to authenticate & authorize for git repositories anywhere. it's far too brittle
I have never used SSH before and I am not sure about this.
MainGameProject/
.git
Assets/
CommonCodeRepo/
.git
Assets/
ProjectA/
.git
Assets/
ProjectB/
.git
Assets/```
Actually, I want the structure to be like this, if Common and ProjectA and ProjectB are separate repositories, it seems like it can reduce complexity.
But I'm confused, I'm not sure what the best stucture is.
I am targeting to have multiple games within a single game and want them to be developed separately to prevent problems as the number of games increases and they progress.
ProjectA, ProjectB, ProjectC etc.
how are you working with git? using a GUI? which one?
also, can you answer "how do you want to control access to a git repository?"
is this something you plan to work on with other people?
Yes, different individuals should be able to work in separate repositories, pushing code and developing any project independently. However, in reality, all these projects will be part of a main project. So, when the main project is compiled, the scenes from the other projects within the main project should be accessible to players. You can think of it like Atari games that contain 9999 games in one.
i have setting like this , i use sourcetree
can you answer the other questions
I use GitHub desktop when I think I don't need Git
if you haven't created an ssh key for github, and you don't use the git cli, this is all going to be very hard
are you interested in using git?
i guess, why use git at all? you can simply zip file everything you need
and copy directories around
and share that
Yes, I use it, but not always
what you are describing is really simple to explain for people who use the cli. another advantage is you can ask ChatGPT GPT4 how do use the git command line, you can't ask it how to use the github desktop. you can ask it how to generate an ssh key and use it with github, to read the github docs for you, but you can't ask it to use sourcetree. so you have to use the command line if you want to do anything but the most basic stuff
you'll need to use the command line to merge correctly, even if you resolve conflicts in e.g. rider or vs code with their GUIs
Are you suggesting that I use SSH to set up the system I described?
i'm saying that you will need to do
git submodule add git@github.com:rucesocial/Common.git ./Common
git submodule add git@github.com:rucesocial/Project-A.git ./Project-A
git submodule add git@github.com:rucesocial/Project-B.git ./Project-B
# then add "com.rucesocial.common": "file:../../Common" to Project-A/packages/manifest.json
# then add "com.rucesocial.common": "file:../../Common" to Project-B/packages/manifest.json
but then you also need to have an ssh key, and be familiar with git submodules. committing them will be confusing. it makes more sense to do
# then add "com.rucesocial.common": "git://git@github.com:rucesocial/Common.git" to Project-A/packages/manifest.json
do you see the difference between the two?
anyway you can probably blub through this with gpt4
i wouldn't overthink it
Thank you for your attention, I will research it.
Any recommendations?
i think it is impossible since it requires you store the state somewhere, or alternatively
public Obj methodA(this Obj obj,bool callB=false){
if(callB){obj.MethodB();}
}
Sure you'd just need MethodA to return something that has MethodB on it
That doesn't sound too good, cuz I may want to add more extensions to methodA other than methodB alone , and it might get very messy very fast
oh, it is possible to store the state
private static hashset<Obj> theObjsThatCalledA;
static ClassName{}
public Obj MethodB(this Obj obj){
if(theObjsThatCalledA.Contains(obj)==false){return obj;}
theXXXX.remove(obj);
}
I mean you can just have the first function return a wrapper object containing a reference to the object you called it on. You don't need to mess with static state
Give that wrapper class/struct MethodB
And you're in business
This is how fluent interfaces work
cs
Public class ClassA
{
Public classA methodA(this Transform t)
{
return this;
}
}
Public classA methodB(this ClassA c)
{
Return c;
}
Like that? Apologies for indentation as rn I'm home on my phone 
No
I'm also on a phone gimme a sec
No worries! Not in hurry anyway ^~^
Interesting conversation re: extension methods - I was just reading the google style docs and went deep in a conversation about this with a coworker. Google advises to not use them (https://google.github.io/styleguide/csharp-style.html#extension-methods) if you have access to the original source (ie, it's your own code) as it impacts readability.
I use them myself kind of often for random convenient things but I might be coming around...
Actually since it seems like you're writing one on Transform that's fine
also @hoary prism why not just make your "method b" another extension on the first class that does all the things?
Yeah thats not a problem actually, I was just wondering how to go about doing it 
Didn't know they were called re: extension methods, thanks a bunch! I'll have a look through the docs!
that link is just style guidelines.. but extension methods are fine to make things easier.. Like one I use a lot lately (in unity) is a "make into a unity color from a hex string" thingy
It's just called an extension method, you've already written one above
Doesnt that already exist under ColorUtility?
yeah, but that's what my extension method does 😛 the syntax was just too verbose
(also i added a little bit of special code because I didn't want exceptions - I want pink text and error messages)
public static Color GetHtmlColor(this string htmlString)
{
if (!ColorUtility.TryParseHtmlString(htmlString, out Color ret))
{
w($"Couldn't parse color string: {htmlString}. Defaulting to pink.");
return new Color(1, 0, 1);
}
return ret;
}
Ah understandable
like.. I have this thing in my game called a "hit text" - basically it's floating text that appears and disappears after a moment or two.. I don't think this is the cleanest code (I don't like the use of tuples in general) but I have a start and end color and some various presets that I can.. make a little bit neater in code:
Nice 
that'd kind of be a mess of vertical code if I .. you know, didn't smash it on one line like that.. Although I'm sure someone (or many someones lol) will look at that line and 🤮
but i can consume it like this:
I'm assuming you found these colours on Google , wouldn't it be better to manually convert them first and use that instead?
colors are from webflow.com (love that site btw)
I should/could convert them to static colors so that each and every use doesn't need to parse and allocate for the objects........ buuuuuut it probably doesn't matter
In general I don't ever optimize unless whatever I'm optimizing approaches N > 100,00 or so, so for this application readability and editability are a little more important to me
By saving it somewhere and using that color instead everywhere you also get ability to re edit colors later with ease 👀
public static (Color start, Color end) Double = ("#00539CFF".GetHtmlColor(), "#EEA47F66".GetHtmlColor()); // option 1
// option 2
public static (Color start, Color end) Double
{
get
{
string startString = "#00539CFF";
string endString = "#EEA47F66";
bool didParseStart = ColorUtility.TryParseHtmlString(startString, out Color start);
if (!didParseStart)
{
w($"Couldn't parse color string: {startString}. Defaulting to pink.");
start = new Color(1, 0, 1);
}
bool didParseEnd = ColorUtility.TryParseHtmlString(endString , out Color end);
if (!didParseEnd)
{
w($"Couldn't parse color string: {endString}. Defaulting to pink.");
end = new Color(1, 0, 1);
}
return (start, end);
}
}
Nvm maybe I'm dum afterall, didn't see you were defining colors here in the first place 
Definitely 1 lol
What i actually meant was
Let's suppose code for color cyan is #00aabbff (idek)
What I meant to was
Wouldn't it be better to manually convert that hashtag first and find out color code and save it
I.e.
Public color Cyan = new Color(0,1,1);
And then use
public static (Color Start, Color end) Double = (Color.white, Cyan);
Something like that
Yeah, probably, but I use that html to color thing in lots of places, so.. y use 2 line when 1 do
if I know the color r,g,b then I can just use the color constructor, but HTML colors (which are easier for me to visually "read") are what I use more often
Just in case you might have to use "Cyan" in multiple places
yep, then that makes sense and is fine to use
^^ but this is fine anyway
I just mean whenever I have custom colors I need to place somewhere.. HTML is copy and pasteable and a bit easier to visualize? than something like Color c = new(0.34827, 0.11923, 0.93482)
i can edit a given color in the inspector to get it where I like, then copy and paste the html back to code instead of copying 3 RGB floats
Heh, that would be a nice editor extension to make: "Copy color to new Color constructor"
Then it puts it into your clipboard
Only if unity could implement it 😩
well here's how it would go. Someone writes a simple extension, puts it in the asset store (for free obv) and github/gists. Eight million people install it. Unity reproduces it in 6 years.
Don't forget the bugs that come with it
Everytime you try to copy, unity crashes
haha
Yeah or there's a blatant mistake in the code where it copies new Color(0.24, 0.83, 0.67), and you have to add the f to each number manually otherwise the compiler yells at you
Don't you mean
new Color (0.2400000000001, 0.82999999999, 0.6666666669)?
Oh yeahhh, that one is more infuriating
serves you all right for using Color rather than Color32 like any normal person
But (0,1) range feels so satisfying to my OCD riddled brain 
then, I am sorry to say, you are an idiot
a satisfied idiot

that is as maybe, but your graphics hardware and software would disagree with you, and, guess what, they are the ones who decide what appears on your monitors
try to feed this into your OCD. 0 and 255 are the minimum and maximum values allowed in an unsigned byte
How about not getting hostile about a representation of color that is totally fine and valid
I know that already lol
Thus limiting you to the standard colors, try going HDR with bytes lol
I honestly dont know what steve's point is. Materials/Shaders directly use Color
the response here is a pretty good explanation on it
https://forum.unity.com/threads/what-is-the-difference-between-color-and-color32.824196/#post-5456064
Is there any way to cancel all UnityWebRequests even if I don't have a reference, as is the case when 3rd party packages have requests in flight?
I need help with some code I have spent 3 hours creating (ik skill issue) and I dont even recognize words anymore, basically, I am creating a wow like trainer system where you walk up to a trainer and left click on them, they then give you the class they train in (mage, warrior etc.). This would be very easy if I wasnt making a multiplayer game using Photon, so basically here is the code for the trainer: '''using Photon.Pun;
using UnityEngine;
public class MageTrainerTest : MonoBehaviourPunCallbacks
{
[SerializeField] bool isMageTrain; // Indicates if this trainer can train mages
private bool hasInteracted = false; // Flag to track if interaction has occurred
private void OnMouseDown()
{
if (!hasInteracted && photonView.IsMine) // Check if interaction hasn't happened and if this is the local player's view
{
PlayerController playerController = photonView.GetComponent<PlayerController>(); // Get the PlayerController of the interacting player
if (playerController != null && playerController.isNeutral && isMageTrain)
{
playerController.photonView.RPC("BecomeMage", RpcTarget.AllBuffered); // Call an RPC to become a mage for all players
hasInteracted = true; // Set interaction flag to true locally
}
}
if (!hasInteracted && !photonView.IsMine)
{
photonView.TransferOwnership(PhotonNetwork.LocalPlayer);
PlayerController playerController = photonView.GetComponent<PlayerController>();
if (playerController != null && playerController.isNeutral && isMageTrain)
{
playerController.photonView.RPC("BecomeMage", RpcTarget.AllBuffered); // Call an RPC to become a mage for all players
hasInteracted = true; // Set interaction flag to true locally
}
}
}
}```
and here is the relevant code on the player controller script:
public void BecomeMage()
{
isMage = true;
isNeutral = false;
}```
any help would be super appreciated
#archived-networking
There's also a photon discord
does anyone recall the name of the github project that demonstrated a simple C++ native plugin stub that called back into C#, to allow authoring native plugins in C#?
i don't comprehend why unity had to make the xrinputprovider native only
unsure if this is the right place to ask but do yall have any recommendations on intermediate coding/Unity courses on Unity Learn or elsewhere?
Do you prefer to use reference (data structure) itself as a dictionary key or its field like Guid/Id?
If we use the data structure (SO) reference, we should be sure Ge/GetAll methods return that reference and not a copy of it
To me, I prefer to use an additional field to identify assets/data structures
what you prefer
Dictionary<int,Stuff> or Dictionary<Guid, Stuff> instead of Dictionary<Asset,Stuff>
Guid probably the safest if you care that much
#archived-code-general message
Going to pop this here as I'm not 100% sure which channel it belonged in
Looking to create a balancing tool here.
I have a scriptableobject containing all items in the game and their own data. I need this object to be modifiable in a development build while the game is running so testers can help balance the game. Optionally, I’d like to see that after the tester has finished balancing an item the modified data gets logged to a (text) file. How can I achieve this? Is it possible to show the inspector in a dev build?
You'd need to create your own inspector.
Hi! I have this code for drawing in gizmos (I will change that for a line renderer) a trajectory based on an angle and initial velocity. However I can't figure out how to calculate the angle and initial velocity from a point through which the trajectory should go.
private void OnDrawGizmos()
{
(float initialVelocity, float angle) = CalculateTrajectory(transform.position, target.position, Physics.gravity.y);
List<Vector2> trajectory = PlotTrajectory(transform.position, angle, initialVelocity);
Vector2 prev = transform.position;
for (int i = 1; i < trajectory.Count - 1; i++)
{
Vector2 point = trajectory[i];
if (dotted || i % 2 == 0) Gizmos.DrawLine(prev, point);
prev = point;
}
}
public Vector2 PlotTrajectoryAtTime(Vector2 start, Vector2 startVelocity, float time)
{
return start + startVelocity * time + ((Vector2)Physics.gravity) * time * time * 0.5f;
}
Pretty hard to know when we do not know what CalculateTrajectory and PlotTrajectory does.
Anyway, I have some old code that could be useful for you.
Will you STOP cross posting and !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Hello guys, I have a game that has a map generation system based on rooms, so rooms gets linked with others
The system is already working but I would love to make it perfect
Is there any way to use unity optimization tools with static objects such as lightning etc with those rooms that are not static at first but they will be static after the map generates
Would love to optimize it a lot
it already has a functional culling system working, which pretty much does the job, but getting a few fps is always good
Aren’t custom editors editor only?
!warn 859554602793697350 Don't crosspost.
gabbona10 has been warned.
ye I don't mean a unity editor. Just a mock up editor tool in your project. Basically a UI window with texts and and input fields.
You can use GUI/GUILayout methods for that, similiar to EditorGUI/EditorGUILayout in custom inspectors.
Saving a modified SO in build though... I don't think that's possible by default
But you could copy the data to clipboard and paste it back to the editor, if nothing else
Just being able to edit the data in a dev build alone for testing purposes is already a major step forward!
I have a really nice editor inside unity now with Odin Inspector. I’m hoping to be able to use that exact inspector layout in the test build
I need a bit of help.
Working on a rollback system, mostly figured stuff out.
But when a client shoots another player it will rollback the collider and then freeze at this position.
Example:
https://youtu.be/cpBOCfkNNr0
Code:
https://pastebin.com/XiNkMHvj
Upd1: Ooops, I just noticed, that I have the same for loop twice, maybe it's the problem.
Upd2: It fixed the teleportation problem, but it still doesn't rollback properly.
Possibly because of the interpolation is being calculated wrong.
Sorry I forgot to include PlotTrajectory and Calculate trajectory is empty right now.
List<Vector2> PlotTrajectory(Vector2 startPos, float angle, float initVel)
{
List<Vector2> trajectory = new() { (Vector2)transform.position };
Vector2 prev = startPos;
Vector2 startVelocity = new Vector2(initVel * Mathf.Sin(angle), initVel * Mathf.Cos(angle));
for (int i = 1; ; i++)
{
float t = timestep * i;
if (t > maxTime) break;
Vector2 pos = PlotTrajectoryAtTime(startPos, startVelocity, t);
if (Physics.Linecast(prev, pos)) break;
trajectory.Add(pos);
prev = pos;
}
return trajectory;
}
you can author native unity rendering plugins in C#.
using System.Runtime.InteropServices;
namespace Example;
public class EntryPoint
{
[UnmanagedCallersOnly(EntryPoint = NameOfUnityPluginLoad)]
public static void UnityPluginLoad(IntPtr unityInterfaces)
{
File.AppendAllText("entrypoint.log", $"Example library loaded, unityInterfaces={unityInterfaces}");
}
[UnmanagedCallersOnly(EntryPoint = NameOfUnityPluginUnload)]
public static void UnityPluginUnload(IntPtr unityInterfaces)
{
File.AppendAllText("entrypoint.log", "Example library unloaded");
}
private const string NameOfUnityPluginLoad = nameof(UnityPluginLoad);
private const string NameOfUnityPluginUnload = nameof(UnityPluginUnload);
}
when built with nativeaot as a shared library, everything works. this also lets you cross compile to other platforms
i'm not sure how to attach the debugger to this
it would be nice to have a stub, then delegate to .net domain calls in mono
I was going to build an admin tool for my next game using tech from our last game - persistent database using Cosmos in Azure, web front end with a Blazor/Razor app and a shared library of all the data models that the admin, database and unity client could share.
I realized that I was making it harder for my level designers (and myself) by trying to make a web front end for level design.
I'm going to do a unity based "admin tool" app instead, which will allow me and the designers to do more "in situ" level design. It's a tile based game, so there'll be a traditional palette, drawing tools, etc.
However, there's a lot of typed datapoints as well - level names, character dialogue, etc, and Unity doesn't seem to be great at that. Additionally, setting up those "forms" in unity is a pain.
What technology should I know about to do this? I've typically done all my work in IMGUI (and not their uh.. xml? based UI tech), so I'd prefer to stay there, but if something is clearly better that meets this need, I'm open to it.
TIA
Maybe you could look into UI Toolkit for editor tooling as it enable you to create forums pretty easily with its builder. There is also the possibility to use the code version of it. Alternatively, you could develop a set of PropertyAttribute simular to what Odin/NaughtyAttribute does.
To be clear, this "admin tool" will be a fully packaged windows app, so I won't be able to use any inspector-based data entry, although... that's an interesting idea that could be a lot faster/easier than trying to build my own forms... 🤔
UI Toolkit is the thing I was thinking of - I haven't used it before but I've heard negative things about it (perhaps unjustified)
Not sure I’m understanding, you were using a web app and now you plan on switching to a native Windows app, isn’t that just trading one UI solution to another? What advantage does it provide to your level designers?
I used a web app for our last game's admin tool. It worked well because 100% of the content needed to be online - it was an MMO of sorts, users connected to the game server and downloaded a monolithic configuration file or the delta between what they had and the latest.
For this game, though, we won't have an online presence, so the configuration can be bundled with the app.
This game is a tile/grid based game so .. trying to get the level design tool in a web form of some sort seems like it'd be difficult.
mockup I did yesterday:
A level designer would be able to click on the .. brush .. they want to use, and just paint it onto a grid.
Having that done in a web form in blazor/razor would be a technical challenge
A screenshot of the admin tool (for the last game) and how the content guys would enter things like .. a "level" (different for this game)
better for written text, less good for .. something like I posted above with the grid
I don’t do Blazor but I write web frontends with JS frameworks, that’s trivial to do.
I feel like “this looks difficult in Blazor so I’m going to switch technology” might not be a good idea.
Perhaps but.. I don't see a solution path that's not going to be an awful UI experience for the designers for a grid/tile game. It's certainly not impossible, but .. I dunno, it feels like the wrong solution - having a webapp for this. I suppose there are advantages - all the "levels" could be stored centrally so there'd be no "who's got the file" type issues, and the webapp could just as easily generate the binary file to load in the game for testing.
I just wasn't super impressed with the whole blazor/razor experience overall. It was nice that it was in the .net ecosystem so I could share a lot of code between the unity client and the webapp, but.. it came with its own set of hassles
I guess I don’t see how that’s fundamentally more difficult to implement in web frontend than in native. To me that just looks like a bunch of square sized img tags with fixed top and left position.
Hm.. Yeah, perhaps. 🤔 There's also a (tiny) cost consideration.. Our free plan on azure ran out in November. 😛 The database is a little expensive, the web app containers aren't too bad but all-in we're looking at around $100/month
not a huge deal but .. something
Well seems like you have made up your mind about it then. Mostly I just feel like learning a brand new technology hoping it would solve a generic problem better, might not be a good choice, but I suppose if you are not satisfied with the current solution it’s worth a shot.
Yeah, I'm .. 75%? sure I'm going to do this tooling in a Unity app. I think that a JS framework is probably least likely, just because I don't have a lot of experience there currently. I'm not opposed to it.. just.. pragmatically speaking, it'd be the slowest path.
Do you have any thoughts on UI Toolkit..? I'm looking over the docs for it and .. maybe it's the right tech for this.
No but I haven’t heard good things about it either, especially not when using it in runtime rather than in editor. Things might have changed since the last time I checked it out though.
(I’m not suggesting you to use JS btw in case I gave the wrong idea, I’m just saying it could just be a bunch of img tags, which presumably is doable also in Blazor)
Yeah, it would be. I'd probably make it a bit more functional and write a blazor component that could handle clicks, render different tile types, etc, but.. functionally it's doable for sure
Yeah that mock-up seems like something I could write in 10 mins in Vue, including setting up the project from scratch.
Is there a way to programmatically set the Enter Play Mode Options through code? I know we can do it in the settings menu, but I'd like to automate it.
EditorSettings.enterPlayModeOptions
Thank you!
Is there any way to use the virtual texturing system with your own requests?
So if I wanted to define either the individual texels of triangles in the scene to load or just the material of them themselves, is there a way to do this
my end goal is this: I have a pathtracer that samples random parts of offscreen meshes(and thus textures), so currently I need to have a big ass atlas that results in heavily reduced quality if theres too many textures
If theres a way I could instead get the texture directly from the material or something and then copy it over to a texture for myself, that would be amazing
not using raytracing shaders or anything
I have a question regarding RayCastCommand and Executing Raycasts and overlap in jobs.
If in a single frame several instance of a class kick off the jobs would those batch together automagically ? or to batch em we need to fill the array with raycast queries manually then kick of jobs on them ?
In my project right now I use update polling which enables both approaches
Later one reduces scheduling jobs to a single one whereas per-instance invoke which Ig will eat up time in discarding handles.
At present I lack experiece thus if anyone can guide me it would be great.
Thanks !
Hey, in voxel world games with lands and mountains and isometric camera, how does the camera look at?
I mean it looks at a point with fixed plane in specific height or hit point?
How do i get the list of tags for the project at runtime?
InternalEditorUtility.tags works only in editor and the TagManager.asset file does not include all of the default tags, only additional custom tags that are added after creating the project
Dont cross post
Sorry i realized afterwards it would be better placed here, will delete from the other channel
To answer your question, there is no built in method, you would need to capture the tags yourself in the editor and drop them into something like a ScriptableObject for use at runtime
But how do i access the default built-in tags in the first place?
Hi all,
in my ScriptableObject based customizer I use this code since a long time to create a dynamic ScriptableObject instance at runtime, store the reference from memory to AssetDatabase and use it as Reference in a given entry based on a SerializedProperty:
var newAttribute = ScriptableObject.CreateInstance(nameID) as Attribute;
newAttribute.hideFlags = HideFlags.HideInHierarchy;
/* store the new instance of the ScriptableObject to Unity AssetDatabase. This
special kind of storage is required otherwise all settings will be lost, because
this object only exist in memory yet. Storing it to AssetDatabase persist the
object under given entity as subobject.
*/
AssetDatabase.AddObjectToAsset(newAttribute, this.entity);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(newAttribute));
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
// save attibute to serialized array
var size = this.attributes.arraySize;
this.attributes.InsertArrayElementAtIndex(size);
var entry = this.attributes.GetArrayElementAtIndex(size);
entry.objectReferenceValue = newAttribute;
entry.serializedObject.ApplyModifiedProperties();
attributes.serializedObject.ApplyModifiedProperties();``` This works like a charm since serveral yerars. Tested it with UnityEditor 2021.3.33f1 several minutes ago sucessfully. Switching to 2022.3.13/14f1 results in a nullpointer Exception when calling entry.objectReferenceValue with this description: SerializedObject of SerializedProperty has been disposed.
Changed nothing. Using 2022 LTS since beginning of this year. But never created a configuration by this code since a long time ago, so I haven't run in this failure.
Has something changed I've missed or is this a bug?
you will probably need to hard code those
Hello. I wanted to create a static method that would add listeners to actions to avoid repetitive code. (with subscribing and unsubscribing to a bunch of events). But it doesn't seem to work. If I log the method name from listener (the method I want to add to the action) it work just fine and it also properly logs the action method name after subscribing. But it acts like nothing changed and listening methods are not being invoked with the event. Can this operation be done in a static method? It replaces code in following format: action += MyListinerAsMethod
public static void SetActionListener<T>(Action<T> action, Action<T> listener, bool subscribe)
{
if (subscribe)
action += listener;
else
action -= listener;
}
try add a ref before action
after each += or -= actually a new instance is created and assign back to local variable "action" and didnt affect the original variable you passed into
thanks, works like a charm now
I'm curious how you think this reduces repetitive code. is this not still going to be repeated for every subscription/unsubscription you do? 🤔 and not only that, but it will make the lines even longer
without this method the code is doubled in line size. The lines are longer, but seems like less boilerplate for me. (on the bottom is the standard method with += and -=)
both of the methods require similar code repetitions, but the first one seems more compact to me
An extension method might be better.
will try it out
"this" is passed as value... just copy the value to stack without changing the value itself, that means the extension have to return back the new object created
test code:
public static class StringExtension{
public static string Add(this string a,string b){
a+=b;
return a;
}
public static void Ten(this ref int x){
x=10;
}
}
public class HelloWorld{
public static void Main(string[] args){
string a="abc",c="x";
a.Add("def");
c=c.Add("y");
Console.WriteLine(a);//abc
Console.WriteLine(c);//xy
int abc=9;
abc.Ten();
Console.WriteLine(abc);//10
}
}
alright, but when I'm trying to use "this ref Action<T>" it says that the first parameter of a 'ref' extension method 'SetActionListener' must be a value type or a generic type constrained to struct
is there a way around this?
You can reverse the two arguments
But eh I guess it’s a bit weird to read at that point.
i don’t know why you’d need a ref keyword for “this” in an extension method
the point of an extension method is to add a method as though it was a part of the initial class declaration
you’d never need to pass “this” by reference, because you can just use a static method for that
+= is a compound assignment.
Without ref it would just assign to the parameter variable of the method and not do what you intended.
I would like to know if the problem I am experiencing has naming or something in english...
I have certain events... Action<whatever> in the game that trigger some actions, some of these trigger too many stuff at the same time creating a spike on the same frame. I can think of certain ways to come across this like... waiting for the next frame to do the actions in the listener for example... Or maybe for heavy operations dont use the observer and instead of listening query the state every x seconds....
Anyway my questions if if this 'issue' has a name
Edit: Im open to suggestions on how to solve this of course
for actions, don’t += and -= actually call methods for “add” and “remove” or something?
in which case, you could probably use that, no?
idk if that just does the same thing with extra steps
foo += bar is just a syntactic sugar for foo = foo + bar
Can you not just define: Action<Action, Action> sub = subscribe ? ((a,b) => a+=b;) : ((a,b) => a-=b;);
sub(Console.action, method);
assume that first line has proper syntax
the input delegate itself should just be a pointer, so why does a ref keyword matter?
now you have a func
void add(char*a,char*b){
//add a and b
}
```then
```cs
void add(char* a,char* const b){
char* other=malloc(strlen(a)+strlen(b)+1);
memcpy(other,a,strlen(a));
memcpy(other,b,strlen(b));
other[strlen(a)+strlen(b)]=0;
a=other;
}
```what is the output of a after you call this func?
The difference can be think of as:
class Box
{
public int Value;
}
void Foo(int value) => value++;
void Bar(ref int value) => value++;
var box = new Box();
Console.WriteLine(box.Value); // 0
Foo(box.Value);
Console.WriteLine(box.Value); // 0
Bar(ref box.Value);
Console.WriteLine(box.Value); // 1
You can also take a look at: https://sharplab.io/#v2:D4AQTABAYg9jCwAoA3ki6IgIwDpuQH0AzOCAXggAoBKcgPgmQF8BuNDd9EAFggBUApgGcALjU6MJGCMVIBqCjXqNWEpkiZA=
class Foo
{
System.Action _foo = () => {};
void Test()
{
_foo += () => {};
}
}
The Test method decompiles to:
_foo = Delegate.Combine(_foo, rhs);
So it creates a new action by combining lhs and rhs, and assign back to lhs.
just notice i add the const to decorate the char*....
But yeah I mentioned a potential solution above by swapping the arguments:
// Not allowed
(ref foo).AddOrRemove(bar, shouldAddOrRemove);
// Instead do
bar.AddToOrRemoveFrom(ref foo, shouldAddOrRemove);
It reads pretty bad though.
does the pointer itself actually change when you +=/-=?
yes, the local copy of the pointer
oh shit
so you need ref, or * and & operator
always envisioned the delegate pointing to the start of like a linked list of functions
i didn’t realize the pointer itself actually changes, but that does make sense
Fundamentally it's because foo += bar is just foo = foo + bar which is overloaded to do foo = Delegate.Combine(foo, bar), and Delegate.Combine creates a new delegate (https://learn.microsoft.com/en-us/dotnet/api/system.delegate.combine?view=netstandard-2.1).
This is also why you cannot overload += operator, you can only overload +.
didn’t know that. ty
using C# Unity Gaming Services Cloud Code Modules
How would I keep a player instance "alive" on the server?
A client can now send a request to buy an item, but if they spam click it it sends seperate requests
Is there a way to "remember" that player buying an item on the server, and then when they buy more just add it to a variable, instead of having to save it to my database directly every single click?
Hello i have these 2 scripts, and currently im only able to move the gameobject which i put into my inspector. I need to achieve a functionality where when a gameobject is clicked i can move the object clicked, and not the one in the inspector. By adding a static variable or other stuff, i just destroy the already achieved functionality. Im not good enough to add this on my own.
https://paste.mod.gg/ahrkeqofsuet/0
https://paste.mod.gg/qupcikcckvtp/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
i just realized I fucked up a lot in my code by assuming += wasn’t actually overwriting the delegate variable
now going back to fix, and I see I do want to pass in some actions by ref lol
is there a simple way to do this without just removing the event keyword? I like the safety it provides
I personally don't like using event or delegate multicasting in general.
You can specify custom add and remove "getter/setter" for your event, like you would do with a property
i don’t know what you mean by multicasting.
multicasting is what happens whenever there's more than one listener for the delegate
Essentially just += yeah, when you do foo += bar and then foo(), both the original foo and the added bar will be invoked.
Does anyone know a method of creating a standard MeshCollider from within the Job system? I've already got the mesh generating in the job struct, however I am struggling to find a performant way to create the collider. I don't have access to Unity's source.
I'm also wondering if it's possible to convert Unity.Physics.MeshCollider into UnityEngine.MeshCollider?
would this work as an example:
public Action MyAction {
private get => myAction;
private set => myAction = value;
add => myAction += value;
remove => myAction -= value;
}```
No, it does not work like that
public event Action MyEvent
{
add { /* called when '+=' is used */ }
remove { /* called when '-=' is used }
}
you can create meshes in the job system with https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh.MeshData.html
And assign to a MeshCollider's sharedMesh on the main thread
It's pretty footgun of a feature, the fact that you had those uncaught bugs caused by missing ref is a testament to its potential danger.
That's the problem, assigning to MeshCollider is really slow
I'm already building my mesh in my job struct
so then would this be right:
public event Action MyAction {
add => myAction += value;
remove => myAction -= value;
}```
That surely compiles, is it what you want though? No idea, I just arrived
I think your options are:
- Play with https://docs.unity3d.com/ScriptReference/MeshCollider-cookingOptions.html to potentially disable some things and speed it up
- Use/make a less complicated collider
- Break the collider into smaller simpler peices and create them over time
- Use Unity.Physics instead of the "normal" physics engine
i want an event where I can effectively pass it around by reference for some other block of code to request (un)subscription of some function. to/from that event delegate
Tried that,
Already doing this with LOD,
Already doing this with chunking,
This is what I'm going to try next
thanks for getting back with me, much appreciated, probably going to look into migrating to Unity.Physics
without exposing it as a naked public non-event where any random class can set to null etc
You can wrap it in a class, and override + and - operators for (un)subscribing
but if I wrap it in a class, that wouldn’t give total access to the class that manages it.
Another common source of bugs:
// Imagine this is a property of a class
var eventHandler = () => Debug.Log("An event happened");
// A piece of code (Foo) saves the handler for later use
var savedHandler = eventHandler;
// Another piece of code (Bar) subscribes to the event
eventHandler += () => Debug.Log("Bar wants to do something");
// Foo raises an event
savedHandler();
// Did you spot the bug?
// Bar's event subscription doesn't get triggered
oh wait, I might?
In my experience, it's much better to expose methods like Subscribe/Unsubscribe/Raise, than to expose the action directly.
i sometimes make tiered event delegates for specific things where timing matters. Like OnLevelLoadEarly, OnLevelLoad, OnLevelLoadLate. Then docstrings specify what is allowed to be happenning in each stage
i also very rarely store handlers for event delegates
You can still encapsulate it without exposing the action directly, and avoid the potential footgun.
Internally I do still use += because it's convenient, but never exposed externally.
i’m not sure I appreciate the difference in the use case where you only ever use +=, -=, and ?.Invoke()
if I want more, then I need to think harder
Well, it's more about correctness than convenience.
You wouldn't have this problem 😄
well, I didn’t realize += was an actual assignment. I thought it was syntactic sugar for .add
which is my mistake.
Yep, and you better make sure you won't make that mistake again in the future, or your teammates won't, etc.
i think I only have that going on in 2 places within a 5 month project.
Since I normally call actions in extremely simple ways to avoid complexity
what is the sort of wrapper pattern that you use?
i’m scared by how much you are typing
That's the problem, assigning to MeshCollider is really slow
that has not been my experience. try disabling all the cooking options, and then use a mesh you didn't generate and assign it
observe that it will all go very fast
i think you may be creating invalid or buggy meshes
are these convex meshes? do they have more than 256 tris?
I'm not sure how much that is applicable to other games, but my entire game is built upon a reactivity system.
Anything that may change is wrapped in a Ref<T>, which essentially is a more power event emitter that other systems can use to subscribe to events.
For example if a piece of UI wants to display player's HP, Watch basically works as +=:
player.Hp.Watch(hp =>
{
// Update the UI with value hp
});
Or maybe the system wants to render player's HP as red when they are below 200, Computed allows you to derive new events:
player.Hp
.Computed(hp => hp < 200)
.Computed(isDangerous => isDangerous ? Color.Red : Color.Green)
.Watch(color =>
{
// Update the UI with value color
});
A few things which I find this to be more effective over alternatives:
- Obviously, there's no gotcha with
+=. - Watchers are automatically disposed when systems go out of scope, so there won't be the classic issue of "oops I forgot to
-=now there's a hidden memory leak" - No leaky abstraction. What I mean is that traditionally
Playerclass may expose an eventOnHpChangeand another eventOnHpDangerStatusChangeso that the UI system can hook into those events. This imo is a very leaky abstraction and pretending to decouple the two systems, even though in reality thePlayerclass still has to be very much aware that "there exists a UI system that cares about the danger status event so I must make such an event." In mine, there is only onePlayer.Hp, if another system wants to derive a new event, they are free to do it themselves.
this mostly sounds like a proxy pattern
this is in one sense really easy to achieve, but in another sense, because you're using cloud modules, there's all this other noise going on that makes it seemingly hard. i have no idea if cloud modules are completely stateless, they certainly pretend to be out of necessity. it would be simpler to "throttle buffer" your clicks, using unirx, see approach https://stackoverflow.com/questions/66913467/in-rxjs-how-can-you-make-a-throttled-buffer-operator
unirx (system.reactive) already has all these affordances.
In web frontend development, this is usually called "signal based reactivity system" and you will find it in many frameworks. Modern frontend frameworks are all based on reactivity and signal based is one of the most popular ones.
You are able to declaratively ("this happens when HP changes") drive the logic of an entire complex application rather than procedurally ("subscribe to HP changes when system loads and unsubscribe when system unloads").
batch for what purpose exactly? the jobs will be distributed among the worker threads, hopefully at a time when the collision data cannot be modified - it's possible that burst locks it, i don't know
I am creating procedural terrain (grid meshes with noise on y axis), the meshes are valid, but they do have up to 8192 triangles at the most (closest), and that's why I'm needing a more efficient way to create colliders and preferably asynchronously. With the size required of this terrain, it's important that the system can handle a large amount which is why I am going to look into Unity.Physics
Yep, Rx (reactive extension) is also another popular reactivity system that can solve the same problem.
how do you figure the meshes are perfectly valid for the purposes of mesh colliders?
you should try what i am saying
and that's why I'm needing a more efficient way to create colliders and preferably asynchronously
i suppose you are already generating the terrain mesh. there is only one physics world and only one representation to it, so no matter how parallelized you may be in generating the meshes, eventually you will need to serially update the single physx datastructure
why aren't you using Unity Terrain?
@hollow veldt unity terrain colliders correspond to the physx heightfield collider. it has to be handled in a special way to do it performantly
you could generate your terrain however you want, but why are you rendering it using ordinary meshes? @hollow veldt or, you could use Unity Terrain just for the Terrain Collider
imo, people try to generate terrain all the time, and try to reinvent Unity Terrain, and it is such a long long journey
it's kind of pointless to avoid using unity terrain, it already has all the optimizations and tradeoffs you need for like, working terrain
My terrain needs a custom system to fit a design flow and aesthetic, it is also infinite
then i guess you're not going to have terrain physics
you can try using the terrain collider
with a terrain that doesn't render
I think I've got an idea...
and give the unity terrain the heightfield so that you can use physx heightfields
there is no shortcut here
although honestly, 35ms is nothing
is that what we are worried about?
it's enough to cause visual hitches
yes but how often are you generating terrain?
depends on how fast the player goes, so it can become problematic
I'm also running a beefy processor so average user will definitely notice
the player is moving fast on a terrain that needs ground accurate collisions?
I do something like this, but I try to make explicit event Actions, don’t publicly expose setters, and invoke actions depending on specific types of method calls that i expect to be reactive.
It's basically the same thing but with way less syntax overhead.
But yeah whatever works for you is fine, mine just solves the 3 problems I listed above, which I found them to be quite annoying.
i also have reactive values, which are a class with the builtin delegate, for some variables where I want calls on any sort of modification
Oh then you are basically half way there.
Ref<T>/Signal<T>/whatever you want to name it, is basically just a box that contains a value, and on changing said value it triggers all subscribers.
Once you all in with this reactive primitive and build your entire application logic around it, you get benefits like what I've mentioned. Deriving events, automatic disposal of subscribers, etc.
i use both. but I try to keep some delegates for more specific method calls, so I can split things like OnPlayerHeal, OnPlayerDamaged, and also change HP on ResetPlayerState without invoking anything.
just for example
That's reminiscent of someone else's problem in this chat a while ago, where they have an issue of "I'm loading a game save that resets my game state, but I don't want events to trigger while I was doing the loading"
Under the signal reactivity system, your player has just one thing: Ref<PlayerState> and that's it. There is no separate HP (HP is just part of PlayerState), for system that want's to listen to only HP changes, they can derive it by doing player.State.Computed(state => state.Hp).
The issue of "I don't want to trigger HP change event while I was mid way through modifying the player state" does not exist, because you wouldn't do state.Value = newState until your entire newState has been properly built.
I try to limit my use of variables with builtin delegates to variables that really need to use a public setter from many different points of contact, and listen to modifications from many points of contact
eg, changing gravity. changing all red blocks to blue blocks.
these are variables for which I don’t really need one class being in control of managing and tightly controlling specific edits
@undone coral fixed it by creating a dynamic queue, slicing it up into frames, and processing them in parallel
[BurstCompile]
struct CollisionBakeJob : IJobParallelFor
{
NativeArray<int> meshIDs;
public CollisionBakeJob(NativeArray<int> IDs)
{
meshIDs = IDs;
}
public void Execute(int index)
{
Physics.BakeMesh(meshIDs[index], true);
}
}```
nice
bump
Hello! Which part do you think isn't working?
Do you agree with me?
For persistent data structures which you want to load/save them, it is better to create a ctor for them instead of using parameterless ctor becase if we add a new field to that data structure and add it to ctor argument, we get compile error in all places
As you can see i can only move the same object with the arrows. I need an update function to change to the selected waterjelly/static variable, but i cant get that to work
is anyone here familiar with NavMeshAgent? I am trying to setup a simple patrol character, but I want to use my custom movement using character controller. Problem is I think the nav mesh agent's collider is interfering with the ground check logic I have because when I disable the agent the character is grounded
Any workarounds for this?
Probably will need to either do your own ground checking (capsule cast) or skip using the NavMeshAgent entirely and just follow the calculated path manually using your custom CC to move along it.
yeah I was thinking of writing my own agent class
Which, funny enough, is what I'm doing here for this small demo. Custom movement sampling the resulting path from the navmesh.
oh, i didn’t realize navmesh was any good for 2D
There is no built in solution for 2D 😆
LOL
But there's an online repo that extends it for 2D. Basic enough for generating a mesh based off 2D colliders anyway.
I always used A*
do you mean the main A* package?
naah I wrote my own
welp
i’m not in need of pathfinding right now tbh. just good to know 2D continues to be a second class citizen in the unity space
im working now with behavior trees, want to make counter strike like AI
So I have this sharerd system between player and AI including movement logic, plus nav mesh agent movemnt looks terrible XD
Navmesh for 2D is still on the roadmap, so maybe one day.
2D has too much roadmap. not enough doing lol
I am practicing my "Scalable" code writing 😂
one thing that required me to effectively build my own physics engine was the inability to put a dynamic RB into a reference frame
i would love to detail feature requests, but I fear they will be drowned out
if you write code like the one thing you’re making isn’t the only thing that will need it, it will be much more scaleable
what do you mean?
lets say I make a ground contact system for my player. it is smarter if I write it as a separate little general-purpose class, which can later be used by enemies/blocks/etc
i’ll even make it inherit from a simple base class with just contact info, and the derived class has player-specific logic. like if a surface allows jumping
that’s scaleable
or build in interfaces early on
aaah yes SRP single responsibility principle
that and interfaces so you can derive and make different pieces that still work together
for example, my entities/enemies spawn/despawn using a single monobehaviour called SpawnedEntityHandler. It’s on everything. When requesting despawn, SpawnedEntityHandler can search the gameobject for all IDespawnInterruptors to see if we have any monobehaviours that want to veto the despawn.
like, if an item is held by an enemy, and the enemy isn’t despawned, we want it to veto despawning the item
this is all a long winded way to say: get interfaces early, so you don’t make more work going into other classes that are a “done deal” just to add functionality you already had
it’s okay to only have one class that implements a given interface
Can anyone help with this issue? #🧰┃ui-toolkit message
I'm trying to programatically send a ClickEvent to a UI toolkit button in the context of a test. This is hyper advanced code, far beyond what gets talked about normally in this channel, so I was hoping someone who is really strong with Unity C# coding might be able to lend a helping hand. It seems simple (how hard could sending a click event to a button be) but rest assured, it is highly complex.
Thanks in advance if anyone is able to understand and offer assistance.
Not really advance in the sense that you need to have a good understanding of UIToolkit, not necessary having a good understanding of coding concept. If you have any question on particular coding concept or on how to debug/try to understand the issue feel free to ask, but I really doubt that you are going to have a better answer than what you already got previously.
I’d argue that one must have a great understanding of C# to be able to parse what may be required to get working what I’m trying to get working.
Thankfully there is a really advanced programmer in the channel who was able to reverse engineer a hack. Just saying in case there is some hyper advanced programmers here that want to check out an extremely complex problem.
If it’s any simpler than hyper advanced, I’d love to see a code sample that proves me wrong 🙂
do you know how to achieve this in UGUI?
As I said, it is not hyper advance more than knowing how to work around. If I were saying, can you fix my issue in my code, you would not be able to do so till you have read it and understand. You were really lucky that someone had somehow did the work prior to you.
Instead, I was suggesting that maybe we could suggest different method that would enable you to understand how to solve the issue. A good programmer is able to figure out how to solve the issue, what it needs to solve the issue or why the issue cannot be solve/not realistically solvable.
i see that you were helped actually. a good place to look next time is in the source! an approach is to set a breakpoint in one of your own click handlers, and inspect the stack to find the SendEvent method on a panel
In UIToolkit there is also the event debugger that can be useful (it might not be applicable in this situation though)
I honestly do not see what is so 'advanced' or 'hyper advanced' about
void OnClick(ClickEvent ce)
{
}
...
RegisterCallback<ClickEvent>(OnClick);
OnClick(new ClickEvent());
Why can't the same images in a world space canvas be batched?
Canvas
go1
image1
text1
go2
image2
text2
and what is your way to handle it? Create two canvases one for images and the other for texts?
Because that doesn’t work lol
How exactly are you accessing OnClick from the button?
I'm making a 2d metroidvania where the enemies can attach to walls and climb on all sides. Currently I'm using a* and going from top left of the grid to bottom right and checking all the empty tiles. Then out of those empty ones i check if there's at least a ground tile next to it and then mark those tiles as walkable. How can I extend this to allow for the enemy to say drop from a tile onto the player or jump from one tile to another?
Add additional edges
Let's say I have a loaded addressable scene that I told unity to unloadasync(). What happens if I tell unity to loadAsync() it again before the unload operation finishes? Is that soemthing that needs to be handled separately?
Nothing special really. You can load multiple copies of the same scene if you wish.
It's not really any different than if you loaded a different scene while unloading the first
Thanks. Just wanted to be sure.
That's what RegisterCallBack does. This is a class that extends UIElements.Button
Yes it does
and how do you access what's been registered if you only have the Button?
Not following your question
They have a UI Toolkit Button, and they want to simulate clicking it.
They do not have the function they registered to the button, they only have the button
Ah, didn't realise that
So they want to simulate the OnClick without knowing what the actual OnClick method is, correct?
Yes, and they've been answered thoroughly in #🧰┃ui-toolkit
Hello, I have a question related to Vivox,
I want to try to program in a system to reroute Vivox's audio to be played from audio sources in Unity so I can add fx, control volume, etc. Would anyone know how I'd do this, or where I can look for resources/documentation on audio stuff like this?
is this what you are looking for?
Oh thank you so much!
I need some help with my active ragdoll script, I want to make it so when the hip's rotation exceeds the max rotation for balancing, it applies forces to try and correct the hips's rotation, so far no luck
this is what the script looks like right now, it literally does nothing 💀
well for one force should never be added in Update
it should always be in FixedUpdate
for two , none of this seems to have anything to do with rotation
Seems like some basic debugging is in order.
oops
old script
that was for getting him to stand, which that is not the direction I went for that
dis the one for rotationhttps://pastebin.com/YbY6KdLk
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
its terrible dont even look at it, ima start over
Is there any best practice for Terrain under dots?
how can i use terrain tools on dots project?
Hi, are there any tools/tutorials on enclosing a square within the smallest circle possible in Unity?
a sqaure or many squares?
Sorry, a rectangle (though it can be viewed as a square given the longest side)
It would be just 1 square
or rectangle
In geometry, a set of points are said to be concyclic (or cocyclic) if they lie on a common circle. A polygon whose vertices are concyclic is called a cyclic polygon, and the circle is called its circumscribing circle or circumcircle. All concyclic points are equidistant from the center of the circle.
Three points in the plane that do not all fa...
What I am trying to do is scale a Mask with the Camera Fustrum for different screen sizes
Thanks
Hello everyone just wanted to ask is there a server where I can ask someone to help me with something and Ill pay them money for their time in Unity just asking
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I'm following sebastian lague's tutorial on A* pathfinding and I've modified the code a bit to work with a sidescroller and tilemaps. However, the code keeps making my game freeze when i run it. I've narrowed it down to one loop but I'm still not sure what's going wrong. Could someone take a look at it?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ty in advance
seems like something in this loop is causing unity to freeze upon pressing play
int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour);
if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
{
neighbour.gCost = newMovementCostToNeighbour;
neighbour.hCost = GetDistance(neighbour, targetNode);
neighbour.parent = currentNode;
if (!openSet.Contains(neighbour))
openSet.Add(neighbour);
}
there is no loop here
sorry i meant the if statement
btw is backtick, the key above the tab
its contained in a foreeach loop but when i comment this part out, it doesn't freeze
its weird cuz i swear this code was working before (project i worked on but then left, just came back to it)
if closed set contains the point then you should skip it
and idk why it was "work" before
btw
if (!neighbour.walkable || closedSet.Contains(neighbour))
{
continue;
}
Isn't that what this part does?
oh my bad
btw if the foreach is dead loop, that means openset is growing while iteration
wait the remove should be correct
the code is exactly the same as the tutorial except for changing two lines in the pathfindinggrid class
void CreateGrid() {
grid = new Node[gridSizeX,gridSizeY];
Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x/2 - Vector3.up * gridWorldSize.y/2;
for (int x = 0; x < gridSizeX; x ++) {
for (int y = 0; y < gridSizeY; y ++) {
Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up* (y * nodeDiameter + nodeRadius);
bool walkable = false;
if(!groundTileMap.HasTile(Vector3Int.FloorToInt(new Vector3(worldPoint.x - nodeRadius, worldPoint.y - nodeRadius))))
walkable = CheckNeighbours(worldPoint);
grid[x,y] = new Node(walkable,worldPoint, x,y);
}
}
}
Changed instances of Vector3.forward to Vector3.up (I'm doing sidescroller not top down)
void OnDrawGizmos() {
Gizmos.DrawWireCube(transform.position,new Vector3(gridWorldSize.x,gridWorldSize.y,0));
if (onlyDisplayPathGizmos) {
if (path != null) {
foreach (Node n in path) {
Gizmos.color = Color.black;
Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter-.1f));
}
}
}
else {
if (grid != null) {
foreach (Node n in grid) {
Gizmos.color = (n.walkable)?Color.white:Color.red;
if (path != null)
if (path.Contains(n))
Gizmos.color = Color.black;
Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter-.1f));
}
}
}
}
Vector3(gridWorldSize.x,1,gridWorldSize.y));->Vector3(gridWorldSize.x,gridWorldSize.y,0));
so that it displays the grid rectangle on xy plane
instead of xz plane
oh wait, i misread again, getneighbor should be finite elements it wont cause dead loop
Instead of checking if an object is on the unwalkable layer mask, it checks if theres a tile there and if the tile is empty then there should be at least 1 neighbour with a tile (GetNeighbour())
since im making my player able to walk on all sides of tiles
are you sure that the dead loop really caused by foreach not retrace path?
you may try to add a iteration guard in retrace first, the maximum number of iterations should be number of vertices
let me check again
it could be actually i just realized when i commented the if part out, then retrace path will never actually run
unless both the seeker and target start on the same spot
ok i commented out the retrace path part but it still freezes
in my implementation i will skip all visited node after pop the priority queue until get an unvisited one, you may have a try
To prevent same node and its neighbours enqueue again and again
ok this is super weird, it works when i have only 1 tile on the tilemap
so 8 walkable nodes
it seems to be taking pretty long to compute the grid after getting to 4 tiles on the tilemap
and it freezes when i put 10 tiles
not sure where the threshold is tho
Limit the iterations of outermost while loop , should be number of vertices if you skip visited vertices
Anyway i have to sleep now
kk ty
Or use debugger to trace
is there any way, I can switch from a scene to a panel from another scene? I have two scenes, one scene has a panel, I want to switch particularly to that panel. Please provide example codes. Thank you so much! Help is appreciated! 😊
What does "switch to a panel" mean?
This seems like a #💻┃code-beginner or #archived-code-general question if you're just asking about how to reference things across scenes btw
On scene management, there's a scene to scene, I know this already, but I would want to change from a scene to a panel, like when a button is clicked.
Okay! I'll try there!
A couple questions about Vivox,
What is the difference between VivoxCaptureSourceTap and VivoxParticipantTap?
Also, how can I silence the audio coming from the raw Vivox output so I can only hear the tapped output (from the audio source)?
hi guys i have a problem with my unity jump script
So share what you've tried in #💻┃code-beginner so people can attempt to help?
You can try again, in #💻┃code-beginner with some actual description of what's not working, any errors etc.
The less cryptic the easier it is for everyone.
Figured these out, but now I'm wonder what I need for VivoxParticipantTap to work?
Every time I get error -1050, saying the participant uri is null. Do I need the tap and participant components to be on the same game object? Do I need a script to derive from the VivoxParticipant class to be on one of the objects?
is it possible to exclude plugins/scripts from a platform when building?
tryin gto build to webgl, but discord api isn't friendly for it
like, i know #if UNITY_WEBGL is probably a thing, but how do i prevent plugins and .dlls from being built with the platform? 🤔
if there's no clean solution to this problem, i guess i could just rewrite everything to work as is when i just drag and drop it into the project after fixing it
you can specify the platforms in the inspector of the plugin
I have these gameobjects. What would be the best and easiest way to detect colissions before they happen on the jellies, and stop the movement alltogether? The jellies use simple vector 2 right/up/down/left onmousedown for movement
Before they happen? How do they happen? Are they falling down or sliding around? What's the actual mechanics here?
oh, i may misunderstood, if you want to detect the collision before they happens, then simply create a quadtree and calculate all future position of jellies in the next frame, then find out all overlap jellies foreach jelly, btw i dont think built in physics engine can do that (construct BVH or space partitioning of the next frame since the movement of next frame actually non deterministic).
i found that there is a sweeptest method but idk if it is always true when all of the colliders are moving (i believe it wont reconstruct a new tree for all future positions)
Basically pressing the arrow will move the gameobject one square in the grid
Is there a way to code an ai like chat gpt in unity?
you can code ai in any language as long as you know the math
That said the answer is the same as to "can I make Fortnite/Call of Duty/<any AAA game> in Unity": technically yes but in practise no, one person can't replicate the same thing as a company with 800 employees
if he means coding a transformer completely from scratch....uh
but he means if it is possible to use some library then it is possible, even if c# doesnt provide library for that, call external dll to process it
Need help with collision detection in my code. Trying to manually check for collisions between a main object and a collider. Set one as convex and the other as concave, then swapped them for a double-check. Issue is, sometimes it misses collisions. Any ideas?
You can see here that the pipes are generating off previous pipes and not colliding with other pipes. BUT the big box on the outside doesn't stop them from going outside it like it should. That box btw has an inside facing surface and an outside so it meets physics standards
I tested it with another mesh where its just a wall and floor (a single mesh for testing convex hull solution). It still went through
this is what happens without the convex concave trick
45 degree line from the hull
Unity 6 is working on exactly that, AI for literally every Unity field so it’s more accessible to everyone — but if you’re asking about using the ai inside of a game, you need to make API calls to it, and it’s really depends on which AI you want to use.
If you wanted to get started now, most AI’s are “good” with Unity, you’ll likely make things work, but nearly never optimized, or professional written
Best a tool, rather than a dependency
thank you, i am blind lmao.
Yes, but you better off using library such as https://unity.com/products/machine-learning-agents or https://unity.com/products/sentis or any other DLL/library.
Why are you computing the penetration ? You are not even using the direction/distance from it. Can you just use other means such as Physics.Overlap ?
Oh I never new about that function, I was using it to just check the overlap!! Thanks let me try that. I suspect I might find similar problems thought but thanks for the responce!
OH WAIT thats not a function. There is only overlapping boxes and spheres and capsules. No mesh overlap
Usually, you never want to do an overlap mesh, the cost huge for a realtime application
Its not for real time
its precalculated at the start of game
and even if I wanted to do it realtime thats fine. I know that its now slow enough to slow the game down noticably
I believe that you better find other alternative such as using bounding boxes for placement
I could do bounding boxes and just have many of them to approximate the shape. But its not ideal. Also I should explain that in my simulation I am using VERY SIMPLE meshes instead of what you see to caclulate collisions
as you can see here
each pipe has a proxy
It seem to me that you wouldnt even need to use physics to find out collision.
hows that?
If your shape are as simple as you state they are, you should be able to know when a piece would intersect with another
I mean, if they all have use the same metric, the amount of possible intersection is restricted
Well no so this project is intended for any structure the user wants to use. This could be building mesh pieces, pipes, roads, ships...etc
Usually, application that have placement like that use bounding box/connector
I have mesh colliders / anchors
i call the connectrs achors
similar thing just with the ability for people to use a mesh to approximate the shape for ease of use
ill look into the bounding box thing tho
Sure, then use bounding boxes with those and it would work in 99.9% of case I believe.
I have a question! I am trying to make a drive horror game and am having a problem with the first person camera. I have clamped the X axis so they can't do a front flip with the camera, but I can't figure out how to clamp the Y axis. Any suggestions?
Image
You could always have multiple boxes if needed.
ill definitly try rewriting the code with multiple bounding boxes thanks
it looks like your not using the rotationY anywhere?
also a question like this would be best in #💻┃code-beginner or #archived-code-general
I took it out of the Euler function bc it wasn't working
no one was responding
this is what happends when I put rotationY into Euler
Could you put it back and use
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
so that I can actually see the issue. The video wasn't clear to me?
So whats the problem? Is it that you can't look down or something?
I'm trying to have it that you can't look in a complete circle to your right and left
so its like your looking over your shoulder in a car and can only look so far
but i can't figure out how to clamp the rotation
oh and its allowing you to go further than you think it should?
yea
hmm let me take a deeper look
if u look at the video, you can only move when the Y value is 140 or -140
Oh it may be that you need to swap the x and y rotation when creating the euler. Not sure but I think that rotX should actually go in the y or z spot of the euler constructor
RATHER
I'll try it
i mean the limits swap
sorry dont actually swap the rotation because then you will move mouse left and right and it will go up and down
yeah looking at it it looks like the ylimit is clamping the x rotation technically. So you can rotate the camera 140 degrees left and right rather than 45 degrees
I still don't get how to lock the Y axis at 140 and -140 or whatever the lookYLimit is
but you are locking it with the clamp?
yes
you are doing it? Remember that locking at 140 is allowing it to go past the 90 degress limit.
So you are able to look farther back then straight up If you want to stop it from looking farther than straight up you lock at 90 degress
Anyone know how the new Participant Tap works for Vivox 16? Every time I start a game, I get error -1050 (VivoxService not initialized)
In the Voice Participant script above, I call the following functions:
async void Start()
{
if (!isLocalPlayer)
{
return;
}
await InitializeAsync();
participantTap = gameObject.AddComponent<VivoxParticipantTap>();
BindLoginActions();
BindToChannelActions();
BindToParticipantEvents();
await LoginUserAsync();
await SwitchToDesiredChannels(desiredChannels);
}
async Task InitializeAsync()
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
await VivoxService.Instance.InitializeAsync();
}
async Task LoginUserAsync()
{
// For this example, the VivoxService is initialized.
var loginOptions = new LoginOptions()
{
DisplayName = Steamworks.SteamFriends.GetPersonaName(),
EnableTTS = true,
};
await VivoxService.Instance.LoginAsync(loginOptions);
}
Should I be calling it somewhere else, or is there something I'm forgetting?
A blind guess, maybe you are trying to use it before it’s finished initializing?
In it, there are some functions called in Awake and OnEnable that I can't change that check if the service is initialized
but the only functions I have to initialize the service/login are asynchronous; there's almost no chance that it all initializes in one frame or in time for the Awake functions in the Tap component. it almost seems like an error on Unity's part unless I'm missing something vital, which I almost definitely am
It seems to me that you just have to wait for it to finish initializing before using, could do a loading scene or something.
Thing is, if I enable the component after initialization, I get another error saying participant uri (the player ID for vivox basically) is null
it's really weird, and there is barely any resources for it anywhere since it came out just about 2 months ago
That sounds like a separate issue, though I don’t know enough to help sorry.
you're all good, no worries
The error seems to suggest you don’t have the URI set up correctly though, so I’d probably check that.
It does intialize on the functions I listed above, my best guess is that the Participant Tap grabs it when it's initialized, so when that component is disabled, it can't do that
it's a weird loop of one bug causing another that I can't really fix
unless again, I'm missing something I don't know about
I doubt that, this seems like the usual “set this up globally once at the start of your game” type of thing, and I wouldn’t expect it to force developer to have everything that uses it to be available in the scene for it to work.
I'll try intializing services on game awake, haven't tried it since I'm used to just doing it when the player joins a lobby since it only needs to be intialized then
but I'll go do that real quick
I tried it but still got the same error
oh hold on
gonna try something rq
just found out that this exists
it was nowhere in the documentation
Oh sorry, I didn't see it there
Could've sworn I read through all of the Services.Vivox stuff. Then again, it was around 5 in the morning when I was reading through it all
I'm using the new Input System, anyone know how I can make Unity Buttons use something else other than Enter to count as button click?
Like, in the UI, if u navigate to a button with Arrow Keys lets say, you have to hit Enter to count as button click.
How do I add other ways to trigger the button, aside from Enter key?
should be on the event system
ye
I don't see where it implies the Enter key as default tho
Is it the "Submit" section?
I would assume so. The action asset there too I think is related to what keys you want.
Ah, I think submit is more like a global keycode for all controller types
Same with click and point since it can either mean touchscreen
I did that, and it worked, but now my player can't move
cause both UI and Player (on the left side) share "WASD" buttons in some sort of action
Player uses WASD under Movement
UI uses WASD under Navigation
Interesting, I wouldn't expect one map to consume the input of another. I've not fooled too much around with multiple maps so perhaps ask in #🖱️┃input-system
I'm looking for a way to reference specific child game object in a prefab loosely.
So for example: I reference game object X on a prefab. In runtime I can use that reference on prefab instance and identify same child game object.
Trick part is - this reference can't exist on prefab itself.
Is there any way to have such functionality?
Not entirely sure I understand what you're trying to achieve.
What do you mean by "the reference can't exist on the prefab"? Where can it exist then?
on separate asset
you could store a path to be used with Transform.Find at runtime? you could probably write some editor code to make it look like a reference if you wanted to hide it
name isn't very reliable
it's more like last resort I'd say
well it's how animator properties work for example, since there isn't really a better way out of the box... maybe you can assign them guids or something like that with a component?
the goal is to avoid modifying target prefab
but I see your point
no way to do that
without relying on something else other than name
or maybe child index, but that's not much better
since new children overrides will break it
so the child of the prefab can be different throughout runtime?
idk what your situation with the prefabs is but if you can't modify them maybe you could make a variant with a new component referencing those children?
nah, serialization of reference must be exclusively on target asset
I have problem, and really dont know where to look next
This is me calling my other namespace and it can't find public static method but can find classes in namespace
DelaySound class is part of Microlight.MicroAudio namespace
but this method can't be found
I had assembly definition before but i removed it for debugging
Its not misspelled as it can find other classes
as can be seen here, no problem creating new class from the namespace
What class does the method belong to?
...
exactly
MicroAudio
this works now...
but it worked without namespace before
I really doubt that.
not a good idea to have namespace and class names the same
Since your namespace and class have the same name, you probably had the full namespace in the usings.
Oh no i get it. I can use MicroAudio.PlaySoundEffect outside Microlight "root namespace"
i cant use simple version inside Microlight namespace
It works in game "global" namespace
Yeah and was trying to do the same inside Microlight.MicroUI namespace
no doubt you have a using statement
i have it in both
You can do it if you add the full namespace in the usings.
Compare the namespaces from both files. You'll see the difference.
I would use other class name but didnt come up with something, as i want to simplify the useage
notice how the using statement is unused?
i bet it would be used if class name was something different like MicroAudioClass
indeed
it's the way c# evaluates namespace and class names
You can do something like using ma = MicroAudio.MicroAudio;(change ma to a proper name) in the usings and using that inside the class. ma.StaticMethod.
Thanks, seems as cleaner fix for current problem.
Maybe i come up with nice way of new namespace
Has anyone here had issues before with creating a WebGL build using Unity.Services.Multiplay? I'm trying to create a build but it says it cannot find this assembly despite the fact I've imported the package and my server build (linux) builds correctly.
I can't find anything online that says multiplay namespace cannot be used in webgl builds
Idk builds are weird I tried webGL once but unity builds just aren’t the greatest my recommendation is make sure your game is saved make sure your important scenes are selected in the build settings and make sure that you are making the right build. WebGL has never been the greatest if you are running on Linux it might be better but if not try to do the basic PC build for an exe file.
works fine for windows build too. So must be something with Webgl, which is annoying
Hey there, I'm using Vivox for my game's voice chat. I want to use 2 channels. A main 3D/Positional channel and a 2D channel that is used for a walkie talkie. However the player talks into the walkie talkie channel they no longer talk into the 3D channel.
Here is my code:
This is subscribed to the VivoxService.Instance.LoggedIn event
private async void LoggedIn()
{
await VivoxService.Instance.JoinPositionalChannelAsync("Default", ChatCapability.AudioOnly, new Channel3DProperties(32, 1, 1.0f, AudioFadeModel.ExponentialByDistance));
ChannelOptions options = new ChannelOptions();
options.MakeActiveChannelUponJoining = false;
await VivoxService.Instance.JoinGroupChannelAsync("WalkieTalkie", ChatCapability.AudioOnly, options);
await VivoxService.Instance.SetChannelTransmissionModeAsync(TransmissionMode.Single, "Default");
await VivoxService.Instance.SetChannelVolumeAsync("WalkieTalkie", walkieTalkieEnabled == false ? -50 : 0);
}```
And this is my update
```csharp
private void Update()
{
if (!hasUsername && username.Value.ToString() != "")
{
gameObject.name = username.Value.ToString();
hasUsername = true;
}
if (!isInVivoxChannel) return;
VivoxService.Instance.Set3DPosition(gameObject, "Default");
if (!IsOwner) return;
if (Input.GetKeyDown(KeyCode.R))
{
walkieTalkieEnabled = !walkieTalkieEnabled;
VivoxService.Instance.SetChannelVolumeAsync("WalkieTalkie", walkieTalkieEnabled == false ? -50 : 0);
UIDebug.instance.wtStatus.text = "Walkie Talkie Status: " + (walkieTalkieEnabled == false ? "Off" : "On");
}
if (walkieTalkieEnabled)
{
if (Input.GetKey(KeyCode.E))
{
VivoxService.Instance.SetChannelTransmissionModeAsync(TransmissionMode.All);
UIDebug.instance.wtEnabled.text = "Talking Into Walkie Talkie: True";
}
else
{
VivoxService.Instance.SetChannelTransmissionModeAsync(TransmissionMode.Single, "Default");
UIDebug.instance.wtEnabled.text = "Talking Into Walkie Talkie: False";
}
}
else
{
VivoxService.Instance.SetChannelTransmissionModeAsync(TransmissionMode.Single, "Default");
UIDebug.instance.wtEnabled.text = "Talking Into Walkie Talkie: False";
}
}```
Has anyone here had issues before with creating a WebGL build using Unity.Services.Multiplay? I'm trying to create a build but it says it cannot find this assembly despite the fact I've imported the package and my server build (linux) builds correctly.
what issue specifically?
Assets\MultiplayConnection.cs(10,22): error CS0234: The type or namespace name 'Multiplay' does not exist in the namespace 'Unity.Services' (are you missing an assembly reference?)
Only for webgl and Unity services
I made a build for windows and it worked fine
My server Linux build works too
Also webgl can detect other services like matchmaker and authentication. They work fine, it’s only multiplay it can’t get
does MultiPlay have an asmdef?
i don't know what to tell you. it's probably not supported
apparently it's not compatible with webgl on the assembly
but strange that this isn't easily accessible via Unity docs? Unless I completely missed it somewhere
Its not up to me to say whether it should work on a particular platform or not, but now you know why
Hey all, trying to create broadsides style naval combat in my 2D game. Tried to find a tutorial to show me how to do this but can't find anything. User should be able to choose to fire out port or starboard sides with different keys. They can hold the fire button to "charge" their shot which affects the spread of the projectiles fired. Anybody know where I might find a tutorial on something like this? Oh, I also need a way for the player to visually see the charging to kinda aim for the "sweet spot". Rebel Galaxy style shooting but in 2D as an example.
Follow any standard tutorial and you will be able to do that at somepoint.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Im starting to think about making a global wind system, and I have a rather fundamental question for you gents and ladies. Would you ever need the wind data to be on the cpu side as well? Right now I can seem to think of a use case for that.
Perhaps if you need to move colliding objects, but I'd probably make a second wind system for that on the CPU side that mimics the GPU side to a lesser degree.
but if it's just blowing grass, leaves, and trees then it probably doesn't need to communicate with with the cpu for the most part.
How would you see that affecting animations? I'm wondering about root motion changes.
Anything which is wind powered, windmill, sail boat, I can see a need for the wind data on cpu
Good point, Also I seem to have forgotten about shuriken
Can someone help me understand if my coding is wrong or if I need to add something
Go to #💻┃code-beginner
Share your full error message
Share your full script (using a paste site)
does anyone know shader graph??
Oh, and please don't crosspost, I see you asked this in all three code channels.
One channel per question please
oki
Yoo i've been having trouble with your shader plugin for manaseed and eventually gave up on it. - colors dont change
Hi I have asked around in a c# discord about this issue and they say that its an issue where unity doesn't yet support the newer versions of c# but that i can use a polysharp? Can anyone aid me in this? 🌸
However when i asked him how to install the polysharp he said thats a unity thing he doesnt understand yet and that i have to ask unity experts
Why exactly are you trying to make a record type? I have a feeling there's some kind of misunderstanding somewhere
Because records are cleaner and shorter than using a struct or object for when you dont need extra methods
Basically: encapsulation
Ok, but Unity has only partial support for records so I wouldn't personally use them. The cleaner & shorter approach becomes quite quickly cumbersome and messy when you have to start adding polyfills and workarounds
Fair enough, so i should just stick to structs
I have run into another issue c# discord server havent been able to help me solve its essentially all about unity complaining that im trying to modify a collection during foreach however when you look at the code that isnt happening. Here is struct where this happens: https://imgbox.com/jswPBGFJ
And this is the error message: https://imgbox.com/8UGaCKZz
And this is where the Alarms struct is used: https://imgbox.com/Zx7Svd2G
Pretty sure you cannot modify a key in a foreach loop. Also, !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Its a copy of a key
show the stack trace
Im still new to unity and c# how do i do that?
its the bit at the bottom of the console when you select an error
Anyone here knows a lot about Inverse kinematics? I need help with FABRIK
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.Dictionary`2+KeyCollection+Enumerator[TKey,TValue].MoveNext () (at <a3b02d6f9b494355b946095ea1f25c54>:0)
Az+Alarm.run () (at Assets/Az.cs:55)
Bigfoot.Alarms () (at Assets/Bigfoot.cs:58)
Bigfoot.Update () (at Assets/Bigfoot.cs:65)
Alarm.run ? in Az.cs, where it is ? I see Alarms.run but it does not contains line 55
can you post the BigFoot script
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I can post the entire bigfoot script but really it just interacts with the Alarms struct with two lines:
post it
private Az.Alarms alarm;
And then inside void Update(){
Az.RunAlarms(alarm);
}
Az is a script/class that contains both the Alarms struct and the RunAlarms method
full script please
Should i upload both Az and Bigfoot?
yes
That code does not match with the stack trace you posted
Each one has a different stack trace though
Oh its two that repeata
Let me give you the two that repeats:
The stack trace you posted
Bigfoot.Update () (at Assets/Bigfoot.cs:65)
The code you posted for BigFoot. There is no line 65 in Bigfoot.Update
Yeah im looking at that craziness too
Im looking at my code right now and there is no line 65 in update
But the stack trace if i save the bigfoot file
Keeps saying line 65 in update
which would suggest that the code being run is not the code we are looking at
do you have domain reload disabled?
I dont know what that is or where to find it
It's the thing that makes the code reimport automatically when you change it. For now try to force a recompile by just restarting unity and see if the error changes
Thank you
I think your problem is that Alarms is a struct it should be a class
there is some way to get material name applied only to the face which player is standing on?
See i was told i could either use a struct or a class so what is the limmitation of a struct compared to a class?
struct is a value type class is a reference type so this
public static void RunAlarms(Alarms alarm)
is being passed by value not by reference
this isn't a code question really.
The mesh would have to have a submesh for that face only to apply a special material for it.
Another alternative is to separately UV map each face of the cube and have a material that takes different textures for different areas
Oooh
Ok
So a way to think about it is Alarms is not a value type its a structure where as Alarm is a value type because its a singular alarm
tbh I hate this unnecessary nesting of classes and structs, it makes following the code so much more difficult
Wait no
The issue is Alarm
So Alarm is not a value type its more of a an object
Ug im confused
No it is not, alarmsList is causing the problem and that is a member of Alarms not Alarm
lol I need get that name by code so it is code related, raycasthit.triangleindex is way to go I think. Thank you for your help
oh I misread the question, thought you were asking how to apply it to one side.
yeah you'd check which submesh(es) contain that triangle
that will tell you which materials are there
Alarm is also a struct so it is also a value type
So trying to be fancy just got me in trouble, leave structs and records its classes all the way down
yep, looks like it, I think you have bitten off more than you could chew
and put everything into it's own properly named file
Are you against my Az for Asriela script 😂
it just makes debugging so much easier because the stack trace tells you exactly the route the code followed
yes, very much so
Dont worry its for my own personal use only , its just functionality im recreating in unity that existed in game maker studio
well, it is until you come here looking for help and confuse the fuck out of most people who could help you
So what should I call it GameMakerStudioFunctions?
remember KISS
Call it what you like but you have
An Interface
A Monobehaviour Class
Containing a nested struct
Containing another nested struct
All in one code file
Not a good idea
The concept basically is that you have a single class with a bunch of functions that you take with you from game to game so you dont have to rebuild all the basic functionality over and over again each time
Like a quick start for game development
no problem, test it all as seperate elements and then join them all together when they are working
this is code, nothing is carved in tablets of stone
I see so you are saying when i am adding new functionality to my "Az" class i should first put it in a seperate class until it works then add it to the Az
yes, great plan
You were correct when i restarted unity the issue was resolved
Thank you
you might want to think about building your AZ code into a dll and using that in a Plugins folder. That way you can keep the split code files and have a single point of entry for the code
That is one hundred percent the goal i still need to learn about how dlls work but yeah
easy peasy, DM me if you need help
Anyone know how the new Participant Tap
Oh wow thanks!
You need to update the Roslyn to the latest version which is the requirement for the sourcegen to work in PolySharp. Unity's roslyn is quite outdated
And yes, PolySharp is working just fine in Unity
just becareful that not all c# 11 features are supported in Unity with PolySharp
you can update the Roslyn with this tool https://github.com/DaZombieKiller/UnityRoslynUpdater
A tool to update the Roslyn compiler and C# language versions for a Unity installation. - GitHub - DaZombieKiller/UnityRoslynUpdater: A tool to update the Roslyn compiler and C# language versions f...
Thanks alot, I didn't see that channel. I will delete my Message and move it
hey guys im building a game with firebase and it keeps loading the same random entry from weeks ago even though i deleted everything from the database atleast 100 times now anyone know why it keeps happening?
important to mention that even after playing through the session with the same old entry the next time itll load it itll be with the updated numbers
there isn't enough context here to understand or diagnose what's going on
I get from the database the data once when the game loads, abd save it when closed.
Lets say I delete everything from the database it always loads the same save.
Say it loads it with 5 coins and gain 1 in game the next time ill delete everything itll load with 6 coins.
So it doesnt just load something that doesnt exist (cause I deleted everything from the database through the firebase console) it also somehow remembers it?? Idk whats going on here
i think ther'es a lot of stuff going on that you are looking at, and you have to read carefully what is on screen when you are "delet[ing] everything from the database"
there's also a lot going on in firebase that might make it too complex for you to use
Cache, it's probably data being cached in the endpoint you're using
for example, if you enabled offline persistence, your game will update firestore / realtime database with whatever it thinks is the latest data
the firebase console cannot delete data that is offline, which then gets synced later
@dawn zephyr does your code use SetPersistenceEnabled ?
I dont think it does
maybe you should post a snippet of what you are doing on the client
to set up your firestore or realtime database, and how you save the player data
your game is setting the amount to N despite deleting, so there's no confusion here about what is going on
it is doing exactly what you are asking it to do
it loads firebase and everything from one class
private async UniTaskVoid LoadFirebaseAndGame() { Application.targetFrameRate = 120; await FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(async task => { if (task.Exception == null) { FirebaseDatabase.DefaultInstance.SetPersistenceEnabled(false); await _databaseManager.GetInitialData(); ScenesLoader.Instance.LoadGame(); Destroy(gameObject); } else { _canvas.gameObject.SetActive(true); } }); }
then i have one class that gets everything from the database into one datasnapshot
public class DatabaseManager : MonoBehaviour, IDatabase { private DatabaseReference _databaseReference; private DataSnapshot _dataSnapshot; private void Awake() => _databaseReference = FirebaseDatabase.DefaultInstance.RootReference.Child(SystemInfo.deviceUniqueIdentifier); public async UniTask GetInitialData() => _dataSnapshot = await _databaseReference.GetValueAsync(); public object GetValueFromDatabase(string path) => _dataSnapshot.Child(path)?.GetValue(true); public void SetValueToDatabase(string path, object value) => _databaseReference.Child(path).SetValueAsync(value);
thats basically all i have thats related to firebase
it loads firebase and everything from
If all you want is just record classes (not record structs), you do not need to set up PolySharp or any complicated stuff.
All you need is to copy the 3 lines of IsExternalInit polyfill to your project and that’s it, you can start using record classes without further setup.
Oh sweet
Ug I have been trying to just find out how to make a functuon that finds the nearest object and people have given so many different solutions allot of which i dont understand and now my one friend when i asked him suggested a k-d tree and im just like 😭
Wtf is a k-d tree and why does it look like this wildness: https://en.wikipedia.org/wiki/K-d_tree
In computer science, a k-d tree (short for k-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. K-dimensional is that which concerns exactly k orthogonal axes or a space of any number of dimensions. k-d trees are a useful data structure for several applications, such as:
Searches involving a...
How many objects? Do the objects move/spawn/despawn? Is the search area confined? Are objects sparsely or densely populated in the area?
Whats that for
I know what it is
But what did u bring it up for
That ChatGPT solution:
FindObjectsOfTypeand LINQ are both performance traps.- The
Selectuses an anonymous object instead of value tuple which is unnecessary allocation. - The solution is also O(n).
As always, a terrible answer not worth using.
Gpt strikes again
Like my friend Andre always says chatGPT doesnt know shit about programming
The questions I asked here probes some requirements that can help determine what approach to go for.
I suppose I did miss one aspect though: are you doing this frequently (like every frame) or infrequently.
I built an entire alarm system just to offset the frequency of the nearest object function lol
And also for all future alarm usage id need
But also i dont need anything fancy right now
I dont make games with thousands of enemies, i make games with few characters that do very complex thinking
So all in all in the future id probably use the k-d tree not to have npcs navigate but rather to manage their thinking
Im short i dont make fighting games
Where u have a ton of enemies
The amount of objects will be the biggest determining factor.
For small numbers, O(n) is absolutely fine and saves you all the trouble of using a more advanced data structure.
guys any idea why compute shader behaves weird in editor but works in playmode?
Im sayimg like 20 characters but then when it comes to objects they interact with that is determined via weighing needs not really competing about which object is closest so much
What is O(n) i keep seeing these things im assuming it refers to complexity/memory usage?
I mean finding the closest objects inherently depends on "how many possible objects do I need to check"
Yeah and in the kind of games i make ur looking at a max of 20
Objects to check for who is closest at any given time
Big O notation is for complexity yes, usually time complexity because that's what people care more about, but also used for space complexity.
20 is absolutely tiny number, you should just keep a list of all those objects and check them one by one.
Thanks let me add that to my study list
actually i think it gives a great answer that is going to work very well for you
Literally what ive been trying to do in game maker studio it would be simple but ofcourse in unity now im having to make an abstract class to even assemble that list
i kind of figured it would be "20" objects, use what was shown in there. it was to save the tedium of writing a ton of C# code to express a bunch of ideas, like bounds and nearest points and such
For reference, I recently had to do an overlap test of 1D ranges, for ~4000 ranges the naive O(n) solution takes ~0.2 ms.
Compare that to your 20 objects, it's tiny in comparison.
you can create an empty component, add it to objects you would like to deal with, then modify findobjectsbytype in the snippet i shared with you
(In my game though the amount of objects could go up to tens of thousands, and I switched to using a grid, which drops the ~4000 objects test case down to ~0.015 ms)
But again, 20 objects is nothing, just check them one by one.
Im well aware of the game called they are billions
anyway the solution is pretty much flawless
@undone coral It's not flawless even if you ignore point 1 or 3, point 2 is a low hanging fruit you can improve on.
i think you should start with it, and make changes to the core logic as you need it. or, you can continue that conversation, my goal was to jot down some of the key ideas, like OrderBy
yes, point 1 and 3 will not be an issue for @tepid jay
but wasting time will be
My whole point is i dont even want to be having any of these convos cause im not doing anything worth discussing but im still new to how to access objects and their parts in unity
It will not, but only because the answer got lucky: before the conversation continued, no one knew it was 20 objects not 10,000 objects.
well that's what i showed you
it's findobjectsbytype
and sorting can be done with OrderBy
i think you should read the text that i linked. it's a good tool as you're learning the api
if you ahve a quesitona bout accessing objects it will tell you a correct answer...
In gamemaker you can just go target=instance_nearest(tree) target.health-=6; in unity its not that simple
That's the problem of ChatGPT, it only knows how to answer but not how to ask. That solution would be horrible if we needed to deal with 10,000 objects, and ChatGPT doesn't know to ask you about requirements first and just assume "yep an O(n) solution is fine to spit out" and it got lucky this time.
you can ask chatgpt to convert gamemaker code into c# code for you, if only to see some of the concepts...
(And even the answer isn't that good)
i am trying to show you how to fish here
and perhaps have a less frustrating experience
none of what the other user is talking about is going to matter
I think i learn best when i can ask what does this part i am looking for look like as oppose to here is a solution
okay well, think about paying the $20 for GPT4 because these were the opposite of #archived-code-advanced questions
it is going to make your journey so much smoother
https://chat.openai.com/share/1f78108e-a2c2-42e9-b726-d1dfb3e1e1bb this was also pretty fruitful
Yeah sorry this conversation wasnt meant to continue in this channel
take a look at what i linked, which uses beginner coding ideas instead of LINQ
and it should be exactly what you need. if you want to ask it more questions,by all means, it will very competently (flawlessly) answer beginner coding questions in the context of unity. don't be stubborn about this. just use it.
https://i.imgur.com/EWtOKEQ.png
https://i.imgur.com/Z38i9oH.png
Then you get one of those 50/50 replies where you get to choose if you're correct or not
I understand all of that the issue was always just making it modular so how to access different objects with differently named scripts
Oh cool
Thanks for these
i think you can try to have a conversation with it and say that and you will have a lot of success 🙂
I think my frustration comes from wanting to get back to the speed of development i was used to with a game engine i knew quite well. I understand there is a transition process. I am just trying to force myself through it as quickly as possible,because this all feels like things i should already know and understand
I don't know how GameMaker's instance_nearest works, but I highly doubt that's a perfect solution for every scenario, because fundamentally collision detection is a complicated problem with many researches put into it.
So likely the instance_nearest is just a "good enough for most people" solution that you were using without thinking too much, and now you are confronted with the true nature of the problem.
For further reading, here's a good series: https://0fps.net/2015/01/18/collision-detection-part-2/
Its actually much more readable than how allot of people post solutions online.
Obviously it's irrelevant since you are dealing with 20 objects and you don't need any of the advanced solutions in there, but that is good reading material if you want to learn more in depth into the problem.
It is definitely good at explaining things clearly, and writing well.
Unfortunately it is mostly spam and rarely correct. Certainly never flawless...
And it robs you the chance to learn properly most of the time
one nice thing is you'll be able to regularly ask it how to achieve something in unity that you are familiar with achieving in game maker. however, if you want good answers, you'll need to pay for GPT4 (i.e. chatgpt plus)
what does it do?
Thank you I am having a blast here with chatGPT, this is definitely going to speed up my learning process with basics.
Idk what the problem is
I'm sure there's more involved in generating and rendering that mesh than just a compute shader...
It is the compute shader