#archived-code-advanced

1 messages · Page 90 of 1

fervent dagger
#

hmm Note: Currently the Globals type has to be defined in an assembly loaded from a file. If the assembly is in-memory (including e.g. when the sample is executed in Interactive Window) the script won't be able to access the type.

#

how do i load System.Reflection

untold moth
#

Why would you need to download it? It should be included in a build automatically if you're using it and the platform supports it.🤔

fervent dagger
#

Reflection not found from Beeee

untold moth
#

And is it Il2CPP build?

fervent dagger
#

unity mono runtime

#

Unity 2023

untold moth
#

What platform are you building for..?

#

Or when does that error appear?

fervent dagger
#

while processing scripts

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

public class script : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        object result = CSharpScript.Evaluate("1 + 2");
        Debug.Log("result = " + result);
    }

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

unity seems to have died

#

relaunches unity

#

ignores compilation errors

untold moth
fervent dagger
#
<b><color=#bb4444>[CscSettings]</color></b> This is first compilation. Request script compilation again.
UnityEngine.Debug:Log (object)
Coffee.CSharpCompilerSettings.Logger:LogInfo (string,object[])
Coffee.CSharpCompilerSettings.CustomCompiler_2021:Register ()
Coffee.CSharpCompilerSettings.Core:Initialize ()
UnityEditor.EditorAssemblies:ProcessInitializeOnLoadMethodAttributes ()
#
System.Exception: Reflection not found: Driver in Bee.BeeDriver.ActiveBuild
  at Coffee.CSharpCompilerSettings.ReflectionExtensions.Get (System.Object self, System.String memberName, System.Reflection.MemberInfo mi) [0x00077] in <1953dcd1da5444c992e14e6e66b4207b>:0 
  at Coffee.CSharpCompilerSettings.CustomCompiler_2021.OnCompilationStarted (System.Object state) [0x00006] in <1953dcd1da5444c992e14e6e66b4207b>:0 
  at (wrapper delegate-invoke) System.Action`1[System.Object].invoke_void_T(object)
  at UnityEditor.Compilation.CompilationPipeline+<>c.<SubscribeToEvents>b__26_0 (System.Object context) [0x0000b] in <4ec4ffcbf9cb40b9a62b20bd9f80de36>:0 
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline (UnityEditor.Scripting.ScriptCompilation.EditorScriptCompilationOptions,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,int,string[],bool)
#
System.NullReferenceException: Object reference not set to an instance of an object
  at Coffee.CSharpCompilerSettings.CustomCompiler_2021.OnCompilationFinished (System.Object state) [0x00038] in <1953dcd1da5444c992e14e6e66b4207b>:0 
  at (wrapper delegate-invoke) System.Action`1[System.Object].invoke_void_T(object)
  at UnityEditor.Compilation.CompilationPipeline+<>c.<SubscribeToEvents>b__26_1 (System.Object context) [0x0000b] in <4ec4ffcbf9cb40b9a62b20bd9f80de36>:0 
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline (UnityEditor.Scripting.ScriptCompilation.EditorScriptCompilationOptions,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,int,string[],bool)
#
Assets\script.cs(10,25): error CS0103: The name 'CSharpScript' does not exist in the current context
fervent dagger
untold moth
#

Yeah, you can't use that at runtime probably.

fervent dagger
#

which is why i need to try to include my own

untold moth
#

I don't think that's gonna work. It's a system library. It probably has some dependencies on the platform and os.

#

Actually. Maybe the unity package would work in a build too.🤔

fervent dagger
#

i cant seem to find anything online about System.Exception: Reflection not found: Driver in Bee.BeeDriver.ActiveBuild

#

imma try using openupm-cli if it doesnt work

#

now i just get

Assets\script.cs(10,25): error CS0103: The name 'CSharpScript' does not exist in the current context
#

oh

Code Samples

    Note: the samples require the following using:
    using Microsoft.CodeAnalysis.CSharp.Scripting;
#

oof

Assets\script.cs(10,25): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
#

installs via openupm

#

A new scoped registry is now available in the Package Manager. o.o

fervent dagger
#

hmm Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)

#
    "org.nuget.microsoft.codeanalysis.csharp": "4.8.0"
  },
  "scopedRegistries": [
    {
      "name": "package.openupm.com",
      "url": "https://package.openupm.com",
      "scopes": [
        "org.nuget.microsoft.codeanalysis.analyzers",
        "org.nuget.microsoft.codeanalysis.common",
        "org.nuget.microsoft.codeanalysis.csharp",
        "org.nuget.system.buffers",
        "org.nuget.system.collections.immutable",
        "org.nuget.system.memory",
        "org.nuget.system.numerics.vectors",
        "org.nuget.system.reflection.metadata",
        "org.nuget.system.runtime.compilerservices.unsafe",
        "org.nuget.system.text.encoding.codepages",
        "org.nuget.system.threading.tasks.extensions"
      ]
    }
  ]
}```
#

imma try re-opening

#

hmm

> openupm view org.nuget.microsoft.codeanalysis.csharp.scripting
(node:59884) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
ERR! 404 package not found: org.nuget.microsoft.codeanalysis.csharp.scripting
#

can anyone create a sample project with Microsoft.CodeAnalysis.CSharp.Scripting package installed and working at runtime

as i still get

Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
open rapids
#

Hey all, I ran into a very weird problem with Threading on Android.

Here is my code:

void Start()
{
    Thread thread = new Thread(inferThread);
    thread.Start(); 
}    

void inferThread()
{
    Dot.SetActive(true);
    results = objectDetector.infer(bgrMatCopy);
    Dot.SetActive(false);
}    ```

On desktop this crashes (as it should) because you can't access the "Dot" GameObject from a thread. But in an Android build this works fine. Which makes me suspect it's not actually creating a thread.

Any ideas what's going on?
thin mesa
#

that's just recoil, no? the crosshair just follows where the gun is actually aiming along with the recoil

earnest canopy
#

hey can someone help me with my terrain system to implement octree for better performance and higher detail

thin mesa
#

or were you perhaps referring to the weapon turning slightly before the body? either way though, this isn't really a code question

#

yes, that's just moving the crosshair instead of locking it to the center of the screen. create a ray from the front of the gun, choose a distance along that ray and convert the position to screenspace and you have the crosshair's position

urban warren
#

I am working on an custom animation curve thing. I am working on making controls for it. But having a hard time figuring out how to draw the in/out tangents so that they are a constant radius of the keyframe. The tangent is just a float.

It is one of those things where I feel like I almost understand what I need to do, but just not clicking.

austere jewel
urban warren
austere jewel
#

I'm unsure what the difficulty would be; in UITK you could position a rect on a point and translate it by half its length, or position it manually, or draw it using painter2D

urban warren
#

The difficulty is that the tangent is a float. Not a Vector2

austere jewel
#

I am just about to implement something similar myself so I can look into the logic behind it too

urban warren
austere jewel
#

The docs seem to say it's just a rise/run, but that doesn't completely make sense to me so I'll have to check

austere jewel
urban warren
austere jewel
#

It's the gradient of the slope of the curve

#

0 if flat, and it cannot be vertical (undefined)

#

so to draw the tangent I'd find the aspect ratio of the view, width / height and use that as x, and math.atan2(tangent, aspect) should be that angle in radians

#

(untested)

urban warren
austere jewel
# urban warren atan2 seems like the right track...? I guess I am not quite following what you m...

The value of the tangent is the y side of a right-angled triangle where the other side is 1.
The view into the curve isn't necessarily a square though, where the X and Y axes are the same length. So to find the correct angle for the tangent you need to involve the aspect of the view. So, multiply the 1 by the aspect, and feed those x and y values into atan to get the angle of the hypotenuse line formed by the X axis and the tangent value (the length of the y-side)

urban warren
#

Which is basically just

Vector2 dir = new(1, keyframe.TangentOut).normalized;
float dx = nextKeyframe.Time = keyframe.Time;

Vector2 resultDir = dir * dx;
austere jewel
#

That also works, what you do depends how you're drawing the line

#

They use a NormalizeInViewSpace function to do the aspect stuff

urban warren
#

You know what though, I'll take it. Few things to iron out, but even still. If it works that is good enough for me. Thank you very much Vertx! 😄

kindred tusk
#

I think I'm losing my mind here, why is this variable being set to "" before Awake:

#nullable enable

namespace EffortStar {
  public class NarrativeController : MonoBehaviour {

    // ...

    string? _leftCharacterId;
    string? _rightCharacterId;

    // ...

    void Awake() {
      if (_leftCharacterId == "") {
        Debug.LogError($"{nameof(_leftCharacterId)} is empty string", this);
      }
    }

  }
}

#

I must be doing something wrong somewhere

thin mesa
#

is your inspector set to debug mode? if so, then private variables are being serialized so unity is assigning an empty string to it

kindred tusk
#

Damn, that is wildly shit

#

I didn't realize it actually changed their values

#

I thought it would just render them to the screen using reflection

#

why would it do that???

thin mesa
#

yeah, you should be able to mark as [NonSerialized] to get around that. no idea why it does it though, i assumed the same as you but i guess it's probably easier to just serialize everything

kindred tusk
#

Just had to go AFK for a second to decompress after an hour of confusion

kindred tusk
#

ah, no. it was it!

#

thanks

#

I had it in two places

timid citrus
#

Hi
I have a script that calculate an azimutAngle and polarAngle from joystick input. Then creating a quaternion rotation from those two angles and using Lerp to rotate the target. With this i am able to move a object with the joystick so that it points forward with 0,0 and is rotated to its side if i press full left.
The issue i am getting is that when i move the object from left to right it rotates around itself it. And is "upside down". Noticed that if i switch the polar angle to positive or negative the behaviour is the other way around. Have been using ChatGPT and Muse.

 // Calculate azimuthal and polar angles based on joystick input
                    float azimuthalAngle = Mathf.Atan2(horizontalInput, -verticalInput) * Mathf.Rad2Deg;
                    float polarAngle =
                        Mathf.Asin(Mathf.Clamp01(Mathf.Sqrt(horizontalInput * horizontalInput +
                                                            verticalInput * verticalInput))) * Mathf.Rad2Deg;

                    // Scale the polar angle based on the sphere size
                    polarAngle = _sphereSize;

                    // Create a quaternion based on azimuthal and polar angles
                    Quaternion rotation = Quaternion.Euler(-polarAngle, azimuthalAngle, 0f);

                    // Apply the rotation to the child object, taking into account parent's rotation
                    targetObject.rotation = Quaternion.Slerp(targetObject.rotation, parentObject.rotation rotation,
                        Time.deltaTime * rotationSpeed);
glacial wedge
#

Hi,
I want to debug log the stacktrace like the ones that is outputted when there is a runtime error that logs all the previous method calls.
how to?

glacial wedge
#

no?

sly grove
#

As does Debug.LogError

glacial wedge
#

I'm inside a static class and method

sly grove
sly grove
#

It is itself a static method

glacial wedge
#

oh, yeah. I miss one part.... I need more than the script call, i want the scene gameobject that execute the previous script call

sly grove
#

You would have to include that information manually. That information won't be available by any automatic means

glacial wedge
#

but I wont pass an additional context only for debug assist

devout hare
#

Put Debug.Log(name) on line 27 of TextView.cs and see what it prints just before the warning

#

or use the debugger

umbral trail
#

is there any way to tell if the player is running on an embedded gpu?

novel plinth
#

you could try Process.GetProcessesByName(processName) then inspect the returned Process array and see if you can get it from there.
We did similar to what you're trying to do but kinda forget what we used back then

#

I don't think Unity has an api for this, I might be wrong, you should double check

umbral trail
#

I'm wondering now if it would be better to just use a blacklist of unsupported egpus (eg intel HD/UHD) since there are going to be a bunch of high end ones that should be good enough

novel plinth
#

I honestly think you shouldn't be too concerned about that

umbral trail
#

there isn't that I can see, can't tell if you get dedicated vram either 😦

novel plinth
#

if their hardware aren't powerful enough to play your game due to ancient gpus, it's on them

umbral trail
#

we've already had someone complain about the game being "glitchy" when they have a dainty laptop, so just going to put a warning at start up

#

some people just don't understand

glacial wedge
#

Is it possible to search for object in scene that has a class that contain a property of a specific type?

novel plinth
#

runtime? if so, better to pool them in a static List/Dictionary after instantiation (Awake or Enable)

unique mountain
#

hey guys, how can I make the tests runner to finish testing all elements in a list even if it fails for 1 element

glacial wedge
# upbeat path yes, reflection

can you give me an example?

#if UNITY_EDITOR
        [MenuItem("Tools/Localization/Find empty text")]
        private static void FindReferences()
        {
            // GameObject.find
search for classes that contains string property empty
        }
#endif
urban warren
#

Is there any caveats to using source generators in Unity? Cause this feels like it is going to speed up editor tooling a ton.

scenic forge
# urban warren Is there any caveats to using source generators in Unity? Cause this feels like ...

Two major points:

  • Unity does not support project reference, so you have to build the SG project separately and copy the dll over. You can automate this to make it easier for you, but it's not that big of an issue because SGs tend to be "write once and done."
  • Unity doesn't not support the latest incremental SG, so you are stuck with the old one with worse performance. It shouldn't be too much of an issue, I have a nearly 100k LoC project with heavy use of SG and I don't see noticeable performance degradation.
#

SG and editor scripts can both fulfill the role of code generation, and my general advice is that if you want to generate code purely based on code and generate immediately (so you don't need to tab out of IDE back to Unity editor, wait for it to run, tab back into your IDE), SG is a good fit; otherwise consider good old editor scripts.

urban warren
# scenic forge Two major points: - Unity does not support project reference, so you have to bui...

Sweet, so nothing really.
I wanna write SGs for parsing UXML to do stuff like automatically querying elements so I don't have to write a bunch of rootVisualElement.Q<Button>(className: "some-class-name");
And hooking up ListViews and Buttons and that sort of thing.

And then probably another one for creating 'viewmodels' classes that automatically get certain properties in a SerializedProperty/Object

scenic forge
#

Yeah those sound like really good use cases of SG.

urban warren
#

Yeah, I'm familiar with the MVVM communitytoolkit. I have actually been doing stuff with Avalonia.ui (like WPF) in my free time which is part of what gave me the idea to try out source generatos.

I'm not sure if it is better to just do automagically and match method names with button names/classes. Or do explicitly use attribute, or an attribute with a uxml class/element name... gotta think about it I guess.

But this will take down the boilerplate I write by sooo much

#

Maybe partial methods for somethings like ListView make/bindItem... 🤔

#

Not really sure what sort of 'best practices' there are for SGs

scenic forge
#

Yeah I think the general consensus is to make things explicit so it's clear what's being generated, and helps with debugging too, rather than relying on some opaque rules like naming a certain way.

#

But, in some cases I do think generating implicitly based on rules is fine, eg stuffs like DTO for JSON where they serve one purpose and one purpose only.

urban warren
#

DTO?

scenic forge
#

Eg:

[Json]
public partial record GameSave(int Level, float Hp) {}

var gameSave = JsonUtility.From<GameSave>(someJson);
gameSave.Validate();
#

In this case stuffs are generated (eg validation) implicitly based on the fields Level/Hp with no explicit annotation, but is imo fine because GameSave serves that one single purpose.

urban warren
#

Ahh that makes sense.

Just trying to understand common usage. So if I wanted to bind a method to a button. Which would be the way you would suggest? B?

// Auto-generated
public Button LogMessageButton { get {..} }

// User defined.
// A: Auto matched based on the method name.
private void LogMessage(){ }

// B: Found by the attribute, auto-matched on the method name
[Command]
private void LogMessage(){ }

// C: Found and matched by the attribute. Method name dosn't matter
[Command(nameof(LogMessageButton))]
private void LogMessage(){ }
scenic forge
#

I'd probably go with B.

#

The issue with A is that you could be writing a LogMessage method that wasn't meant to be a command but rather just a private utility method, and one day you added a button that just happens to have the same name and suddenly they are wired together unknowingly.

#

C is a bit verbose but is fine if you prefer that explicitness.

urban warren
#

Yeah that is kind of what I was thinking the issue was with A as well as I was writing that out.

#

If you don't mind. What about a ListView do you think, with its makeItem and bindItem? Same thing or would you do something different? I was considering maybe partial methods to force implementation?

scenic forge
#

Hmm that I'm not too familiar to give a suggestion.

#

SG does veer into the territory of API design though, it's almost like making your own library/framework, so you might need to go through a few iterations to settle on the one you like/fits your use case the most.

urban warren
#

Just two events that the ListView requires you to subscribe to in order to have it draw the items.
But doesn't really matter too much. Thank you for the help! SGs are so cool, and going to save me so much time and make the code look so nice! 😄

#

Except for the SG code it self, that is ugly haha

novel wing
urban warren
novel wing
#

Just to clarify, by single method I meant something along the lines of void Setup(out Func<> Make, out Func<> Bind). But no clue what's a nice way to do it

urban warren
#

Ahh, like that. Probably easier to still just use two methods or manually assign them. But yeah, no super clean way to do it

charred drum
#
    {
        object[] _newArray = new object[inArray.Length + 1];
        for (int i = 0; i < inArray.Length - 1; i++)
        {
            _newArray[i] = inArray[i];
        }
        _newArray[_newArray.Length - 1] = add;
        //Return new array
        return _newArray;
    }```
Hello, this function creates a new array, and returns what I need it too, confirmed with debug. However: When I use it like this?

```items.Weapons = Astro_AddToArray(items.Weapons, _loadObj) as ScriptObject_Weapon[];```
``items.Weapons`` is simply set to an array of 0. Is there a reason why this is happening?
#

ScriptObject_Weapon is a ScriptableObject, also

austere jewel
#

Use a List, and almost never use object

scenic forge
#

Learn and rewrite that method using generics.

austere jewel
#

Or just use a List and use Add and don't do this at all

charred drum
#

Yeah, it's set to null, actually

kindred tusk
#

When we make a macOS build using il2cpp we get an null ref exception from within an automatic code signing process:

System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.)
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at UnityEditor.OSXStandalone.CodeSigning.HashUtils.WriteHashString(Byte[] data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 41
   at UnityEditor.OSXStandalone.CodeSigning.HashUtils.HashFile(NPath file, Byte[]& sha1Hash, Byte[]& sha256Hash) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 148
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignResourceFile(FileToSign file) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 243
   at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.<>c__DisplayClass9_1.<SignFilesWide>b__0() in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 193
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)

This happens on 90% of our IL2CPP builds. (Mono builds succeed.)

We can't work out how to configure code signing. In this case we actually want to disable it so we can sign our own builds afterwards.
However I'm additionally curious what developer ID it is using to sign, since there seems to be no option to configure this in any way.

We're on Unity 2022.3.12
We can't reproduce this issue on a fresh project.

We've been struggling with this for days, any insights would be appreciated!

#

The docs also kind of contradict themselves here:

Unity automatically code signs any application it builds for macOS.
- Code signing & notarization

To code sign your application you need to use the command line. On your machine, open Terminal and navigate to the directory that the application is in.
- Code sign the application

charred drum
#
    {
        List<T> _newArray = new List<T>();
        foreach(T item in inArray) 
        {
            _newArray.Add(item);
        }
        _newArray.Add(add);
        //Return new array
        return _newArray;
    }```
The code that worked
kindred tusk
kindred tusk
#

Or:

static T[] AddElementToArray<T>(T[] array, T element) {
  System.Array.Resize(ref array, array.Length + 1);
  array[^1] = element;
  return array;
}

Then you can do:

items.Weapons = AddElementToArray(items.Weapons, _loadObj);
austere jewel
#

What was wrong with just list.Add(...), why are we even using an array

kindred tusk
#

dunno

#

the example was:

items.Weapons = Astro_AddToArray(items.Weapons, _loadObj) as ScriptObject_Weapon[];
austere jewel
#

Unless this is editor-only, this is a stupid premise, and if it is, then just use ArrayUtility.Add

scenic forge
#

Either they don't know that you can just use List<Weapon> and add to it directly, or they have a requirement to make a new copy rather than mutating.

austere jewel
#

I don't really like giving bad-code answers until those requirements are specified meaningfully. If they don't understand generics, I will go for the lowest common denominator answer

scenic forge
#

(Side note if it was already a list and you for whatever reason need to make a copy rather than adding directly, you can do:)

items.Weapons = new(items.Weapons) { weaponToBeAdded };
charred drum
# kindred tusk Ah, actually in this case you should do this: ```cs static void AddElementToArra...

That's actually quite better, thanks!

I should also say why it's an array is because this is how I originally programmed it, without think I'd actually ever change it. Essentially, what's in the array at startup is the vanilla assets

This code is actually used to add addons using AssetBundle
It unpacks the items in an Bundle, and then checks what object is which, and if it's a specified object (Like Scriptobject_Weapon), it adds to the Item Schema

I guess that the reason I don't change to list is because it would break a lot of code (Which would take a while to debug and make sure works correctly, as I use this Item Schema a lot), and also because I would have to re-fill the list with the items, which there are a lot of lists and a lot of items to re-fill, which is time consuming

kindred tusk
charred drum
#

Honestly, me neither!

Anyway, I DID just use it like:

for (int i = 0; i < _originalArray.length - 1; i++){
  items.Weapons[i] = _originalArray[i];
}
items.Weapons[items.Weapons.Length + 1] = _loadedItem;```

But it feels so cluttered, as I have to do this with maps, apparel, items, and more. I wanted to be able to just call a function
formal lichen
#

could also just use a list (use Linq to convert back to an array if needed)

charred drum
#

I believe that's what I did in the code, here's what it's like for weapons:

{
    items.Weapons = Astro_AddToArray(items.Weapons, _loadObj as ScriptObject_Weapon).ToArray();
}```
#

Thanks friends!

scenic forge
#
if (_loadObj is ScriptObject_Weapon weapon)
{
    // You can use variable weapon now
}
charred drum
#

Man, I never knew any of this before 😅

This will help me so much in programming

fervent dagger
#

so, anyone know how to fix

Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
charred drum
#

What's the line in question? And prefferably the function it's in

untold moth
#

You can inspect the assembly in visual studios to confirm that it doesn't contain the Scripting type.

fervent dagger
#

where do i put the dll

charred drum
#

Is it possible to add a string of information to an AssetBundle manifest? I'd like to use it to add an author's name

fervent dagger
#

hmm

Assets\script.cs(11,38): error CS0117: 'CSharpScript' does not contain a definition for 'Evaluate'
#
Microsoft.CodeAnalysis.CSharp.Scripting.dll
Microsoft.CodeAnalysis.Scripting.dll
#

does winget install Microsoft.NuGet

#

hmm \nuget\Microsoft.CodeAnalysis.CSharp.Scripting.4.9.0-2.final\lib\netstandard2.0

#
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         1/11/2024  12:48 PM                Microsoft.CodeAnalysis.Analyzers.3.3.4
d-----         1/11/2024  12:48 PM                Microsoft.CodeAnalysis.Common.4.9.0-2.final
d-----         1/11/2024  12:48 PM                Microsoft.CodeAnalysis.CSharp.4.9.0-2.final
d-----         1/11/2024  12:48 PM                Microsoft.CodeAnalysis.CSharp.Scripting.4.9.0-2.final
d-----         1/11/2024  12:48 PM                Microsoft.CodeAnalysis.Scripting.Common.4.9.0-2.final
d-----         1/11/2024  12:48 PM                Microsoft.CSharp.4.7.0
d-----         1/11/2024  12:48 PM                System.Buffers.4.5.1
d-----         1/11/2024  12:48 PM                System.Collections.Immutable.7.0.0
d-----         1/11/2024  12:48 PM                System.Memory.4.5.5
d-----         1/11/2024  12:48 PM                System.Numerics.Vectors.4.5.0
d-----         1/11/2024  12:48 PM                System.Reflection.Metadata.7.0.0
d-----         1/11/2024  12:48 PM                System.Runtime.CompilerServices.Unsafe.6.0.0
#
    Directory: C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\System.Buffers.4.5.1\lib


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         1/11/2024  12:48 PM                net461
d-----         1/11/2024  12:48 PM                netcoreapp2.0
d-----         1/11/2024  12:48 PM                netstandard1.1
d-----         1/11/2024  12:48 PM                netstandard2.0
d-----         1/11/2024  12:48 PM                uap10.0.16299
#

should i delete all the other lib dirs other than netstandard2.0

#

or can i keep them without problems

#

oof 526 errors

#
Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets already contains a ruleset file: Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets/DataflowRulesEnabled.ruleset. Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets/MicrosoftCodeAnalysisCorrectnessRulesDefault.ruleset will be ignored.
#
Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/buildTransitive/config already contains a globalconfig file: Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/buildTransitive/config/analysislevelmicrosoftcodeanalysisdesign_3_3_3_default_warnaserror.globalconfig will be ignored.
#
Failed to find entry-points:

Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ---> System.Exception: Failed to resolve assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in directories: C:\Unity_Editor\2023.2.3f1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32

C:\Unity_Editor\2023.2.3f1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32\Facades

C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CodeAnalysis.Scripting.Common.4.9.0-2.final\lib\net7.0\ko

...

#
error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CSharp.4.7.0\lib\netstandard2.0\Microsoft.CSharp.dll' and 'C:\Unity_Editor\2023.2.3f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Microsoft.CSharp.dll'. Remove one of the duplicate references.
#

i did

PS C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget>
nuget install Microsoft.CodeAnalysis.CSharp.Scripting -Version 4.9.0-2.final -Verbosity detailed
#

i deleted all dirs except for netstandard2.0

#

hmm

error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CSharp.4.7.0\lib\netstandard2.0\Microsoft.CSharp.dll' and 'C:\Unity_Editor\2023.2.3f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Microsoft.CSharp.dll'. Remove one of the duplicate references.

tho now i only have 1 error

#

hmmm if i move it into Assets - Unused and remove the .meta file then i get

Assets\script.cs(11,38): error CS0117: 'CSharpScript' does not contain a definition for 'Evaluate'
untold moth
fervent dagger
#

yea

untold moth
#

Press F12 when your caret is on the CSharpScript type and see what members it has.

#

And what assembly it takes you to.

#

Also it seems like there is no Evaluate. There's EvaluateAsync.

fervent dagger
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Microsoft.CodeAnalysis.CSharp.Scripting;

public class script : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        object result = CSharpScript.Evaluate("1 + 2");
        Debug.Log("result = " + result);
    }

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

im doing this

from

Code Samples

    Note: the samples require the following using:
    using Microsoft.CodeAnalysis.CSharp.Scripting;
Evaluate a C# expression

object result = await CSharpScript.EvaluateAsync("1 + 2");
untold moth
#

Don't you see any problems with your code?

#

Compared to the "from"

#

It's not the same what they have, is it?

fervent dagger
#

await requires async method

untold moth
#

Well, that's the only thing they have. So you've gotta use it

#

Make Start async. Or get the task result. That would make it execute synchronously.

fervent dagger
#

oof Visual Studio froze

#

ffs *uses vs code instead

fervent dagger
#

finally finished evaluating

#
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
#

would i do object result = CSharpScript.EvaluateAsync("1 + 2").Result;

untold moth
kindred tusk
#

Because the async task won't have completed

#

or is it not actually async?

untold moth
#

No. It blocks until the result is ready.

kindred tusk
#

Ahh, cool.

#

So fine if it's in a thread

rocky mica
#

@fervent dagger is there anything specific you wanna achive with async methods?

fervent dagger
#

code compilation

rocky mica
#

gotcha, are you looking for multi thread performance? if not I suggest using something like Unitask

urban warren
#

Any idea why rider would see a source generator just fine, but Unity would show compile errors about members not existing as if the source generator isn't running?
(SG creates members in a partial class)

urban warren
#

Ahh looks like there were compile errors.

#

Ahh, nope still not seeing it. Is there a way to debug this...?

#

Unity's example from the docs works fine. Just my code that isn't beeing seen by Unity.

#

Just tried manually doing it and all the code works. So it is just Unity not seeing it for some reason... 😕

scenic forge
# urban warren Unity's example from the docs works fine. Just my code that isn't beeing seen by...

If example works for you, then that means you probably have SG properly integrated and the issue lies in your SG code.
One thing with SG is that if it fails (eg throws an exception) there would not be any indication of it and the file just silently not get generated. There are ways to debug SG but I think VS is required (😒), instead a method I use is to try..catch your SG and generate a source file with the caught exception as comments in it, so you can inspect that in your IDE.

#

Some blind guesses without know the problem, are you doing file IO in your SG? Because that is not allowed.

urban warren
scenic forge
#

🤔

#

I'm fairly certain that file IO isn't allowed and that would throw, but now I can't be sure.

urban warren
#

Well. I just commented it out and it works...

#

No idea why it isn't throwing though

#

Any suggestions about how I would go about reading the uxml then?

scenic forge
#

The mechanism for SG to read files is via additional files compiler argument (because SG runs on every key stroke in your IDE so doing file IO will tank your IDE performance)

#

But I think that would mean you need to add all your uxml files as compiler arguments though, and that sounds a bit yikes.

urban warren
#

Can I add them to Addition Files some how? Is that a thing in the .csproj file...?

scenic forge
#

Via the compiler arguments in (IIRC) Unity project settings.

#

You'd also need to add them to your CSProj files though otherwise your IDE wouldn't know.

#

But yeah this is why I recommend to use SG only for generating code based on code, and generating code based on assets is probably better done with editor scripts.

urban warren
#

😭

#

It is a pain, but I guess that is what I gotta do 😦

#

Thank you for the help! I am sure I will find other stuff to use source generators for.

#

Oh and I did more testing and yeah, in rider it generates the code from reading a file just fine. Evn seems to build. But in Unity, not so. No errors or warnings or exceptions. Just fails silently.

scenic forge
#

Interesting, I can't say if it's Unity or Rider that's being inconsistent.

hardy jacinth
#

A C# specific question, needed ASAP:
How do I call a concrete method of a class, when I am referencing it by it's interface, that happens to have a default method defined?

icy smelt
#

Did I get it wrong, or there still a big overhead when not caching the transform component of our behaviors?

tired fog
#

Can I render alpha to the camera as a value? Im trying to get a custom render texture and I would like to capture alpha as value and not as a blend. Like the alpha channel of a render texture having data.
The idea is that I want to pass four values generated by a particle system texture (those 4 values being on the texture that the particle makes) by capturing it with a camera, and saving it to a render texture

tired fog
hardy jacinth
tired fog
#

A, a bad but working approach would be to cast it

#
Iface x = new Concrete();
(x as Concrete).DoThing();

but I can see how you wouldn't want that

#

an interface however, shouldn't have default methods tho, you would be better using abstract classes, or in the best case since we are in unity, a component based system. Can I ask why are u using interfaces for such a case?

hardy jacinth
#

unfortunately due to some design decisions earlier I cannot easily move to abstract classes for now

compact ingot
#

best thing to do is to rewrite the whole thing and thank yourself later for it

hardy jacinth
#

I can explain in more detail what I am doing and maybe it will give some more context, but the explanation could be a bit lengthy

tired fog
#

Make a thread for it, and let's see

compact ingot
#

the explanation doesnt matter really

#

its just bad design

hardy jacinth
# compact ingot its just bad design

for now let me explain a bit more, I know the design is far from perfect for now but I needed something between "prototype" and "perfect design" that I could iteratively refactor into something better

compact ingot
#

its not about perfect, its fundamentally flawed

hardy jacinth
#

also the part I'm doing right now is basically separate from the unity ecosystem, it could be a separate dll

#

ok, here it goes:

compact ingot
sage radish
tired fog
#

Ah true lol, i didn't check the alpha of the render texture

#

but it's there

finite sundial
#

Anyone knows how can I start implementing profile pictures of users in a list ex. leaderboards using firebase? I have no idea where to start

potent stream
#

Like from steam?

timid blaze
#

What are some of the best Unity interfaces you guys use?

timid blaze
#

Sorry probably not making sense. Are there any unity interfaces. That let you tap into events that unity fires like whether that be from a collision, ui event, etc.

upbeat path
sly grove
#

It's not really productive to just list things. That's like reading the dictionary, it isn't going to help you learn.

upbeat path
#

I was presuming interface in the strict C# terminology

timid blaze
sly grove
timid blaze
upbeat path
#

IPointer is not a tool, it is an interface available from the Unity Engine

#

I'm still failing to grasp what you are actually asking for here

#

what do you mean when you say 'interfaces' because that has a very strict interpretation in the C# world

timid blaze
half swan
#

It's kind of sounding like you just anything from the API

upbeat path
#

but what do you mean by interfaces, I think we are talking at cross purposes here

half swan
#

And you should be specific about what you want, not just generic "what is there", because you've been linked to the docs twice already, which shows what there is
The second link was for evenets you may be talking about

upbeat path
timid blaze
# upbeat path Do you know what a C# Interface is?

I was just asking if there are any interfaces I could use instead of re-inventing the wheel for my own game. I am currently using a interface that will help handle collisions, but I wanted to know if there are any other similar tools. I should've started off with that.

upbeat path
#

you still haven't answerd the question 'what do you mean by interface?' until you do this conversation is pointless

upbeat path
#

so which interface are you using to help with collisions?

timid blaze
scenic forge
#

An interface is a contract between the implementer (what you need to implement) and consumer (what has been implemented and allowed to use), interface by itself when removed from the two parties is not useful, so asking a list of useful interfaces isn't exactly a question that makes sense.
You will know when an interface is useful when 1) you see a consuming method asking for an interface, so you the implementer implements it, or 2) you the consumer want to be able to consume multiple implementations in the same way, so you create an interface for implementers to implement.

#

If you don't have either party, an interface is useless, and when you have one party, that party tells you which interface is used and thus useful.

upbeat path
#

coz I'm struggling to understand what you actually are asking for

timid blaze
#

Scripts that need to react to a collision implement ICollisionHanderable

A CollisionHandler checks for the correct interface. If it has it then it sends a unity event to the corresponding script that implements ICollisionHanderable. Its not perfect, but do you guys find yourself commonly using specific Unity Engine Interfaces? I know you have to implement your own logic.

upbeat path
#

OMG, I honestly do not know what to say to that

timid blaze
tiny pewter
#

it is quite weird to broadcast collision message to other guys by publisher-subscribers pattern

upbeat path
# timid blaze Could you try?

If you were somehow wrapping OnCollisionEnter in your own Interface it would have been interesting to see (which is why I asked), what you have done is the exact opposite which makes it pointless, redundant and unnecessary

timid blaze
upbeat path
#

the whole point of Interfaces is to enforce a contract which can be seamlessly used

timid blaze
misty glade
#

I have a bug that expresses itself on one specific device (google pixel 6). There's some massive jutter when doing various things - camera panning/zooming, typically. We're using Cinemachine. Since I can't repro this in the editor or other devices, what sort of things should I be looking at?

#

(I do have access to a physical google pixel 6, but .. honestly, don't know where to start in on this particular bug)

tall ferry
# timid blaze Sorry these are two completely different scripts. Is your perception that this i...

Why do you even need interfaces here?
"TriggerHandler checks the incoming collision object... if the incoming object has that interface then it will..."
Why cant that objects scripts just use the physics messages and do logic themselves? This looks like some massive over engineering to do with no benefit. It's just a bunch of extra events which arent free (relatively since the alternative is no events)

timid blaze
finite sundial
potent stream
#

oh if you want users to upload pics you would need to serialize them and store them i have done it before a long time ago but it wasnt super easy

tall ferry
tall ferry
unborn relic
#

Hello,

I have the following use case. I have a scene manager that handles loading screens between scenes, and also shows progress bars and what not.
Some scenes are only considered ready if there are multiple events raised (on world generation compelte, on player spawned, on music started playing etc.)
What is a clean way to check if all events from a list of UnityActions have been invoked?
(If there is one such pattern)

sly grove
unborn relic
#

thanks!

#

how can I hold a queue of UnityAction's regardless of their generics? <int>, <string> etc?

scenic forge
# unborn relic how can I hold a queue of UnityAction's regardless of their generics? <int>, <st...

If the queue is just for keeping track of what has already been called, then you don't need to know the type specifically, you can just use Queue<object>.
Or really, since it sounds like you don't care about the event order, a HashSet<T> can also work and semantically makes more sense. But even better, assuming an event can happen only once, you can just have an int to keep track of the number of event called and check if it has reached the total event count.

#

But maybe the scene should just have one big ready event for when it's completely ready, and listeners can just listen to that.

cerulean wasp
#

you might want a list tbh, if you want to not erase it as you iterate through it

#

Queue<object> sounds both correct and cursed imo

unborn relic
cerulean wasp
cerulean wasp
#

IEnumerator CoordinatedLoading(string filename) {
OnBeforeLevelLoad?.Invoke();
yield return null;
LoadLevelFile(filename);
yield return null;
OnLevelLoadEarly?.Invoke();
OnLevelLoad?.Invoke()
OnLevelLoadLate?.Invoke();
}

#

docstrings on each delegate detail the kinds of things expected to be happening during each phase. Like my tilemaps are changing during OnLevelLoad invocation. So everything that needs to happen on the raw level file happens OnLevelLoadEarly. Everything that modifies level goes OnLevelLoad, and everything that acts on the fully modified level goes OnLevelLoadLate

#

does that make sense?

#

this is a bit different from your question with respect to making a load bar, but this is how I coordinate my level loading

#

My names could use some work on that front tho

scenic forge
# cerulean wasp IEnumerator CoordinatedLoading(string filename) { OnBeforeLevelLoad?.Invoke(); y...

Not related the original question anymore, but I find stuffs like this to be very brittle. You are largely relying on convention to make sure the things are happening in the right order, and is one mistake away from creating a hidden bug that cannot be caught unless you notice it at runtime. In the future if you need to hook into one more thing, suddenly you need to make a new OnLevelLoadSuperLate or OnPostLevelLoad.

cerulean wasp
scenic forge
#

Which is still convention.

cerulean wasp
#

true i could have probably called the class manually, but it felt dirty

#

part of it is that I only established a convention after realizing what the pattern was to make everything work

#

eg the tilemaps changing is the critical moment where some things need to happen before vs after it

#

i believe the middle delegate only has one entry, iirc

#

which doesn’t make it right, but this is the pattern I only realized later

#

(and if I knew that was going to be the critical point, then I would have made that middle part differently, probably)

#

i feel impending danger

scenic forge
#

For something like loading, imo a much better pattern is to have each separate machinery that does just one thing and one thing only. That machinery could be a class, just a plain function, whatever, it does not matter.
Each machinery takes in some data (or takes in nothing), does some operation to it (whether that's changing the data that was fed in or creating data by itself), and spits out data in a new shape.
This way you let compiler enforce the loading for you: if a piece of machinery requires data from the output of previous machinery, you literally cannot execute them in the wrong order because the former wouldn't have the necessary input to start; if multiple pieces of machinery do not depend on each other's data, you can easily see that and turn them to run in parallel if needed.
This way you successfully turned your loading from convention based with no help from compiler, to something enforced by compiler to never be able to make a mistake.

cerulean wasp
#

that makes sense, but those parts of loading don’t necessarily have anything to do with each other, except for relationship to the middle part which edits tilemaps

scenic forge
#

And no issue with that, each part doesn't have to depend on each other and can be completely independent, but the point is by doing this you can easily see it: this machinery takes in no data so it's independent and I'm free to execute this in any order I want.

cerulean wasp
#

one example is a singleton that just takes a census of what was loaded into the tilemaps. And another is a singleton that just needs to know that it should clear its collections, because it’s about to be called

#

and neither of these functions require any arguments. it’s just a timing thing

scenic forge
#

a singleton that just takes a census of what was loaded into the tilemaps
That part is not independent, it very much depends on the tilemaps already being loaded.

#

And what's your way of ensuring that singleton is only executed after the tilemaps are already loaded? Nothing other than convention.

cerulean wasp
#

i mean, why would you subscribe a method to OnBeforeLevelLoad if you want to execute it OnAfterLevelLoad?

scenic forge
#

Exactly, that's entirely on the programmer to read the docs and make sure they understand which event to hook in order to do what they want. If they made a mistake, now the singleton will collect useless census data because tilemap is still empty, and you wouldn't notice that problem until runtime.

cerulean wasp
#

OnBeforeLevelLoad mostly notifies things to clear their contents before the level is loaded. So i don’t see how this could depend on anything? Without just adding a prerequisite that does nothing?

#

or adding an enum argument that clarifies what stage of level loading we’re on?

#

i guess I don’t understand how I would address your point without violating the Open/Close principle

scenic forge
#

You are missing the point, the point is that you are entirely relying on programmer to not make a mistake, where as if you have something like:

var tilemapCensus = new TilemapCensus(tilemap);
tilemapCensus.Execute();

You literally wouldn't be able to do it in the wrong order because you don't have tilemap loaded yet, it entirely eliminates the possibility of error because compiler is protecting you from it.

cerulean wasp
#

but that would require me to edit the code for level loading every time I add something that needs to go off when my level loads

#

which doesn’t sound correct

#

and a lot of those methods rightly contain no arguments

scenic forge
#

Loading and notifying is different though, there's nothing stopping you to still have a "level loaded" event only for notifying listeners (but not for listeners to hook into and modify the data, because that's loading)

cerulean wasp
#

maybe it’s best if I explain a bit more

#

the main script in OnLevelLoad that modifies the level basically goes into the tilemaps, and creates gameobjects based on tiles, and erases some of those tiles

#

OnLevelLoadEarly are methods that need to know that the level finished loading in its raw, unadultered state.

#

OnLevelLoadLate are methods that need to know that everything is now instantiated (so it’s safe to look at groups of gameobjects or tiles without their existence changing as a result of other things in the delegate)

#

naming aside, it makes sense as the functions within a given delegate must not affect each other in any way. I just lack a smart way to enforce that across like 15 singleston methods in a delegate

#

without making one giant cursed function to specifically orchestrate a specific order of calls

unborn relic
#

hello, i am loading a scene additively and async. the async handle shows a progress of 0.9f, yet isDone is false. what am i missing here?

scenic forge
#

Yes, and the smart way to enforce it is by leveraging the language and the compiler.
Nothing stops you from writing:

var levelTilemap = LoadLevelTilemap();
var dialogueData = LoadLevelDialogueData();
var enemies = CreateEnemies(levelTilemap);
var allies = CreateAllies(levelTilemap);
var dialogues = ProcessDialogues(dialogueData);
PositionGameObjects(enemies, allies);

Suddenly, if you attempts to call PositionGameObjects before enemies and allies have been created, you literally can't; or if you tried to create enemies without loading tilemap first, you can't.
On the flip side, it's immediately obvious that LoadLevelTilemap and LoadLevelDialogueData do not depend on each other (because they literally take in no argument) so you can parallelize them if performance is a concern.
Now you arrive at a system where the language and compiler enforces it for you, where there is no "early"/"late"/"pre"/"post" with conventions that programmers have to follow but no way to enforce.

upbeat path
unborn relic
cerulean wasp
#

like if I want to make a singleton just .Clear all of its lists OnLevelLoadEarly, that function would only take in an argument if I artificially made it such, at which point i’m just playing with function signatures

scenic forge
cerulean wasp
#

wdym

#

my singleton might not need a reference even to the tilemaps to know to clear its own lists

scenic forge
#

Like if you have a function that does FindObjectsOfType<T>(), that function very much has a hidden argument, it depends on the objects already being in the scene.

#

These hidden dependencies is the reason you have to enforce a convention such that "X is already loaded before you can call this function"

cerulean wasp
#

how else to I make .Clear() ing private collections depend more forcefully then?

scenic forge
#

By not allowing you to use these hidden global dependencies, and enforcing each machinery is just "takes some data, fiddle with it, spits out new data" it makes the dependency chain clear, and thus able to leverage the language and compiler to enforce it for you.

scenic forge
#

Key point here being private. If that data is later used by something else, then it's not private.

cerulean wasp
#

most of the contents of what is called is private

#

private, modifying private data

#

but that doesn’t mean it could not lead to some sort of actual dependency

scenic forge
#

Again you can still have an "level loaded" event, stuffs that do not matter to the loading can still listen to it and do whatever their own internal private data loading/cleaning as necessary.

cerulean wasp
#

i’ll need to think harder about this

scenic forge
#

Like if something has some private data (private means literally nothing else can observe it) then it does not matter whether it was cleared in "early" or "late" or "pre" or "post."

#

If it does matter when it was cleared, then it means it wasn't truly private.

unborn relic
#

Hello,

I saw that it is good practice to keep functionalities on a per scene level. Persistent managers = 1 scene, Different menus = different scenes, different worlds = different scenes etc..., and to additively load them on demand when needed.

My question is how to handle things like EventSystems / Global volumes, which can only exist once per scene.
Thus, if i have a scene main menu for example which i'm working on, it needs a global volume + event system, but so does a deungeon scene for example. But when I additively load one or the other Unity will complain. I could only have 1 and DontDestroyOnLoad(), but I still need them when working on individual scenes, and removing them every time I stop working on a scene seems like a chore.

How do people handle this type of stuff?

hushed fable
unborn relic
hushed fable
#

I don't know how they do it, but I don't keep the main menu around when loading to gameplay scenes.

#

If you do need to load multiple scenes, I would probably either have a primary scene that makes sure to load the scene I need (even in editor) or to have scripts load those dependencies in every scene that needs them if they are missing

#

Like Gameplay mode scene would load the map scene

frozen flax
#

What is the best way to find another client's player object if you know it's id? Unity NGO

frozen flax
livid kraken
finite sundial
livid kraken
#

!code

thorn flintBOT
unborn relic
kindred tusk
unborn relic
kindred tusk
#

Your can add multiple scenes in the editor

unborn relic
#

what a simple solution

#

thanks!!! ❤️

kindred tusk
#

Or you can write an editor script that listens for the play event

#

And loads the base scene

#

There's an event for entering play mode and you can load any scene that you need when you hit play

kindred tusk
# unborn relic thank you very much!

If you want to add this you can use the initialize on load attribute on a static class and subscribe to the play mode change event. Then you can use the editor scene manager to check if the scene you want is loaded and load it additively if not

fervent dagger
#

unable to resolve reference Microsoft.CodeAnalysis.Workspaces

fervent dagger
#

where do i get this from

Assembly 'Assets/nuget/Microsoft.CodeAnalysis.Workspaces.Common.4.9.0-2.final/lib/netstandard2.0/Microsoft.CodeAnalysis.Workspaces.dll' will not be loaded due to errors:
Unable to resolve reference 'SQLitePCLRaw.batteries_v2'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
#

0 packages returned for SQLitePCLRaw.batteries_v2

#

so far i has all these

tired fog
#

I need some help on getting a method called after a domain reload. I have some data that is private and instantiated through a method, but after it reloads the domain, the data gets lost

#

How could I get that method called again after the domain reload is finished?

#

I guess I need to do something seen here? https://docs.unity.cn/es/2021.1/Manual/DomainReloading.html

novel plinth
tired fog
#

Weird, it doesn't get called

tired fog
#

also this class has a [ExecuteInEditMode] attribute to also be called on edit mode

#

the before one does get called, but not the other one

sly grove
tired fog
#

With the [ExecuteInEditMode] it does when loading the scene, which is when it should subscribe to the event

#

Well, ended up doing a combination of OnValidate, OnEnable, and Start with some events, it sounds way more complicated that what it actually is. But i didnt really need to reload after assembly really, but after something else is called. So endedup doing it with events

cunning citrus
#

I need help, the next code it's supposted to save another boxhelp height on boxHelpHeight var, that works correctly, cause the log shows me the values changing... But when i try to apply the var's value to the right boxhelp it doesn't work... What could happen? The right boxhelp changes it's vertical size to a really small one and it doesn't do nothing with that code```csharp
boxHelpHeight = GUILayoutUtility.GetLastRect().height;
Debug.Log("BoxHelp Height: " + boxHelpHeight);

// RIGHT BOXHELP
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(boxHelpHeight), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.25f));

GUILayout.Space(2);
GUI.backgroundColor = new Color(46f / 255f, 204f / 255f, 113f / 255f);
propertyAdditionMenu.Draw();
GUILayout.Space(15);
GUI.backgroundColor = Color.white;

EditorGUILayout.EndVertical();```

unborn relic
#

how do you guys handle async event handlers? how do you unsubscribe an async event handler from an event?

scenic forge
unborn relic
scenic forge
#

You certainly do not need to subscribe with a lambda, and even with a lambda you can still unsubscribe it.

sly grove
#

unless you save the lambda to a variable

scenic forge
#

A lambda ultimately just compiles down to a C# method (with a capture class) anyways.

#

So you can do either:

  • Save the lambda to a variable, subscribe/unsubscribe that variable.
  • Write it as a method rather than lambda, subscribe/unsubscribe that method.
unborn relic
unborn relic
sly grove
#

that's just saying not to use lambdas

#

as mentioned

#

saving it to a variable works to unsubscribe if you keep that reference around outside the function

#

e.g. in a member variable

#

It has nothing to do with async

unborn relic
#

oh okay, understood. thanks a lot! will do that then

sly grove
#

I would just avoid lambda entirely to make it simpler

unborn relic
sly grove
#

Seems to work fine?

unborn relic
#

ah damn, okay, sorry guys i mussinderstood it seems. thanks a lot for your help guys @scenic forge @sly grove

midnight fiber
#

does any one have any experience with making melee combat ?

#

i dont want to make it using raycast cuz of that i had problems with blocking

fervent dagger
#

ooo

Start
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:9)

evaluating ...
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:10)

result = 3
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:12)
Debug.Log("Start");
Debug.Log("evaluating ...");
object result = CSharpScript.EvaluateAsync("1 + 2").Result;
Debug.Log("result = " + result);
native raven
#

Thinking of ways to do characters in my top down dungeon crawler. Came up with this idea so it can happen in runtime, but not too sure about it yet, still trying to wrap my head around how to do attacks. Any advice?

#

I just don't really know where to start with something like this

naive nexus
#

Hey guys, I came across an interesting problem and I didn't know what channel to post it in so I'll put it here 😅

While testing my game, I noticed something weird was happening with the player taking damage. Normally he does take damage fine but when the player presses the attack button right before he gets hit, he doesn't take any damage.

I double check the collision I had in the code but nothing was out of the ordinary. I have a interface called IDamageable that is currently on the Player Health and Character Guard script. I checked to make sure it wasn't accidentally grabbed guard script but it said (Debug.Log) said it was the parent GO which the guard isn't on but the health 😭

In the Console screenshot, you can see it grabs the first one four times and the second one twice. I'm not sure whatsoever what the problem is, DEFINITELY need another pair of eyes!

Thank you in advance!

native raven
#

unless the attack doesn't use colliders

cerulean sky
#

Hello!

#

I've had a problem since upgrading unity recently, my custom build script fails because it tries to copy the built data somewhere after the build except the data isn't there yet

#

After calling BuildPipeline.BuildPlayer , if I list the contents of the directory, I get every PDB and EXE, but the directories (MonoBleedingEdge and GameName_Data) are not there yet. They show up a few seconds later... This behaviour did not exist in Unity 2020: after calling BuildPlayer everything would be guaranteed to be there, now it's no longer the case

#

What function or event should I usee or subscribe to, to run code after the build has been completed and every folder/etc created?

upbeat path
#

@cerulean sky There is also the C# FileSystemWatcher class which may be use if the above does not work

cerulean sky
thorn flintBOT
cerulean sky
#

ah got it, there was a priority int to implement aswell. Thanks 🙂

earnest canopy
#

is here anyone that can help me to implement octree for my terrain system?

tiny pewter
#

you didnt tell us what are your problems....

gritty delta
#

Does anywhere here worked with LLM unity from GitHub?

open zealot
#

hi i need help .. can anyone suuggest what script or method can i use for saving collect gamobject in level and display on another scene

hushed fable
eager reef
#

Is there any way I could pass additional mesh data to the shader without associating it with the mesh vertices? My use case is, I'm rendering a voxel mesh and would like to pass an array of voxel ID's for the chunk to the mesh shader instead of storing voxel ID's inside each vertex

eager reef
#

Right, with settings a buffer of sorts inside the shader

#

My next question is, each chunk will have a unique set of blocks obviously, which means that buffer in the shader will need to be unique for each chunk

So how can I have that buffer property be per-instance?

hardy jacinth
#

How do I correctly generate shader and material in the runtime?

#

what I have currently (simplified):

[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[DisallowMultipleComponent]
[SelectionBase]
[ExecuteAlways]
public class SdfSceneController : MonoBehavior {
  [SerializeField] private Shader?   shaderAsset;
  [SerializeField] private Material? materialAsset;

  private void OnValidate() {
      if (shaderAsset == null) shaderAsset = ShaderUtil.CreateShaderAsset("// empty shader");
      if (materialAsset == null) materialAsset = new Material(shaderAsset);
      materialAsset.name = shaderAsset.name;
  }

  protected void OnEnable() {
      Renderer = GetComponent<MeshRenderer>();
      Renderer.sharedMaterial = materialAsset;
  }

  public void RebuildShader() {
      var shaderText = AssembleShaderSource();
      Debug.LogFormat("Shader code:\n---\n{0}\n---", shaderText);
      ShaderUtil.UpdateShaderAsset(shaderAsset, shaderText);
  }
  // + custom editor with a button for calling RebuildShader() method
}
#

and when running in editor and clicking RebuildShader it spams:

State comes from an incompatible keyword space
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
#

but when I run play the shader is generated and displayed correctly

austere jewel
#

At runtime? Afaik you can't.
ShaderUtil is in the Unity Editor assembly

hardy jacinth
#

maybe not in runtime, but in the editor so that the asset is not stored in project files and is only temporary when object is loaded or something

#

hmm, I think I would like to sometimes regenerate a shader in runtime when the game is actually playing

#

is it not possible?

austere jewel
#

I would be very wary about doing anything that isn't just basic maths in OnValidate

hardy jacinth
#

at least update their code

hardy jacinth
austere jewel
hardy jacinth
austere jewel
#

In OnValidate, so you move the functionality to the actual editor Update where there are less restrictions (might also have to check whether you're currently deferring to not double-up)

spiral grotto
#

I'm not a coder but I have a question that will probably have an advanced answer, and I'm not hopeless so I'll be able to probably understand the answer on a basic level enough to convey what needs done.

So preamble aside,

We are trying to munge multiple meshes from modular level design into larger single meshes, the current solution however had code munge multiple parts of scenes causing them to no longer be able to be edited.

Is there a way to tag things to munge or auto munge at the time of compiling/baking the game instead of in the scene files? So this way only the RC gets munged levels and the master scene files remain fully modular?

untold moth
#

If it's just for optimization purpose, unity static batching would do it for you automatically. Otherwise, you could hook to the build pipeline to perform preprocessing before the build.

kindred tusk
#

Having an issue with our build server where we get these errors after restoring the cached Library/ from an older buidl:

error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/ParsedHierarchy/Sequence.cs' could not be found.

error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/CharacterRange.cs' could not be found.

error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkRuntime/VariablesState.cs' could not be found.

error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/ParsedHierarchy/Choice.cs' could not be found.

error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkRuntime/Flow.cs' could not be found.

The issue seems to be that it's looking for verison 1.1.7 of the package, but we've since updated to 1.1.8. The error doesn't give more info about where these old file paths are referenced though.

I would expect everything to be updated by Unity before it started to build.

kindred tusk
#

Having an issue with our build server

tight ridge
#

Is anyone kind enough to help me on this Android build error? It's been 2 hours now that I'm trying to solve a build problem on Android, ChatGPT can't help me. I have this error on build :

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

FAILURE: Build failed with an exception.

  • Where:
    Build file 'E:\Unity\Unity_Projects\WEGames_1_MagicGrid\Library\Bee\Android\Prj\Mono2x\Gradle\unityLibrary\mobilenotifications.androidlib\build.gradle' line: 5

  • What went wrong:
    A problem occurred evaluating project ':unityLibrary:mobilenotifications.androidlib'.
    No signature of method: build_3ny7gyewinvf307n5slubpz6h.android() is applicable for argument types: (build_3ny7gyewinvf307n5slubpz6h$_run_closure1) values: [build_3ny7gyewinvf307n5slubpz6h$_run_closure1@64ca58f0]

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    Here's my gradle file:

    id 'com.android.library'
}

android {
    def unityLib = project(':unityLibrary').android // Use 'android' instead of 'extensions.getByName('android')'
    
    compileSdkVersion unityLib.compileSdkVersion // Directly use the compileSdkVersion property
    buildToolsVersion unityLib.buildToolsVersion

    defaultConfig {
        minSdkVersion 22
        consumerProguardFiles "proguard-rules.pro"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    bundle {
        language {
            enableUncompressedNativeLibs false
        }
    }
}

dependencies {
    api files('../libs/unity-classes.jar')
}```
misty glade
#

@untold moth I can't find the original thread but someone from Microsoft emailed me back and we were able to diagnose the VS/Unity hang I experienced before. Turns out you can still deadlock yourself if you're creative. As a "general warning" to whoever reads this (not sure where this nugget of information should best live.. a github gist?):

If you put a breakpoint on a line of code that a debug watch expression tries to evaluate (in the course of hitting that breakpoint), VS and Unity will hang pretty hard (deadlock/race condition). It's not as unlikely a scenario as you might first think - since if you use watch expressions to get to the bottom of a bug, you're likely to also have breakpoints "around" that functional area, deadlocking yourself out of your tools.

In my case, something was going wrong with my player loader, so I had a breakpoint at the beginning of the load command - but I had previously put a watch expression to show me the value of something in that player structure - which was also trying to load the player through the load command. The debugger and VS were competing and stuck on the same breakpoint. So uh.. don't do that. 🙂 Watch expressions are great but in visual studio, don't seem to play nice with breakpoints or conditional breakpoints.

untold moth
#

It tends to slow down your app considerably too, even if you don't run into a deadlock.

spring bear
#

I have done it like russian doll: Player prefab holds the scripts about movement and control and has a placeholder for actual character. Then character prefab is being instantiated in that placeholder. Character holds the scripts with stats and skills and so on and also has the placeholder for character 3d model. (In my case this is a must since I plan to switch the controllable characters and also to be able to swap models of those characters). I am still working on skill scriptable objects and still have no idea how to implement this so I am kinda stuck with this and switched to working on something different )

misty glade
# untold moth Ah, that explains it. It's basically the same as a race condition/multithreaded ...

Yeah I don't often use the expression evaluation in the watch window, but in this case I was needing access to a private member through a singleton so I did.. not realizing/remembering that evaluation of that expression would go through a breakpoint (and that's what broke). Conditional breakpoints and evaluated watches are really slow on performance, but sometimes they're the best way [for me] to find a buggy and spray it 🪳

timber flame
#

I have implemented a generic class to keep a runtime collection of some stuff with some methods (GetAll, GetById, Add, Remove, etc.)

Collection<T> where T:MonoBehaviour

First, have you defined something like it and second, in Get method, do you prefer to return the gameobject or T itself? Another question, which component of that gameobject/entity should be chosen? Because a gameobject contains several different components

upbeat path
#

btw you should always return T because T will give you gameObject but GameObject will not give you T

tiny pewter
#

You can write some method eg query by gameobject if you need all monbehaviour of one gameobject in your collection

#

Btw get components mono behaviour can also do that, though it may return some scripts that not in your collections

timber flame
#

The benefit of returning gameobject is that you can access components easily
How do you choose which component is the main/entry for a gameobject, so use it in spawn time or getting a gameobject through collection, etc.

upbeat path
timber flame
#

Callers can cache if they want

upbeat path
#

then what is the point of your collection at all?

tiny pewter
#

I think i know what you want, you have one mono behaviour and you want to get other mono behaviours

timber flame
#

For example a list of items, enemies, characters, buildings

upbeat path
#

you make no sense, you want a runtime collection but you dont want to cache, why?

timber flame
#
  public class Collection<T> where T : MonoBehaviour
        {
            public event Action<T> Added;
            public event Action<T> Removed;
        
            protected readonly Dictionary<Guid, T> ItemDictionary = new();

            public int Count()
            {
                return ItemDictionary.Count;
            }
        
            public T GetById(Guid id)
            {
                return ItemDictionary[id];
            }

            public bool TryGet(Guid id, out T item)
            {
                return ItemDictionary.TryGetValue(id, out item);
            }

            public IReadOnlyDictionary<Guid, T> GetAll()
            {
                return ItemDictionary;
            }

            public IReadOnlyList<TType> GetAll<TType>()
            {
                return ItemDictionary.Values.Select(item => item.GetComponent<TType>()).Where(item => item != null).ToArray();
            }

            public void Add(T item)
            {
                ItemDictionary.Add(item.GetComponent<Entity>().InstanceId, item);
                RaiseAddedEvent(item);
            }

            public bool Remove(T item)
            {
                return RemoveById(item.GetComponent<Entity>().InstanceId);
            }
            public bool RemoveById(Guid id)
            {
                var removed = ItemDictionary.Remove(id, out var item);
                if (removed)
                {
                    RaiseRemovedEvent(item);
                }
                return removed;
            }

            protected virtual void RaiseAddedEvent(T entity)
            {
                Added?.Invoke(entity);
            }

            protected virtual void RaiseRemovedEvent(T entity)
            {
                Removed?.Invoke(entity);
            }
        }
timber flame
#
 public GameObject GetById(Guid id)
            {
                return ItemDictionary[id];
            }
#

My concern is if a component of a gameobject is the main component and other classes work with it instead of gameobject itself, how do you consider it and select that component?

craggy spear
#

"main component" ?

wise tartan
#

Hey, I'm converting a byte that I get from a packet into an Enum using the code below:

reader.ReadByteSafe(out byte messageType);
receivedType = (MessageType)Enum.ToObject(typeof(MessageType), messageType); ```
Question: my `MessageType` currently has entries 0-3. What would happen if the byte received would equal 4 or any different number?
#

Would it throw an error or just create an invalid enum?

#

Nevermind, looked it up (shouldve done so in the first place) - apparently just has the enum represent a value equal to the int behind it 🤔

tiny pewter
#

you have tested it

enum ABCD{
    A=0,B=1
}
public static void Main(string[] args){
    Console.WriteLine ((ABCD)2);//2
    Console.WriteLine ((ABCD)1);//B
}
misty glade
#

I'm putting some of my game through a bit of a stress test for performance tuning.. but I'm not sure how to really proceed with the profiler. Here's a snap of a slow frame during the test.

It appears as if a lot of time is taken up with instantiate calls. Would pooling objects be a good way to reduce those calls?

#

here's a zoomed in instantiate.. there's a lot of textmeshpro items, but I don't know a way around that (we show little popup texts for score at the point of the score)

sly grove
#

that's taking up about equal time to the instantiates

#

same with the stuff on the right

misty glade
#

a lot of logic

sly grove
#

well maybe that logic can be optimized

misty glade
#

In a nutshell, it's a grid based game with a bunch of tiles of different types, and they all have various properties that determine how they move, interact with other tiles, destroy themselves or other tiles, etc

#

It probably can, but .. it's also just an awful big stress test .. lemme snap a quick vid

sly grove
#

I'd zoom into that stuff and see what's slow - it can likely be optimized

misty glade
#

The way I'm handling the logic now is to essentially recursively move each piece one at a time until it stops moving.. It could be changed to be smarter, but it turned out to be ridiculously complicated as I started to add tile types (like a tile that is destroyed by something moving "through" it but not stopping the original), or level shapes that aren't just grids

#

I don't think the 13x13 with 50+ tiles on the board at once will ever be a part of the final product.. I'm a little hesitant to try to poke at the premove and executemove parts of the method

#

They appear to be about 33% of the total processing time of that frame which seems ok

#

I am using a fair bit of LINQ in there though, maybe I should go to more traditional loop/finds

#

Actually, on the worst frame (one of them hit 625 ms) the game logic part of the frame is still small.. I don't think it's a great place to try to optimize

sly grove
misty glade
#

the execute move has the instantiates

sly grove
#

doesn't look like it

sly grove
#

that's going to be very inefficient/create lots of garbage

misty glade
#

Oh, sorry, you're try - it's in EndTurn()

#

Yeah, I think I could probably reduce the LINQ use

#

Lemme paste a couple snippets

sly grove
#

reducing/eliminating recursion will most likely help as well

misty glade
sly grove
#

there's nothing you can do with recursion that can't be accomplished with a Stack or Queue

#

yeah that switch is pretty inefficient

misty glade
#

I folded up a lot of the code to hopefully make it readable, but this should give the gist - recursively move each tile one space at a time

sly grove
#

especially since it seems like that code is probably running many times when it could be running once and the results reused?

misty glade
#

I don't think that matters - that particular switch only happens once per move.. I think the optimization would be in TryMoveOnce() since that happens 10,000+ times

#

wait, which switch?

#

in Premove()?

sly grove
#

in Premove

#

IDK how premove works

misty glade
#

Premove orders all the tiles (since they have to be processed from "frontmost" to back), then iterates over each, doing "tryMoveOnce()" until the tile is done moving

sly grove
#

this is a 1024 game?

misty glade
#

imagine an array like this: [ ]=[ ]=[ ]=[ ]=[ 1 ]=[ ]=[ 1 ]=[ ]=[ ]=[ ]

the "1" on the right moves first until it hits a wall, then the "1" on the left moves until it hits the other tile (which is now at the wall) and then they both merge into a 2

#

yeah, it's a 1024-ish game

#

but my spin on it is a lot of custom tile types

sly grove
# misty glade

Ok. Yeah I'd have to think a lot about the most optimal way to do this. What are all these ToLists from in the profiler if not Premove?

misty glade
#

the tolists are probably in the TryMoveOnce - I folded up all those "ifs" but a lot of them are doing shit like this:

#

ie - using where in LINQ instead of for'ing over the collections

#

I'm assuming (or recall vaguely?) that .Where() has an implicit ToList

#

Should I look at using something like BenchMark.NET for this? I'm .. having a hard time sorta telling where I should spend my optimization energy

#

Like, I can't tell from the profiler what the "sum" of a given method execution time is over several frames.. i can peel apart one frame but it's hard to get big picture from this

sly grove
#

Don't we really only care about one frame at a time?

misty glade
#

true

sly grove
#

over several frames sum isn't really that relevant

sly grove
misty glade
#

I also see a really high amount of GC use.. is that.. actionable..?

sly grove
#

It definitely still creates an IEnumerable though

misty glade
#

sure, one sec

sly grove
misty glade
#

oh wait, nevermind, i mixed up the colors, it's "other"

#

the puke color of "others" is too close to the brown of GC

#

is there any tip you have to make this profiler hierarchy a little easier to read/navigate? not exactly sure what I'm looking for but it's a little hard to navigate

#

here's the whole frame

#

lemme try to notate it

tall ferry
misty glade
#

i think that linq area is a lot of FirstOrDefault shit

tall ferry
misty glade
#

oh yeah this is way more productive

tall ferry
#

Expand it even further, itll eventually tell you GC.alloc and anything else that's causing issues

#

For the big areas

misty glade
#

so basically EndTurn, Premove, and ExecuteMove are all roughly taking 1/3 of the frame, so at least I can peel apart each of those and figure out the best way to optimize

#

cooooool, this is much better

tall ferry
misty glade
#

so firstOrDefault is taking a bit of time, 15 ms.. i could optimize there, instantiate takes 23ms, don't know what I can do to optimize that

#

my initialize function is also taking 11ms which is surprising to me

#

that should just be trivial

#

hard to see any obvious optimizations here, now that we're getting down to the 1-5ms amount, but I do see that I've left the UpdateDebugText() in there, and the ToString() can probably be cached or optimized, that shouldn't take 2ms.. etc..

#

anyway, this is actionable now, thanks

#

this is also cool since it already shows me what I thought I needed from Benchmark.NET - the total amount of calls in the recursion

#

tryMoveOnce only called 318 times.. much less than I would have guessed

#

oh wow, i found a super easy thing to fix..

#

basically in the "try move once" (the 318 calls) I check to see if there's anything in the destination by iterating the entire grid until it finds something in that location instead of caching/storing items

sly grove
#

yep

#

keep going like that

#

I see a lot of your code seems to be iterating the whole grid

misty glade
#

making a hashset of tiles on the grid and then looking up their positions will be much faster... or alternatively i could tackle the frog of just making the GridPoint (a custom struct with an X and Y) implement the appropriate interfaces to be used as a key itself.. so I could TryGetValue on that key instead of iterating an entire dictionary of 13^2 items 318 times

sly grove
#

revisit whether that's always necessary

misty glade
#

yeah - in general I tend to not optimize logic like this because it's often not necessary, and with all the tile types and "domain logic" of my game, making these methods more readable and less bug prone is important to me

#

but this is a totally acceptable/easy fix.. like 2 lines of code

#

should take 40ms off of the frame

dusty wigeon
misty glade
#

these objects aren't unity objects

#

just naked classes

#

I even wrote an API on this grid to prevent myself from doing stupid shit

sly grove
#

Why use Instantiate then?

misty glade
#

so I don't even need to change anything on the unity side, I can just cache these items and rebuild the cache manually or whatever

dusty wigeon
#

Strange, I would have expected to see some instantiate there and there. At least, this is what the profiler looks like.

misty glade
#

the game client needs to instantiate the tiles after all the processing is done

sly grove
# misty glade

Those properties are convenient but will be inefficient if used a lot

#

those OfType things

misty glade
#

yep, that's what I'm changing

#

I don't mind a little extra data use here - caching some of the various types

#

it makes the logic a bit easier to read but .. yeah, doing the oftype or firstordefault repeatedly/recursively is clearly slow

#

it lets me write code like this, though, which I think is bug-resistant because it reads a bit like english:

#

and all my tile classes have the abstract/polymorphism/interface thing going on to implement their own behaviour (and nothing else)

#

but then as a side effect, i need quick ways to get sets of tiles with some qualifier at the grid level, like "all destroyable tiles" or "all mergeable tiles" or "all number tiles" or whatever, and building that on the fly isn't cheap

dusty wigeon
#

There is nothing wrong with doing that. Code should be self explanatory.

misty glade
#

what do you guys like the API for something like this to look like? I don't use this pattern often (where I give the power to rebuild the cache externally)

misty glade
#

something like that

sly grove
#

I would personally use the TryGet Pattern rather than a Nullable but I'd say that's a matter of preference.

misty glade
#

Hm.. I feel like there was a reason I adopted this pattern.. maybe something to do with blazor/razor and nullable types .. but I can't recall

#

I do like the tryget pattern better overall

dusty wigeon
#

I am not really fan of nulluable as well.
I also really like the proxy pattern. (for everything cache)

unborn relic
#

hello, i am loading some scenes additively when needed in the editor via the EditorApplication.playModeStateChanged event.
but after doing so and leaving play mode, the additively asdded scene gets removed. is there any way to keep it there? (additively added to my scene, just like if it were drag and dropped there by me)

cerulean wasp
#

every time I try returning null for a fail state, it just leads to spaghetti

terse oyster
#

Help! Any idea why?

#

In that place shoud be "Play"

fresh salmon
terse oyster
#

and what can I do?

fresh salmon
misty glade
scenic forge
#

Using null to represent failed state is fine if you have NRT turned on. The problem with using null to represent failed state isn't that it by itself is a bad idea, but that C# type system does not help you keep track of it, unless you turn on NRT. In languages with type system that was built with that in mind, it's hardly a problem and try pattern doesn't need to exist. (Try pattern also has some minor ergonomic issues both for the implementer and the caller)

#

State of null in C# is generally quite unfortunate and especially worse in Unity. I did migrate to NRT a few weeks ago and it does feel worth it, but the process was painful.

bleak citrus
#

the "billion dollar mistake", indeed

unborn relic
#

if I have an event being raised in a file somewhere in an addon, let's say /Assets/Plugins/Foo/bar.cs invokes a UnityAction<int> in a class called Baz and a method called Bat. Is there any way I can override that from a script inside my scripts folders, so that when I update the unity package, my change doesnt interfere with the update?

PS: i must do this because the package in question raises an event, while I need it to raise an event that is encapsulated in a scriptable object so that i can share it between scenes

sly grove
unborn relic
sly grove
#

Isn't the point of your SO to bridge such reference gaps?

#

Have that script reference the SO to inform it about the event being fired.

unborn relic
unborn relic
unborn relic
untold moth
#

Original event -> SO -> SO event -> listener

#

Or rather original invoker -> call a method on SO -> SO invokes an event -> listener

unborn relic
untold moth
#

Or maybe avoid the SO entirely..? Are both scenes loaded at the same time?

unborn relic
unborn relic
untold moth
#

So the event that you want to forward is not at real time..?

unborn relic
untold moth
#

And you want to listen to it from where?

unborn relic
#

that one handles the loading screens / progress bars, so it needs to know when the loaded scene is ready to be shown

untold moth
#

Ah. Is it a DDOL scene?

unborn relic
untold moth
#

How are they persistent then..?🤔

unborn relic
#

or sorry, if you mean metaphorically then yes

#

i imagine scenes cannot be ddol-ed right?

untold moth
#

No. But when you make an object DDOL it is moved to a DDOL scene automatically.

unborn relic
#

ah okay. the GO's within the persistent managers scene are not DDOL, but the scene itself I one I just keep around for all scenes basically

#

the reason I don't ddol the managers inside yet is because im not sure whether ill need them for ALL scenes in the future

untold moth
#

So you're loading other scenes additively?🤔

untold moth
#

I see.

#

Anyways, if the managers are always present, you probably don't even need an SO. Just call a method on your manager from the proxy script.

unborn relic
#

but for some reason I like the event re-invokation option a bit more

#

seems like it's a bit less tightly coupled

#

@untold moth thank you very much for your patience and great answers

untold moth
#

To be honest there's nothing advanced about that question though. Maybe ask in #archived-code-general next time.

unborn relic
#

will do!

dreamy pasture
#

Hey! I'm trying to forward my camera feed to my locally running python server, how would one go about sending/extracting the camera feed?

Instead of streaming the video do I have to send it frame by frame? I understand all the websocket stuff I'm more curious about the Unity side of things since I'm a beginner

dreamy pasture
#

I want to use OpenCV in a way where the video feed it receives comes from my unity app instead of a physical webcam

tiny pewter
#

afaik opencv requires frame data not some compressed stuffs, that mean you have to feed it with frames, btw isnt you still need a phyiscal camera?
dont know python, so difficult

sly grove
#

There seem to be some OpenCV related assets on the asset store - not without a cost though

sage radish
dreamy pasture
#

Yep, localhost only

#

also always on the same port

sage radish
#

You could try reading the texture data directly from GPU memory

dreamy pasture
#

oh boy 😂

#

Is that as compliacted as it sounds?

tiny pewter
#

open cv is written in cpp so you may write a plugin without any network traffic

dreamy pasture
dreamy pasture
#

I mean it can't be that hard right? I'm reading the code of flightmare simulator which is a quadcopter/drone simulator that does the exact same thing, where in unity the video is exported and is passed into computer vision software

#

This is a code snippet, there seems to be a render method where a Texture2D is created

#

What exactly is that? Is it an in image, or what exactly?

noble granite
#

So this is a really wierd question, but would it be possible to compile shaders during a game’s runtime?

#

Rather than at build

sly grove
noble granite
#

The former, more or less

sly grove
#

If that's possible it will be very difficult. The Unity core engine definitely doesn't ship with a shader compilation pipeline built in

noble granite
#

Yeah, I know

#

It more of an experiment

#

Just to see if I can do it

sly grove
#

You want to make ShaderToy more or less?

noble granite
#

Fully aware it’s not practical lol

noble granite
#

I’ll look into it

#

One sec

sly grove
#

realtime writing shaders and visualizing them immediately

#

really fun web app 😛

noble granite
#

Sort of, id still like to be able to apply them to materials and such

sage radish
#

The closest you can get to runtime compiled shaders is to write a native graphics plugin to submit commands directly to OpenGL/DirectX/Vulkan. But that bypasses Unity's Shader/Material system.

noble granite
#

I see

#

Anyway, thanks

sage spindle
#

I have a custom mesh, which is a cube, how can I get the center position for one of the faces? I can do it with a unity cube but not a custom mesh. The gizmo will spawn inside it. With Unity primitive cube: Vector3 spherePosition = transform.position + transform.right * transform.lossyScale.y / 2f; Gizmos.color = Color.yellow; Gizmos.DrawSphere(spherePosition, 1);

dusty wigeon
sage spindle
#

No it is 5 units

sly grove
#

but yeah if your middle-of-face is 2.5 units away it would be:

Vector3 knownOffset = Vector3.forward * 2.5f;
Vector3 worldSpaceLocationOfFace = transform.TransformPoint(knownOffset);```
#

that would be the "front" face

#

for the top face use Vector3.up, for the right face Vector3.right, and so on

zealous summit
#

I'm writing a custom saving system with player prefs and trying to make a list of my PlayerPrefsData generic class so that I can access and modify all settings with ease. The problem is with compering the type of PlayerPrefsData witch is a generic class. Is there a way to store all generic classes as field types in a list like this?

    public PlayerPrefsData<float> SoundsVolumeSetting = new("SoundsVolumeSetting", 1f);
    public List<FieldInfo> AllSettings { get; private set; } = new();

    private void DefineAllSettings()
    {
        foreach (FieldInfo fieldInfo in typeof(SettingsManager).GetFields())
        {
            if (fieldInfo.GetType() == typeof(PlayerPrefsData<>))
            {
                AllSettings.Add(fieldInfo);
            }
        }
    }

    public void SetSetting<T>(string key, T value) where T : IComparable
    {
        GetSetting<T>(key).Set(value);
    }

And here is the troublesome line:

if (fieldInfo.GetType() == typeof(PlayerPrefsData<>))
sly thunder
#

Help plz
I'm facing a challenge in my project using Quest 2 and Hand Tracking 2, where manipulated objects pass through others instead of interacting. When trying to move an object towards another, it doesn't stop but goes through. I use Unity and seek guidance to configure realistic collision detection between objects. I appreciate any assistance from the community to enhance this experience.

Best regards,

sly thunder
#

okay!

zealous summit
misty glade
# zealous summit I'm writing a custom saving system with player prefs and trying to make a list o...

If you wanna do something more robust (baby steps towards networking/compression/modular save files) google up MessagePack - it's a doozy of a first step to wrap your head around how it works, but then at the end you can convert anything to/from a byte[] and send it over the network, save it to a file, put it in a playerpref string field, etc. Once you get it set up, you just annotate your fields and it does the rest.

#

Alternatively if you want something more readable/editable/easier to start/, you can serialize to json, stuff that into a single string, and put into player prefs

#

and even easier, if all your settings have a ToString() and a ctor that can hydrate the object from a string, you could just ToString() everything and store that in a player prefs field

zealous summit
#

thanks! I did some research on player prefs based systems and couldn't find anything much useful. Now I have something to read

misty glade
#

MessagePack is a pretty heavy duty tool for what you're likely looking to do, but it's.. a really useful thing to know how to use so .. if you can get over the learning curve (feel free to @ me - no DMs though) it's pretty useful for nearly anything you want to save/load

zealous summit
#

JSON seems really decent for saving, but I'm building a game for WebGL and I'm not sure how it runs on it. Will do more research on saving for this platform, but wanted to have an easy to work with solution already

misty glade
#

JSON is probably your best step if you're just starting with this sort of tech, since it's easy to debug and edit during dev.. and you can use both at the same time (I do) if you need

scenic forge
#

MessagePack isn't the only option either, it's just data serialization, you can do it with JSON, BSON, MessagePack, FlatBuffers, whatever.

misty glade
#

ProtoBuf too

#

or even ini files

#

I have one of those libraries kicking around.. such an ancient format

scenic forge
#

It doesn't make much difference which one you choose, especially if you don't need to communicate with a different app and is entirely read/write within your own game.

#

At that point you can literally just slap on Unity's JsonUtility and that will be all.

misty glade
scenic forge
#

Your original question doesn't have much to do with data serialization tbh, but you are looking for a way to find all serialized values

#

I would generally not recommend doing it with reflection like you did.

misty glade
#

unpopular opinion: i sorta like INI formatting over JSON

scenic forge
misty glade
#

none!

#

it just looks nice. :p

#

JSON is way more functional but .. is also just a bit noisy.. for flat/simple/non-collection data types, I feel like INI files are underrated 😛

#

(I don't actually use it very often but I did for one project, and it was pretty successful)

#

the project had an IP address and version number that I wanted to be able to set/read easily without doing builds

scenic forge
#

That doesn't really matter though, the de/serializer should be opaque to your code.

misty glade
scenic forge
#

The only difference is if you are editing it by hand.

misty glade
#

which I was for this.. it would just bit a few extra bits of nonsense for a JSON config file

#

but INI files are probably best left in the 90s 🙂

scenic forge
#

From a practical standpoint, JSON is supported by practically everything, while INI you either need to bring in a library or slap one together (granted it's very easy to do) but there's also no formal spec for INI, so it's not a feasible long term solution either.

thin mesa
signal pelican
#

I have a question, will provide more info if needed, but imagine deforming a simple plane by setting the vertex heights to random numbers. I'm trying to do this on a plane mesh I imported from blender, and I'm getting a noticeable tilt into the top right direction in the patterns like so:

#

something up with the triangles or uvs that could be causing this effect, as i'm not touching them

#

I'm going to guess it has something with the vertex order in blender being different than in unity and something is off in the loop

valid shale
#

Define "tilt" ?

signal pelican
#

it's got like a terrainish texture on it right now, you can see how all the green stuff streaks from bottom left to top right

#

and it's like that for every seed, so it doesn't appear truly random

untold moth
#

Is the issue that they appear in a diagonal pattern?

valid shale
#

I assumed the green parts were the brown terrain clipping through a base plane.

untold moth
#

Yeah, it's not clear entirely what the issue is and what should we be paying attention to.
@signal pelican please provide some clarification.

signal pelican
#

It's just a simple terrain shader I threw together, green being lower heights, brown being higher heights, here is the same plane with a default white material

#

like the folds are all pointing north east

valid shale
#

Are you driving the heights from a noise function?

signal pelican
#

i was and it wasn't working, so i just went back to using one call to random like so: vertices[i].y = UnityEngine.Random.Range(1f, 5f);

#

and the result is still that

#

i mean the noise i was using was working but it was also stretching like the purely random one is stretching

#

the lague noise tutorial works fine, so i'm sure it's just some weird thing with looping through the vertices incorrectly

#

if you subdivide a plane in blender the center is vertex index of 0

valid shale
#

Do the same type of artifacts appear if you try different seed values?

signal pelican
#

but im still not really sure why vertex order would matter for a completely random assignment

#

yeah

valid shale
#

Are you post-processing the height value at all? E.g. smoothing

signal pelican
#

none that i can see, in the same scene i have bits of lague's terrain gen working and producing results that id expect

#

but he makes the mesh on the fly, im using a subdivided plane from blender

valid shale
#

Hmm yeah that's weird then. I wouldn't expect those types of artifacts to be showing up given pure random height values. Can you try and just set every 2nd vertex to height 3 and all others to 1 or something? Make sure you get the expected results.

austere jewel
#

Just to confirm, this isn't just an artifact of the lighting direction is it?

signal pelican
#

i'm not sure? i can remove the lighting and it still looks liek that

#

i do recalculate normals call after assigning the random values

austere jewel
#

you're going to have to post some code I think

signal pelican
#

here is the side to side comaprison

#

the one on the right is from lague's tutorial with noise and octaves and all that good stuff and just a quick shader i put on

#

so same lighting conditions

valid shale
#

Maybe your base mesh is being rotated/scaled weirdly before you put height values on it since it's coming in from blender?

Also if it works fine with the procedural mesh why not just use a procedural mesh?

signal pelican
#

im using dreamtek's forever engine

#

and i like how it extrudes paths

#

and it also extrudes meshes

#

but i havent figured out how to extrude a procedurally generated mesh in forever

#

so im adding a basic subdivided mesh from blender, the forever engine is bending the plane, and then i deform the plane after with noise

#

that was the plan anyway lol

valid shale
#

You're deforming the plane after it's being bent? Are you accounting for the curved surface in your deformation?

signal pelican
#

well these current examples are not bent

untold moth
# signal pelican

You wouldn't get the left side image with just random number though. It would be more like white noise.

#

So there must be something extra you're doing on the plane.

#

Otherwise you wouldn't get smooth height changes.

signal pelican
#

ive commented a bunch of stuff out so the only thing on the left example that's going right now is:

#

for (int i = 0; i < vertices.Length; i++) {
    vertices[i].y = UnityEngine.Random.Range(1f, 5f);
}

mesh.vertices = vertices;
mesh.RecalculateNormals();
untold moth
#

Ah, maybe it's due to normals recalculation that it looks smooth🤔

signal pelican
#

I appreciate the look guys, i was maybe thing something obvious wuold jump out but the seb lague one on the right is working so ill figure it out

#

ill have to redo the brakceys one for like the 5th time i wonder if it happens on his

austere jewel
#

Without testing it, I think it might just do that if you have such a small or random scale on a mesh that has its triangles set like that

untold moth
#

I guess the issue is that you loop all the vertices like that. It probably reveals some kind of pattern

signal pelican
#

yeah the only thing conceptually that's throwing me off is that the order shouldn't really matter in any way

#

whether i'm saying the 0th height is 6.3 or the 97th height etc

austere jewel
#

It matters if the random has biases and you're experiencing them; but it's probably not visually dense enough to see that

valid shale
#

Yeah the order won't matter if you're using random heights. It will matter for noise based heights though.

untold moth
signal pelican
#

appreciate the look guys, ill figure it out

austere jewel
#

Can you show the result with something that's actually got larger gradients, not just what is practically white noise?

untold moth
#

I'd also love to see a 2d version(rendered to a texture) of it.

#

It's very useful to have a 2d setup for testing when working with noise and other type of procedural generation

austere jewel
#

Just picture a quad that's two triangles, raise any one corner and you're going to experience a gradient on the triangles on the diagonal

#

but if you're actually raising the sides reasonably to form a gradient over a larger distance then you're not going to see that, because the whole mesh expresses a real shape

#

not just white noise on geometry

terse oyster
#

Hi! Is there any way to allow each user to choose if want personalized ads or not?

long ivy
#

You're forced to give them a choice on ios via ATT. You hope they don't figure it out on android (via denying access to idfa). Are you actually contemplating giving them that choice? Because it's a weird one if you're trying to monetize at all

untold moth
#

Pretty sure google requires you to give them a choice as well for the app to get published.

long ivy
#

it's an install-time permission disclosed in the store, you don't have to actively ask like ios... yet

untold moth
#

Hmm... Did something change in the last few years? Pretty sure I was forced to implement a popup prompt in an android game I worked on a few years ago.

#

Maybe it was to be aligned with the iOS port that someone else worked on.🤔

long ivy
#

only thing that changed is that you used to not have to declare the ad id permission at all, but google has been steadily increasing privacy requirements for the past couple years. If your popup was functional and actually turned off tracking (and was respected by ad sdks), you spent dev time generating negative value :(

untold moth
#

Well, that was a requirement from the client. And it's not their first game on the story, so I don't know. Anyways, it's a matter long forgotten.

terse oyster
untold moth
#

What are you using for ads?

somber tendon
shadow shore
#

when I serialize an instance of a scriptableobject to a json file and then deserialize it in another session, it says the object then cannot be instantiated. Is there a way of storing a scriptable object where I can avoid this?

#

I will make my github public for a min so people can help me out

thin mesa
#

at least have the courtesy of linking directly to where your issue is instead of making everyone else try and find your issue

shadow shore
#

I'm working on it

#

sorry was a temp link while i got everything made public

#

CharacterStats is the SO that i need to instantiate from a json

thin mesa
#

ah there it is. you're serializing references to a ScriptableObject.
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html

If the object contains fields with references to other Unity objects, those references are serialized by recording the InstanceID for each referenced object. Because the Instance ID acts like a handle to the in-memory object instance, the JSON string can only be deserialized back during the same session of the Unity engine.

shadow shore
#

I must be missing something obvious as all the other SO's I need to instantiate seem to be fine?

shadow shore
#

I'm not intending to serialize a reference at all

thin mesa
shadow shore
#

each character has an instantiated Stats so we can have different stats for multiple characters based on the same SO

shadow shore
thin mesa
#

now go look at the actual json that is produced and look at what it shows for those CharacterStatsKeyValuePair instances

shadow shore
#

exactly what you said it would

#

the instance ID

thin mesa
#

yes because you are serializing an object that has a reference to the SO, which is a UnityEngine.Object

shadow shore
#

ah... how can I store that dictionary without using a reference then? do I just manually copy all the values into equivalent vars in the CharacterStatsDictionary rather than directly using CharacterStats?

#

I've been using a lot of non-unity c# classes in my project so forgive me for assuming it should act the wrong way

thin mesa
shadow shore
#

i will try doing exactly that

#

moved all of the basic stats to "raw character stats", and i'm just pointing these vars to them

#

or should I be directly accessing them everywhere like rawCharacterStats.

thin mesa
#

naw, making them properties like that is the way to go. i don't know why you've made them private though

shadow shore
#

yeah i changed em to public i just noticed that

#

habit

#

getting a few errors but the json is looking very promising. annoyed with myself that i didn't think to just extract these properties but its good that its halfway there already

shadow shore
#

alright it's all working! 🎉

#

now to do this for the items too

stuck plinth
#

Index accesses itself

#

public int Index => (Index + 1) % list.Count; this getter is accessing itself

#

you probably meant to have Index and NextIndex as separate properties?

obsidian glade
#

what do you think happens when you access Index?

#

you're not overwriting anything, that's only a getter

tired wyvern
#

When using Graphics.DrawMesh() or DrawMeshInstanced(), what strategies are there for raycasting against these meshes? I know drawMesh() doesn't interact with the physics system..

some background:
I'm writing a factory game where belts, etc are all represented in data as NativeArrays/etc so I can use jobs. So DrawMesh would be really practical here. However, the player must be able to interact with factory objects to e.g. add belts, delete machines, etc.

sage radish
#

What they do here is when the player clicks, they render the whole scene with a special shader that renders each object with a different color, then reading back the color of the pixel under the cursor to identify which object it belongs to.
Rendering the whole scene to read back one pixel is a bit overkill though. You could pretty easily render the scene with a super narrow FOV focusing only on where the mouse is and render it to a 1x1 texture, saving you a lot of GPU time.

tired wyvern
tired wyvern
#

Any other strategies you can think of? It looks complicated/time consuming to implement. What I thought of:

  • spawn gameobjects with colliders in the area the player is focused on (game is on a 3D grid)
  • raycast and find which 3D grid points it goes through, then check data on whether those grid points contain objects.
  • or maybe just use gameobjects to render instead. Have a system that creates/destroys gameobjects as the data is changed. gameobject has an id that references the data it is rendering.
sage radish
tired wyvern
#

Now that I think about it, I need to discern the sides of the grid. If the mouse is on the top side, place object above, etc

sage radish
tired wyvern
#

I think I'm gonna start with just using game objects to render. I've shot my foot more than once in the past not keeping it simple.

As the game design settles, I'll know my requirements and performance bottle necks better. Then it might be worth it going the shader or grid traversal route.

tired fog
#

im tryinng to find leaks on my jobs code

#

and got this leak, that i understand says that at line 241, theres a leak with a float4 array

#
0x0000017fdc2743cb (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float4>:Allocate (int,Unity.Collections.Allocator,Unity.Collections.NativeArray`1<Unity.Mathematics.float4>&)
0x0000017fdc2742b3 (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float4>:.ctor (int,Unity.Collections.Allocator,Unity.Collections.NativeArrayOptions)
0x0000017fdc283203 (Mono JIT Code) sapra.ProceduralGeneration.WorldGeneration.WorldChunkGenerator:ScheduleParallel (sapra.ProceduralGeneration.TerrainConfig,sapra.ProceduralGeneration.GenerationInstance,sapra.ProceduralGeneration.WorldGeneration.PointOfInterestData,sapra.ProceduralGeneration.DisposableArrays,Unity.Jobs.JobHandle) (at F:/Projects/Coding/Personal/TerrainGenerator/Assets/sapra.ProceduralGeneration/Runtime/_WorldGeneration/ScriptableObjects/WorldChunkGenerator.cs:241)
#

however going to that line, thats not there

#
//Generate the weight chain
NativeArray<float4> VegetationChained =  new NativeArray<float4>(vegLength*vertices.Length, Allocator.TempJob, NativeArrayOptions.ClearMemory);
NativeArray<JobHandle> vegetationWeights = new NativeArray<JobHandle>(VegetationPacksWithID.Count, Allocator.Temp);
for(int i = 0; i < VegetationPacksWithID.Count; i++){
    VegetationWithID vegID = VegetationPacksWithID[i];
    JobHandle vegetationLayers = CreateVegetationTextures.ScheduleParallel(vertices, vegID.ID, vegID.vegetationSettings,
        FinalWeightsChained, VegetationChained, mesh.settings.Resolution, i, finalTextureJob);
    vegetationWeights[i] = vegetationLayers;
}
JobHandle WhenWeightsDone = JobHandle.CombineDependencies(vegetationWeights);
vegetationWeights.Dispose();
#

any idea on what am i missing or could look at?

#

I can assume that the problem comes from the line above, where there's actually a float4 , but im more concerned on why it doesnt match

long ivy
#

well, do you actually dispose VegetationChained somewhere?

flint sage
#

I'm guessing the line changed because your code changed at some point

#

Or maybe it's a bug

tired fog
tired fog
livid sapphire
#

Hello. I have a problem. When assembling bundles in Addressable, the RAM overflows and the assembly is not assembled. How can this be fixed? In one place I read: "I solved that by creating binary files containing all label data for each tile and added the binary file as TextAsset to the prefab, reducing the file size of all prefabs to 280 MB. So the build process worked again.". But I don't know how to do this. Please, Help me.

violet shoal
#

That comment is describing a solution where they reduce the complexity of how much they are trying to bundle.

valid shale
#

I'm curious how "RAM overflows"

woeful steeple
#

so im coding a rhythm game, and im wondering how i could get the note spawning effect to work?

upbeat path
bleak citrus
#

i'm guessing this means "it ran out of memory and gave up"

upbeat path
#

no, overflow is trying to access more memory than you allocated

#

like a bounds violation

bleak citrus
#

right, that's the proper definition, but I'm guessing this was just an OOM problem

#

since i've never seen someone say "RAM overflow", haha

#

if I saw "buffer overflow" or "buffer overrun", I'd be much more confident that it was a bounds violation

upbeat path
#

there is such a thing, or at least there was as a RAM overflow back in the good old days where you reached the end of physical memory and just went back and started writing to the start of memory. This was a very bad thing as that was where the OS was loaded, but I very much doubt if that is the case here

bleak citrus
#

ah, true, especially when you were working with physical memory addresses

upbeat path
#

and 8bit processors

bleak citrus
#

i implemented a toy operating system in college that used segmented 16-bit addresses, so it wouldn't be that hard to run off the end and come back to zero

upbeat path
#

Win 3.1 did it all the time on the i386

gentle yew
#

I'm expecting it to be a byte[] of the entry, but I guess something else is on top of that and I can't figure it out for hours now... documentation is seriously lacking here

fresh salmon
#

Byte stream at first sight: application/octet-stream
There's a content-disposition header which includes info on what is being streamed (file name and extension)

#

If all else fails, save it to a file, and upload it to a file format recognizer online

gentle yew
#

Hm, I'll try that, thanks for the help @fresh salmon

woeful steeple
#

good day?

fresh salmon
#

See #854851968446365696 for instructions on how to ask a good question, and make sure to post it in the appropriate channel

gentle yew
#

At least I know what's happening now, thanks once again

half swan
#

I think they mean just having the note icons visually appear on the screen.
But I have no idea, so you could definitely be right

woeful steeple
#

honestly i have 10% of a clue of what im doing

thorn flintBOT
#

:teacher: Unity Learn ↗

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

half swan
lilac lantern
#

Is there a way to quit the standalone application in a way that indicates an error occurred? Or should I just call Application.Quit() in my catch block.

lilac lantern
#

Will that actually stop the application though? Isnt it running in native code?

upbeat path
#

read it

lilac lantern
#

I did. I’m not sure if it will because the application is not running in c#.

upbeat path
#

what?

lilac lantern
# upbeat path what?

The unity runtime environment is not running in c#. Therefore I am not sure if this will work.

#

you write your scripts in c# but the engine is in c++

upbeat path
#

I think you need to learn how Unity, C# and Computers in general actually work

lilac lantern
#

I asked a question and you told me to read it. I explained why i asked that question. I know how c# works, i know how computers “in general” work. I do not know what calling Environment.Exit will do when the whole process is not written in c#, which is why I asked.

upbeat path
#

do you know what an Application Domain is?

lilac lantern
#

Yup

upbeat path
#

then what is the problem? Environment.Exit exits an Application domain, the language that that domain is written in is irrelevant

lilac lantern
#

On the documentation you linked it says it returns an exit code to the operating system, not that it exits the application domain. I was unsure of how that would work if the operating system didnt start the process, which i think is a valid question.

upbeat path
#

that is the same thing which you would know if you knew how anything running under Windows worked

lilac lantern
#

Love the superiority complex attitude i get whenever I ask a question in this server 👍

#

Don’t need to know every single thing about something to know “anything” about something

upbeat path
#

you profess knowledge which you obviously do not have

lilac lantern
#

Knowing what an app domain is different knowledge than knowing what returning an exit code to the operating system does when while in a script

#

And a process can have multiple domains, so even if the domain is exited unity could still be running right?

upbeat path
#

no it cannot, an Application can only have 1 domain