#archived-code-advanced

1 messages · Page 87 of 1

regal lava
#

It's either this or cache hundreds of particle systems

untold moth
#

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?

plush hare
#

Does unity/mono suffer from tiered jitting / tiered compilation or whatever its called?

#

or is everything already optimized to fullest extent at compile time?

untold moth
#

If you build il2cpp, it's definitely not an issue.🤷‍♂️

velvet rock
#

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.

velvet rock
#

Just found UnityEditor.SceneManager, so gonna play around with that

lost stag
#

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)

olive cipher
lost stag
#

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

robust gyro
#

`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

humble gale
#

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.

native jasper
humble gale
undone coral
#

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

undone coral
undone coral
lost stag
#

yeah im trying to avoid taking a dependency on the windows api directly, thatvway is not sane

undone coral
#

if that's important to you use a y value of 32 pixels * screen scaling setting

lost stag
#

Thats more or less what I ended up doing, though I couldn't find a way go get the screen scaling setting through unity

bleak island
#

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,

  1. Created a UniversalRendererData object
  2. 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?

undone coral
velvet rock
bleak island
tired fog
#

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

long ivy
regal lava
#
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)

robust gyro
#

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

undone coral
regal lava
#
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 ;)

long ivy
#

it won't matter when you dispose of the original data, as long as you do it after you access it

regal lava
#

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.

scenic forge
#

Is there a reason why you are not using a NativeList?

regal lava
#

Accepts a list, array, or native array

pale basin
#

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?

sly grove
#

If you're just asking how to make a reusable library in Unity, make a UPM package

pale basin
#

I'll do it with git submodule

sly grove
#

When you say "project" I assume you mean Unity project

#

Anyway if you want a shared library for multiple Unity projects you use UPM

scenic forge
pale basin
sly grove
upbeat path
pale basin
upbeat path
turbid salmon
#

Hello,
I'm working a game which need fast and accurate physic. Is there any examples showing how to use Unity Physics without DOTS ?

pale basin
#

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.

upbeat path
#

These are VS projects or unity projects?

tired fog
#

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

upbeat path
tired fog
upbeat path
tired fog
#

Yeah, but in this case is just an hour work the most

pale basin
hoary prism
#

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

pale basin
tired fog
# pale basin My head is getting more and more confused 😐, are you talking about transferring...

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

pale basin
tired fog
#

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

pale basin
#

So is there a method to make it private (a free method)?

tired fog
#

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

pale basin
#

Here ?

tired fog
#

yup

autumn mountain
#

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.

pale basin
tired fog
#

why not?

pale basin
#

How can I do this without logging into my own git account?

tired fog
#

You need to login to add private repos, it's the only way unity knows they are your packages

tired fog
autumn mountain
# tired fog why not?

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.

tired fog
untold thunder
#

Guys can anyone tell me how to use a shader and where and how to get it

tired fog
pale basin
# tired fog Why do you not want to login?

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

tired fog
#

Ah, no problem! glad to help :))

urban warren
#

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?

sage radish
#

The AsyncGPUReadbackRequest returned by the API contains a GetData method.

urban warren
#

Ooh!

#

Yeah yeah, that should work you're right!

sage radish
# urban warren But that returns a `NativeArray`?

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.

urban warren
undone coral
# pale basin I want this to be private, do you have a suggestion for that?

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

pale basin
#
    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.

undone coral
#

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?

pale basin
# undone coral 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.

ancient karma
undone coral
pale basin
undone coral
#

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

pale basin
undone coral
#

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

pale basin
undone coral
# pale basin 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?

undone coral
#

i wouldn't overthink it

pale basin
tiny pewter
#

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();}
}
sly grove
hoary prism
tiny pewter
#

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);
}
sly grove
#

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

hoary prism
sly grove
#

I'm also on a phone gimme a sec

hoary prism
misty glade
#

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?

hoary prism
hoary prism
misty glade
#

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

tall ferry
tall ferry
misty glade
#

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;
        }
tall ferry
#

Ah understandable

misty glade
#

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:

misty glade
#

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:

hoary prism
# misty glade

I'm assuming you found these colours on Google , wouldn't it be better to manually convert them first and use that instead?

misty glade
#

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

hoary prism
misty glade
#
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);
  }
}
hoary prism
misty glade
#

which do you prefer - 1 or 2 🙂

#

basically they do the same

hoary prism
#

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

misty glade
#

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

hoary prism
misty glade
#

yep, then that makes sense and is fine to use

hoary prism
#

^^ but this is fine anyway

misty glade
#

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

fresh salmon
#

Heh, that would be a nice editor extension to make: "Copy color to new Color constructor"

#

Then it puts it into your clipboard

misty glade
#

that'd be easy enough.. hm...

#

maybe I can procrastinate for a bit and do it

hoary prism
misty glade
#

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.

hoary prism
#

Everytime you try to copy, unity crashes

misty glade
#

haha

fresh salmon
#

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

hoary prism
fresh salmon
#

Oh yeahhh, that one is more infuriating

upbeat path
#

serves you all right for using Color rather than Color32 like any normal person

hoary prism
upbeat path
hoary prism
upbeat path
#

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

upbeat path
austere jewel
#

How about not getting hostile about a representation of color that is totally fine and valid

fresh salmon
#

Thus limiting you to the standard colors, try going HDR with bytes lol

tall ferry
thorn patio
#

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?

ember summit
#

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

regal lava
undone coral
#

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

spring holly
#

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?

timber flame
#

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

spring holly
#

what you prefer

timber flame
#

Dictionary<int,Stuff> or Dictionary<Guid, Stuff> instead of Dictionary<Asset,Stuff>

regal lava
#

Guid probably the safest if you care that much

hoary merlin
light falcon
#

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?

fickle mango
sand depot
#

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;
    }
dusty wigeon
dusty wigeon
upbeat path
#

Will you STOP cross posting and !collab

thorn flintBOT
final cipher
#

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

light falcon
hushed fable
#

!warn 859554602793697350 Don't crosspost.

thorn flintBOT
#

dynoSuccess gabbona10 has been warned.

fickle mango
#

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.

lament salmon
#

But you could copy the data to clipboard and paste it back to the editor, if nothing else

light falcon
#

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

haughty skiff
#

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.

sand depot
# dusty wigeon Pretty hard to know when we do not know what CalculateTrajectory and PlotTraject...

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;
    }
undone coral
#

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

misty glade
#

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

dusty wigeon
misty glade
#

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)

scenic forge
#

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?

misty glade
#

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

scenic forge
#

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.

misty glade
#

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

scenic forge
#

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.

misty glade
#

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

scenic forge
#

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.

misty glade
#

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.

scenic forge
#

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)

misty glade
#

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

scenic forge
#

Yeah that mock-up seems like something I could write in 10 mins in Vue, including setting up the project from scratch.

grizzled lake
#

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.

austere jewel
grizzled lake
honest hull
#

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

obtuse arch
#

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 !

timber flame
#

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?

flat nexus
#

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

flat nexus
#

Sorry i realized afterwards it would be better placed here, will delete from the other channel

upbeat path
flat nexus
hot oak
#

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?
upbeat path
zealous summit
#

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;
    }
tiny pewter
#

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

zealous summit
#

thanks, works like a charm now

thin mesa
#

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

zealous summit
#

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

scenic forge
#

An extension method might be better.

zealous summit
#

will try it out

tiny pewter
#

"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
    }
}
zealous summit
#

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?

tiny pewter
zealous summit
#

too bad, it would be a perfect solution

#

but thanks for you help anyway

scenic forge
#

You can reverse the two arguments

#

But eh I guess it’s a bit weird to read at that point.

cerulean wasp
#

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

scenic forge
#

+= is a compound assignment.

#

Without ref it would just assign to the parameter variable of the method and not do what you intended.

stuck onyx
#

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

cerulean wasp
#

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

scenic forge
#

foo += bar is just a syntactic sugar for foo = foo + bar

cerulean wasp
#

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?

tiny pewter
#

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?
scenic forge
#

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
#

So it creates a new action by combining lhs and rhs, and assign back to lhs.

tiny pewter
#

just notice i add the const to decorate the char*....

scenic forge
#

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.

cerulean wasp
#

does the pointer itself actually change when you +=/-=?

tiny pewter
#

yes, the local copy of the pointer

cerulean wasp
#

oh shit

tiny pewter
#

so you need ref, or * and & operator

cerulean wasp
#

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

scenic forge
#

This is also why you cannot overload += operator, you can only overload +.

cerulean wasp
#

didn’t know that. ty

autumn basalt
#

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?

sage kettle
#

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

cerulean wasp
#

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

scenic forge
#

I personally don't like using event or delegate multicasting in general.

fresh salmon
#

You can specify custom add and remove "getter/setter" for your event, like you would do with a property

cerulean wasp
#

i don’t know what you mean by multicasting.

sly grove
#

multicasting is what happens whenever there's more than one listener for the delegate

scenic forge
#

Essentially just += yeah, when you do foo += bar and then foo(), both the original foo and the added bar will be invoked.

cerulean wasp
#

isn’t that just normal?

#

that’s like the whole point of an event delegate

hollow veldt
#

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?

cerulean wasp
fresh salmon
#

No, it does not work like that

#
public event Action MyEvent
{
    add { /* called when '+=' is used */ }
    remove { /* called when '-=' is used }
}
sly grove
scenic forge
hollow veldt
cerulean wasp
fresh salmon
#

That surely compiles, is it what you want though? No idea, I just arrived

sly grove
cerulean wasp
#

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

hollow veldt
cerulean wasp
#

without exposing it as a naked public non-event where any random class can set to null etc

fresh salmon
#

You can wrap it in a class, and override + and - operators for (un)subscribing

cerulean wasp
#

but if I wrap it in a class, that wouldn’t give total access to the class that manages it.

scenic forge
#

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
cerulean wasp
#

oh wait, I might?

scenic forge
#

In my experience, it's much better to expose methods like Subscribe/Unsubscribe/Raise, than to expose the action directly.

cerulean wasp
#

i also very rarely store handlers for event delegates

scenic forge
#

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.

cerulean wasp
#

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

scenic forge
scenic forge
cerulean wasp
#

well, I didn’t realize += was an actual assignment. I thought it was syntactic sugar for .add

#

which is my mistake.

scenic forge
#

Yep, and you better make sure you won't make that mistake again in the future, or your teammates won't, etc.

cerulean wasp
#

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

undone coral
#

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?

scenic forge
# cerulean wasp what is the sort of wrapper pattern that you use?

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 Player class may expose an event OnHpChange and another event OnHpDangerStatusChange so 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 the Player class 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 one Player.Hp, if another system wants to derive a new event, they are free to do it themselves.
cerulean wasp
#

this mostly sounds like a proxy pattern

undone coral
# autumn basalt using C# Unity Gaming Services Cloud Code Modules How would I keep a player inst...

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

undone coral
scenic forge
# cerulean wasp this mostly sounds like a proxy pattern

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").

undone coral
hollow veldt
# undone coral are these convex meshes? do they have more than 256 tris?

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

scenic forge
undone coral
#

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

hollow veldt
#

My terrain needs a custom system to fit a design flow and aesthetic, it is also infinite

undone coral
#

you can try using the terrain collider

#

with a terrain that doesn't render

hollow veldt
#

I think I've got an idea...

undone coral
#

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?

hollow veldt
#

it's enough to cause visual hitches

undone coral
#

yes but how often are you generating terrain?

hollow veldt
#

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

undone coral
#

the player is moving fast on a terrain that needs ground accurate collisions?

cerulean wasp
hollow veldt
#

yeah

#

I got this, don't worry, I'll be back with results

scenic forge
#

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.

cerulean wasp
#

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

scenic forge
#

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.

cerulean wasp
#

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

scenic forge
#

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.

cerulean wasp
#

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

hollow veldt
#

@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);
            }
        }```
potent pecan
timber flame
#

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

sage kettle
sleek ingot
#

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?

humble leaf
sleek ingot
#

yeah I was thinking of writing my own agent class

humble leaf
#

Which, funny enough, is what I'm doing here for this small demo. Custom movement sampling the resulting path from the navmesh.

sleek ingot
#

ooooo

#

looks lovely!

cerulean wasp
#

oh, i didn’t realize navmesh was any good for 2D

humble leaf
#

There is no built in solution for 2D 😆

cerulean wasp
#

LOL

humble leaf
#

But there's an online repo that extends it for 2D. Basic enough for generating a mesh based off 2D colliders anyway.

sleek ingot
cerulean wasp
#

do you mean the main A* package?

sleek ingot
#

naah I wrote my own

cerulean wasp
#

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

sleek ingot
#

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

cerulean wasp
#

that sucks

#

shared movement is usually a good idea tho

humble leaf
cerulean wasp
#

2D has too much roadmap. not enough doing lol

sleek ingot
cerulean wasp
#

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

cerulean wasp
cerulean wasp
#

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

sleek ingot
#

aaah yes SRP single responsibility principle

cerulean wasp
#

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

fickle tinsel
#

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.

dusty wigeon
fickle tinsel
#

If it’s any simpler than hyper advanced, I’d love to see a code sample that proves me wrong 🙂

undone coral
dusty wigeon
# fickle tinsel If it’s any simpler than hyper advanced, I’d love to see a code sample that prov...

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.

undone coral
dusty wigeon
#

In UIToolkit there is also the event debugger that can be useful (it might not be applicable in this situation though)

upbeat path
#

I honestly do not see what is so 'advanced' or 'hyper advanced' about

        void OnClick(ClickEvent ce)
        {
        }
...
            RegisterCallback<ClickEvent>(OnClick);

            OnClick(new ClickEvent());
timber flame
#

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?

fickle tinsel
austere jewel
zenith hearth
#

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?

tiny pewter
#

Add additional edges

runic tendon
#

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?

sly grove
#

It's not really any different than if you loaded a different scene while unloading the first

runic tendon
upbeat path
upbeat path
austere jewel
upbeat path
#

Not following your question

austere jewel
#

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

upbeat path
#

Ah, didn't realise that

#

So they want to simulate the OnClick without knowing what the actual OnClick method is, correct?

austere jewel
silk inlet
#

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?

frigid rune
#

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

sly grove
#

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.

frigid rune
#

oops

#

old script

#

that was for getting him to stand, which that is not the direction I went for that

#

its terrible dont even look at it, ima start over

weak quest
#

Is there any best practice for Terrain under dots?

#

how can i use terrain tools on dots project?

hybrid belfry
#

Hi, are there any tools/tutorials on enclosing a square within the smallest circle possible in Unity?

tiny pewter
#

a sqaure or many squares?

hybrid belfry
#

Sorry, a rectangle (though it can be viewed as a square given the longest side)

#

It would be just 1 square

#

or rectangle

tiny pewter
#

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...

hybrid belfry
#

What I am trying to do is scale a Mask with the Camera Fustrum for different screen sizes

#

Thanks

golden flame
#

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

thorn flintBOT
zenith hearth
#

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?

austere jewel
#

!code

thorn flintBOT
zenith hearth
#

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);
                    
                }
tiny pewter
#

there is no loop here

zenith hearth
#

sorry i meant the if statement

tiny pewter
#

btw is backtick, the key above the tab

zenith hearth
#

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)

tiny pewter
#

if closed set contains the point then you should skip it

#

and idk why it was "work" before
btw

zenith hearth
tiny pewter
#

oh my bad

#

btw if the foreach is dead loop, that means openset is growing while iteration

#

wait the remove should be correct

zenith hearth
#

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

tiny pewter
#

oh wait, i misread again, getneighbor should be finite elements it wont cause dead loop

zenith hearth
#

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

tiny pewter
#

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

zenith hearth
#

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

tiny pewter
#

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

zenith hearth
#

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

tiny pewter
#

Limit the iterations of outermost while loop , should be number of vertices if you skip visited vertices
Anyway i have to sleep now

zenith hearth
#

kk ty

tiny pewter
#

Or use debugger to trace

finite sundial
#

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! 😊

sly grove
finite sundial
silk inlet
#

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)?

delicate dove
#

hi guys i have a problem with my unity jump script

humble leaf
humble leaf
#

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.

silk inlet
brisk minnow
#

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

brisk minnow
#

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

upbeat path
sage kettle
#

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

humble leaf
#

Before they happen? How do they happen? Are they falling down or sliding around? What's the actual mechanics here?

tiny pewter
#

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)

sage kettle
#

Basically pressing the arrow will move the gameobject one square in the grid

tiny pewter
#

then?

#

so you want the player move the jellies to clear the path?

errant tartan
#

Is there a way to code an ai like chat gpt in unity?

tiny pewter
#

you can code ai in any language as long as you know the math

devout hare
#

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

tiny pewter
#

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

sinful fossil
#

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

cunning flame
# errant tartan Is there a way to code an ai like chat gpt in unity?

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

brisk minnow
dusty wigeon
dusty wigeon
sinful fossil
sinful fossil
dusty wigeon
sinful fossil
#

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

dusty wigeon
#

I believe that you better find other alternative such as using bounding boxes for placement

sinful fossil
#

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

dusty wigeon
sinful fossil
#

hows that?

dusty wigeon
#

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

sinful fossil
#

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

dusty wigeon
sinful fossil
#

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

dusty wigeon
#

Sure, then use bounding boxes with those and it would work in 99.9% of case I believe.

oblique egret
#

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

dusty wigeon
#

You could always have multiple boxes if needed.

oblique egret
sinful fossil
sinful fossil
oblique egret
#

I took it out of the Euler function bc it wasn't working

#

no one was responding

sinful fossil
sinful fossil
#

So whats the problem? Is it that you can't look down or something?

oblique egret
#

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

sinful fossil
#

oh and its allowing you to go further than you think it should?

oblique egret
#

yea

sinful fossil
#

hmm let me take a deeper look

oblique egret
#

if u look at the video, you can only move when the Y value is 140 or -140

sinful fossil
#

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

oblique egret
#

I'll try it

sinful fossil
#

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

oblique egret
#

I still don't get how to lock the Y axis at 140 and -140 or whatever the lookYLimit is

sinful fossil
#

but you are locking it with the clamp?

oblique egret
#

yes

sinful fossil
#

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

silk inlet
#

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?

scenic forge
#

A blind guess, maybe you are trying to use it before it’s finished initializing?

silk inlet
#

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

scenic forge
#

It seems to me that you just have to wait for it to finish initializing before using, could do a loading scene or something.

silk inlet
#

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

scenic forge
#

That sounds like a separate issue, though I don’t know enough to help sorry.

silk inlet
#

you're all good, no worries

scenic forge
#

The error seems to suggest you don’t have the URI set up correctly though, so I’d probably check that.

silk inlet
#

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

scenic forge
#

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.

silk inlet
#

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

silk inlet
#

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

limpid prairie
#

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?

regal lava
#

should be on the event system

limpid prairie
#

What's that?

#

Oh

#

the gameobject the buttons auto create?

regal lava
#

ye

limpid prairie
#

I don't see where it implies the Enter key as default tho

#

Is it the "Submit" section?

regal lava
#

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

limpid prairie
#

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

regal lava
#

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

remote drift
#

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?

untold moth
stuck plinth
remote drift
#

it's more like last resort I'd say

stuck plinth
#

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?

remote drift
#

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

regal lava
#

so the child of the prefab can be different throughout runtime?

remote drift
#

no

#

will be same game object

#

just different instance

stuck plinth
#

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?

remote drift
#

nah, serialization of reference must be exclusively on target asset

flint wraith
#

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

untold moth
flint wraith
#

...
exactly

#

MicroAudio

#

this works now...

#

but it worked without namespace before

untold moth
#

I really doubt that.

upbeat path
#

not a good idea to have namespace and class names the same

untold moth
#

Since your namespace and class have the same name, you probably had the full namespace in the usings.

flint wraith
#

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

untold moth
#

Methods belong to classes/structs. Not namespaces

#

MicroAudio is a class here

flint wraith
#

Yeah and was trying to do the same inside Microlight.MicroUI namespace

upbeat path
flint wraith
#

i have it in both

untold moth
#

Compare the namespaces from both files. You'll see the difference.

flint wraith
#

I think problem in first one, both are in Microlight namesapce

untold moth
#

Yes. Try using MicroAudio instead

#

Although 🤔

flint wraith
#

I would use other class name but didnt come up with something, as i want to simplify the useage

upbeat path
flint wraith
#

i bet it would be used if class name was something different like MicroAudioClass

upbeat path
#

indeed

flint wraith
#

Yeah

upbeat path
#

it's the way c# evaluates namespace and class names

untold moth
#

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.

flint wraith
#

Maybe i come up with nice way of new namespace

tropic thicket
#

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

timber oak
#

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.

tropic thicket
willow harness
#

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";
        }
    }```
undone coral
tropic thicket
#

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

undone coral
tropic thicket
#

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

upbeat path
# tropic thicket

Its not up to me to say whether it should work on a particular platform or not, but now you know why

simple blaze
#

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.

dusty wigeon
thorn flintBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

livid kraken
#

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.

regal lava
#

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.

upbeat path
#

Anything which is wind powered, windmill, sail boat, I can see a need for the wind data on cpu

livid kraken
eager temple
#

Can someone help me understand if my coding is wrong or if I need to add something

sly grove
surreal forge
#

does anyone know shader graph??

half swan
surreal forge
#

oki

polar orchid
tepid jay
#

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

devout hare
#

Why exactly are you trying to make a record type? I have a feeling there's some kind of misunderstanding somewhere

tepid jay
#

Because records are cleaner and shorter than using a struct or object for when you dont need extra methods

#

Basically: encapsulation

devout hare
#

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

tepid jay
#

Fair enough, so i should just stick to structs

regal lava
#

how much more minimal can you get with a struct

#

unity even suggest using classes too

tepid jay
#

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

Use imgbox to upload, host and share all your images. It's simple, free and blazing fast!

dusty wigeon
thorn flintBOT
upbeat path
tepid jay
#

Im still new to unity and c# how do i do that?

upbeat path
#

its the bit at the bottom of the console when you select an error

tepid jay
#

Ah ok

#

One sec

spark depot
#

Anyone here knows a lot about Inverse kinematics? I need help with FABRIK

tepid jay
# upbeat path its the bit at the bottom of the console when you select an error

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)

dusty wigeon
upbeat path
dusty wigeon
#

!code

thorn flintBOT
tepid jay
#

I can post the entire bigfoot script but really it just interacts with the Alarms struct with two lines:

upbeat path
#

post it

tepid jay
#

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

upbeat path
#

full script please

tepid jay
#

Should i upload both Az and Bigfoot?

upbeat path
#

yes

tepid jay
#

Here is Az:

#

And Bigfoot:

upbeat path
#

That code does not match with the stack trace you posted

tepid jay
#

Each one has a different stack trace though

#

Oh its two that repeata

#

Let me give you the two that repeats:

upbeat path
#

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

tepid jay
#

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

upbeat path
#

which would suggest that the code being run is not the code we are looking at

#

do you have domain reload disabled?

tepid jay
#

I dont know what that is or where to find it

plain abyss
tepid jay
#

Thank you

upbeat path
#

I think your problem is that Alarms is a struct it should be a class

undone finch
#

there is some way to get material name applied only to the face which player is standing on?

tepid jay
#

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?

upbeat path
#

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

sly grove
tepid jay
#

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

upbeat path
#

tbh I hate this unnecessary nesting of classes and structs, it makes following the code so much more difficult

tepid jay
#

Wait no

#

The issue is Alarm

#

So Alarm is not a value type its more of a an object

#

Ug im confused

upbeat path
#

No it is not, alarmsList is causing the problem and that is a member of Alarms not Alarm

undone finch
sly grove
#

yeah you'd check which submesh(es) contain that triangle

#

that will tell you which materials are there

upbeat path
tepid jay
#

So trying to be fancy just got me in trouble, leave structs and records its classes all the way down

upbeat path
#

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

tepid jay
upbeat path
#

it just makes debugging so much easier because the stack trace tells you exactly the route the code followed

upbeat path
tepid jay
#

Dont worry its for my own personal use only , its just functionality im recreating in unity that existed in game maker studio

upbeat path
#

well, it is until you come here looking for help and confuse the fuck out of most people who could help you

tepid jay
#

So what should I call it GameMakerStudioFunctions?

upbeat path
#

remember KISS

tepid jay
#

I used to call the class Short

#

But then that kinda looked like the short datatype

upbeat path
#

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

tepid jay
#

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

upbeat path
#

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

tepid jay
#

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

upbeat path
#

yes, great plan

tepid jay
#

You were correct when i restarted unity the issue was resolved

upbeat path
#

so you do have domain reload disabled

#

worst thing Unity ever did was to allow this

tepid jay
#

Thank you

upbeat path
# tepid jay 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

tepid jay
upbeat path
hazy coyote
#

Anyone know how the new Participant Tap

tepid jay
novel plinth
#

just becareful that not all c# 11 features are supported in Unity with PolySharp

regal lava
pine storm
#

Thanks alot, I didn't see that channel. I will delete my Message and move it

dawn zephyr
#

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

undone coral
dawn zephyr
#

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

undone coral
#

there's also a lot going on in firebase that might make it too complex for you to use

fresh salmon
#

Cache, it's probably data being cached in the endpoint you're using

undone coral
#

the firebase console cannot delete data that is offline, which then gets synced later

#

@dawn zephyr does your code use SetPersistenceEnabled ?

dawn zephyr
#

I dont think it does

undone coral
#

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

dawn zephyr
#

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

undone coral
#

it loads firebase and everything from

scenic forge
tepid jay
#

Oh sweet

tepid jay
#

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...

scenic forge
tepid jay
#

I know what it is

#

But what did u bring it up for

scenic forge
#

That ChatGPT solution:

  • FindObjectsOfType and LINQ are both performance traps.
  • The Select uses an anonymous object instead of value tuple which is unnecessary allocation.
  • The solution is also O(n).
half swan
#

As always, a terrible answer not worth using.
Gpt strikes again

tepid jay
#

Like my friend Andre always says chatGPT doesnt know shit about programming

scenic forge
#

I suppose I did miss one aspect though: are you doing this frequently (like every frame) or infrequently.

tepid jay
#

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

scenic forge
#

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.

earnest canopy
#

guys any idea why compute shader behaves weird in editor but works in playmode?

tepid jay
#

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?

scenic forge
#

I mean finding the closest objects inherently depends on "how many possible objects do I need to check"

tepid jay
#

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

scenic forge
#

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.

tepid jay
#

Thanks let me add that to my study list

undone coral
tepid jay
undone coral
#

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

scenic forge
#

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.

undone coral
scenic forge
#

(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.

tepid jay
undone coral
scenic forge
undone coral
#

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

undone coral
#

but wasting time will be

tepid jay
scenic forge
undone coral
#

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...

tepid jay
scenic forge
#

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.

undone coral
scenic forge
#

(And even the answer isn't that good)

undone coral
#

i am trying to show you how to fish here

#

and perhaps have a less frustrating experience

undone coral
tepid jay
undone coral
#

it is going to make your journey so much smoother

undone coral
tepid jay
#

Yeah sorry this conversation wasnt meant to continue in this channel

undone coral
#

take a look at what i linked, which uses beginner coding ideas instead of LINQ

undone coral
regal lava
tepid jay
#

Oh cool

#

Thanks for these

undone coral
tepid jay
#

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

scenic forge
# tepid jay I think my frustration comes from wanting to get back to the speed of developmen...

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.

tepid jay
#

Thats true

#

I really like how chat gpt breaks down the solution

#

Thank you

scenic forge
tepid jay
#

Its actually much more readable than how allot of people post solutions online.

scenic forge
half swan
undone coral
earnest canopy
#

in playmode it works right

#

but in editor its broke idk why

#

no errors

#

nothing

tepid jay
#

Thank you I am having a blast here with chatGPT, this is definitely going to speed up my learning process with basics.

earnest canopy
untold moth
earnest canopy
#

It is the compute shader